Azrael7
Azrael7

Reputation: 21

Read serial input to a C variable

Hi I am trying to read serial input (from an Arduino) from a C- program. I am able to send data to the Arduino using

system("echo -n \"data\" > /dev/ttyUSB0");

but I cannot figure out how to get an input from the same Arduino to a string in the c-program (which is to be processed within the program). How do i do this?

Upvotes: 1

Views: 1200

Answers (2)

Eddy Sorngard
Eddy Sorngard

Reputation: 181

Reading 255 bytes from /dev/ttyUSB0 at baud rate 230400:

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

#define BAUDRATE B230400

void main() {
   int fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY);
   struct termios options;
   tcgetattr(fd, &options);
   cfsetispeed(&options, BAUDRATE);
   cfsetspeed(&options, BAUDRATE);
   options.c_cflag |= (CLOCAL | CREAD);
   tcsetattr(fd, TCSANOW, &options);

   if (fd == -1)
       printf("Cannot open port /dev/ttyUSB0\n");
   char buf[255];
   int n = read(fd, buf, sizeof(buf));
   printf("%d bytes read\n%s\n", n, buf);
}

Upvotes: 0

junix
junix

Reputation: 3211

There is no point in calling system for such communication. You can access the serial port pretty much like a file by using the functions open, read, write ioctl and close.

Just pass /dev/ttyUSB0 to open as the file to be opened. You only need ioctl in case you want to modify the connection settings (like baudrate or parity or stuff)

You can have a look at http://www.tldp.org/HOWTO/Serial-Programming-HOWTO/index.html for details.

Upvotes: 5

Related Questions