1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
|
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <error.h>
#include <stdlib.h>
int main(void)
{
int fd, result;
char buffer[255];
struct termios options, storedOptions;
if((fd = open("/dev/ttyUSB1", O_RDWR | O_NOCTTY) == -1))
{
perror("ERROR (device not opened) ");
exit(EXIT_FAILURE);
}
else
{
if(fcntl(fd, F_SETFL, 0) == -1)
{
perror("ERROR (device problem) ");
exit(EXIT_FAILURE);
}
if(tcgetattr(fd, &options) == -1)
{
perror("ERROR (port configuration problem) ");
exit(EXIT_FAILURE);
}
storedOptions = options;
// baudrate
if(cfsetispeed(&options, B4800) == -1 || cfsetospeed(&options, B4800) == -1)
{
perror("ERROR (baudrate setting) ");
exit(EXIT_FAILURE);
}
// enable receiver
options.c_cflag |= CREAD | CLOCAL;
// line oriented mode
// (notice : be careful to desactivate ECHO before sending something to the devive)
options.c_lflag |= (ICANON | ECHO | ECHOE);
options.c_oflag |= (OPOST | NL1 | CR2);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_iflag = IGNPAR;
options.c_cc[VMIN] = 1;
if(tcsetattr(fd, TCSANOW, &options) == -1)
{
perror("ERROR (port configuration setting) ");
exit(EXIT_FAILURE);
}
int nodataCnt = 0;
while(nodataCnt < 200)
{
result = read(fd, buffer, 255);
perror("ERROR? "); // keep returning "Success"
// read fail
if(result == -1)
{
perror("ERROR (read process) ");
exit(EXIT_FAILURE);
}
// no data
if(!result)
{
printf("no data\n");
nodataCnt++;
}
// data received
if(result > 0)
{
buffer[result] = 0;
printf("string : %s number : %d\n", buffer, result);
}
}
tcsetattr(fd, TCSANOW, &storedOptions);
close(fd);
}
return EXIT_SUCCESS;
} |
Partager