Writing STRINGS to serial port in C++ linux

Asked
Active3 hr before
Viewed126 times

10 Answers

serialwritingstrings
90%

OK, you need to stop looking at the code now. Connect your serial port to another port on another box and use a terminal app to read what is being sent in both these cases, (which should be the same, but are not). – Martin James Feb 18 '12 at 12:29 ,I'm happy to solve my own solution but yet disappointed to not have seen the trivial matter much sooner. char by default are signed in c++, which makes it holding the range -128 to 127. However, we are expecting the ASCII values which are 0 to 255. Hence it's as simple as declaring it to be unsigned char str[] and everything else should work. Silly me, Silly me. ,note: the loop is to use user input from console. What i need is a way to send a string variable to the serial port., @rve, thanks, but I solved my problem. In regard to your solution, i even tried hard coding the exact value (4) which is suppose to work and it still doesn't. But thanks, really. Anyways, please see my updated question, it has the solution. I can't post it as a solution for now, cause i dont have enough reputation points. – haikalpribadi Feb 18 '12 at 13:18

After your edit you wrote:

char str[] = {
   0x56,
   0x45,
   0x52,
   0x0D
};
write(tty_fd, str, strlen(str));
88%

Output Modes (c_oflag),Now that we have opened and configured the serial port, we can read and write to it!,First we want to include a few things:,Writing to the Linux serial port is done through the write() function. We use the serial_port file descriptor which was returned from the call to open() above.

// C library headers
#include <stdio.h>
   #include <string.h>

      // Linux headers
      #include <fcntl.h> // Contains file controls like O_RDWR
         #include <errno.h> // Error integer and strerror() function
            #include <termios.h> // Contains POSIX terminal control definitions
               #include <unistd.h> // write(), read(), close()
load more v
72%

"Blocking" sets whether a read() on the port waits for the specified number of characters to arrive.

load more v
65%

Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.,Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question. ,This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

. / send

root @oviserver - desktop: /home/oviserver / shanmugam #. / send
Oviya 3
enter write
Start send
FIle sent successfully 44 bytes

   . / receive

oviserver @oviserver - System - Product - Name: /home/sathish$. / receive
oviya: 3
1 h
1 i
1

1 w
1 e
1 l
1 c
1 o
1 m
1 e
1

1 t
1 o
1
75%

On Linux, I want to send a command string (i.e. some data) to a serial port (containing control characters), and listen to the response (which also usually might contain control characters). ,An intermediate solution, would use a terminal program like screen which will work on a serial device.,Your message is sent to the second cat from stdin, and the first cat relays the response to stdout, turning your terminal into a chatroom.,One has to make sure of course that (i) the serial settings (speed, word length, flow ctrl, etc) are correct and (ii) the serial device (on the other end) is not blocking.

You will want read.write access, if this is a shared system then you should consider the security consequences of opening it up for everyone.

chmod o + rw / dev / ttyS1

A very simple crude method to write to the file, would use the simple echo command.

echo - ne '\033[2J' > /dev/ttyS1

and to read

cat - v < /dev/ttyS1

Equivalent commands.

stty 19200 < /dev/ttyS1
stty 19200 - F / dev / ttyS1

An intermediate solution, would use a terminal program like screen which will work on a serial device.

screen / dev / ttyS1
load more v
40%

Writing Data to the Port,Opening a Serial Port,Listing 1 - Opening a serial port. ,Closing a Serial Port

Listing 1 - Opening a serial port.

#include <stdio.h>   /* Standard input/output definitions */
#include <string.h>  /* String function definitions */
#include <unistd.h>  /* UNIX standard function definitions */
#include <fcntl.h>   /* File control definitions */
#include <errno.h>   /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */

/*
 * 'open_port()' - Open serial port 1.
 *
 * Returns the file descriptor on success or -1 on error.
 */

int
open_port(void)
{
  int fd; /* File descriptor for the port */


  fd = open("/dev/ttyf1", O_RDWR | O_NOCTTY | O_NDELAY);
  if (fd == -1)
  {
   /*
    * Could not open the port.
    */

    perror("open_port: Unable to open /dev/ttyf1 - ");
  }
  else
    fcntl(fd, F_SETFL, 0);

  return (fd);
}
load more v
22%

