i want read and write data from serial port in Ubuntu
Download port Driver Form this side
https://www.silabs.com/products/mcu/Pages/USBtoUARTBridgeVCPDrivers.aspx
write Code in c
#include <stdio.h>
#include <string.h>
#include <unistd.h> //UNIX Standard function definitions
#include <fcntl.h> //File control
#include <errno.h> //Error number def
#include <termios.h> //POSIX terminal control
#include <termio.h>
int open_port(){ //-1 is a error
int port = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);
/*O_RDWR POSIX read write
O_NOCTTY: not a "controlling terminal"
O_NDELAY": Ignore DCD signal state*/
if(port == -1){
perror("open_port: Unable to open /dev/ttyS0 - ");
}else fcntl(port, F_SETFL, 0);
return (port);
}
int set_port(int port){
struct termios options;
tcgetattr(port, &options);
cfsetispeed(&options, B9600); //Typical way of setting baud rate. Actual baud rate are contained in the c_ispeed and c_ospeed members
cfsetospeed(&options, B9600);
options.c_cflag |= (CLOCAL|CREAD);
options.c_cflag &= ~CSIZE;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~PARENB;
options.c_cflag |= CS8; //No parity, 8bits, 1 stop bit (8N1)
options.c_cflag &= ~CRTSCTS;//CNEW_RTSCTS; //Turn off flow control
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); //Make sure that Canonical input is off (raw input data)
options.c_iflag &= ~(IXON | IXOFF | IXANY); //Turn off software control flow
options.c_oflag &= ~OPOST; //Raw output data
options.c_cc[VMIN] = 0;
options.c_cc[VTIME] = 10;
return tcsetattr (port, TCSANOW, &options); //Make changes now without waiting for data to complete.
}
int main(){
int fd, n;
unsigned char byte = 0x0F;
unsigned char buff[255];
int ready;
fd = open_port();
set_port(fd);
//n = write(fd, &byte, 1);
n = write(fd, ":010317D1000A0A\0", 16);
if (n < 0) fputs("write() failed!\n", stderr);
usleep(1000000); //Wait for 1 sec
ioctl(fd, FIONREAD, &ready);
printf("Bytes in input buffer: %d\n\n", ready);
fcntl(fd, F_SETFL, FNDELAY); //Return read immidiatly
n = read(fd, buff, 255);
printf("Byte Read: %d\nByte received: %d %d %d\n\n", n, buff[0], buff[1], buff[2]);
close(fd);
return 0;
}
code is Note Working properly
Write data is ":010311B900010A"
Read data like that ="1021012001201020000012ADFF0000"
Thanx in advance