Writes binary data to the serial port. This data is sent as a byte or series of bytes; to send the characters representing the digits of a number use the print() function instead., Doubts on how to use Github? Learn everything you need to know in this tutorial. ,write() will return the number of bytes written, though reading that number is optional. Data type: size_t.,Serial: serial port object. See the list of available serial ports for each board on the Serial main page. val: a value to send as a single byte. str: a string to send as a series of bytes. buf: an array to send as a series of bytes. len: the number of bytes to be sent from the array.

void setup() {
   Serial.begin(9600);
}

void loop() {
   Serial.write(45); // send a byte with the value 45

   int bytesSent = Serial.write("hello"); //send the string "hello" and return the length of the string.
}
60%

I'm using LibSerial on Ubuntu to read and write data on serial port.,I've solved my problems, so I post here the correct code in case someone needs similar stuff.,At the moment, I'm able to write and receive strings over the serial port, but my code does not work very well: in particular, I'd like to control the reading function in order to read only if there is something to read and exit when there is no information to read in order to send another command without bloicking the flow program.,These serial ports are shown in my system and the user who want to run the application should be under group dialout. To add yourself, use:

load more v
48%

Linux serial port 1.5 стоп-биты , Как установить нестандартную скорость передачи данных на устройстве serial port на Linux? , Моделировать serial port , Как вы проверяете, открыт ли serial port в Linux?

Примечание: цикл предназначен для использования пользовательского ввода с консоли. Что мне нужно, так это способ отправить строковую переменную в serial port.

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>

int main(int argc,char** argv){
    struct termios tio;
    struct termios stdio;
    int tty_fd;
    fd_set rdset;

    unsigned char c='D';

    printf("Please start with %s /dev/ttyS1 (for example)\n",argv[0]);
    memset(&stdio,0,sizeof(stdio));
    stdio.c_iflag=0;
    stdio.c_oflag=0;
    stdio.c_cflag=0;
    stdio.c_lflag=0;
    stdio.c_cc[VMIN]=1;
    stdio.c_cc[VTIME]=0;
    tcsetattr(STDOUT_FILENO,TCSANOW,&stdio);
    tcsetattr(STDOUT_FILENO,TCSAFLUSH,&stdio);
    fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);       // make the reads non-blocking

    memset(&tio,0,sizeof(tio));
    tio.c_iflag=0;
    tio.c_oflag=0;
    tio.c_cflag=CS8|CREAD|CLOCAL;           // 8n1, see termios.h for more information
    tio.c_lflag=0;
    tio.c_cc[VMIN]=1;
    tio.c_cc[VTIME]=5;

    tty_fd=open(argv[1], O_RDWR | O_NONBLOCK);      
    cfsetospeed(&tio,B115200);            // 115200 baud
    cfsetispeed(&tio,B115200);            // 115200 baud

    tcsetattr(tty_fd,TCSANOW,&tio);

    //char str[] = {'V','E','R','\r'};
    //the above str[] doesn't work although it's exactly the same as the following
    char str[] = {0x56, 0x45, 0x52, 0x0D}; 
    write(tty_fd,str,strlen(str));
    if (read(tty_fd,&c,1)>0)
        write(STDOUT_FILENO,&c,1);

    while (c!='q')
    {
            if (read(tty_fd,&c,1)>0)        write(STDOUT_FILENO,&c,1); // if new data is available on the serial port, print it out
            if (read(STDIN_FILENO,&c,1)>0) 
                if(c!='q')
                    write(tty_fd,&c,1);        // if new data is available on the console, send it to the serial port
    }

    close(tty_fd);
}
load more v
23%

Writes data to the serial port output buffer.,Writes a specified number of bytes to the serial port using data from a buffer.,Writes a specified number of characters to the serial port using data from a buffer.,Writes the specified string to the serial port.

public:
   void Write(System::String ^ text);
public:
   void Write(System::String ^ str);
public void Write(string text);
public void Write(string str);
member this.Write: string - > unit
member this.Write: string - > unit
Public Sub Write(text As String)
Public Sub Write(str As String)
load more v

Other "serial-writing" queries related to "Writing STRINGS to serial port in C++ linux"