Code:
#include <stdio.h> // standard input / output functions
#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 definitionss
#include <time.h> // time calls
#include <sys/ioctl.h>
#include <linux/serial.h> // Здесь описана serial_icount_struct
int fd;
int open_port(void)
{
int iret;
int fl_flags;
fd = open("/dev/ttyS0", O_NONBLOCK | O_RDWR);
if(fd == -1) // if open is unsucessful
{
printf("open_port: Unable to open /dev/ttyS0. \n");
return -1;
}
else
{
fl_flags = fcntl(fd,F_GETFL);
iret = fcntl(fd, F_SETFL, FNDELAY);
// iret = fcntl(fd, F_SETFL, fl_flags & ~O_NONBLOCK);
if (iret)
printf("Error fcntl %s\n", strerror(errno));
printf("port is open.\n");
// Переведем устройство в exclusive mode
iret = ioctl(fd, TIOCEXCL, 0);
if (iret < 0) {
return -1;
};
return 0;
}
}
int configure_port()
{
int iret;
struct termios port_settings; // structure to store the port settings in
iret = tcgetattr(fd, &port_settings);
if (iret)
printf("Error tcgetattr %s\n", strerror(errno));
cfsetispeed(&port_settings, B110); // set baud rates
cfsetospeed(&port_settings, B110);
/* cfsetispeed(&port_settings, B9600); // set baud rates
cfsetospeed(&port_settings, B9600);
port_settings.c_cflag &= ~(CSIZE | CSTOPB | PARENB | CLOCAL);
port_settings.c_cflag |= CS8 | CREAD | HUPCL;
port_settings.c_iflag = IGNBRK | IGNPAR;
port_settings.c_oflag = 0;
port_settings.c_lflag = 0;
port_settings.c_cc[VMIN] = 1;
port_settings.c_cc[VTIME] = 10;
*/
port_settings.c_iflag = IGNBRK | IGNPAR;
port_settings.c_oflag = 0;
port_settings.c_lflag = 0;
port_settings.c_cc[VMIN] = 1;
port_settings.c_cc[VTIME] = 10;
port_settings.c_cflag &= ~PARENB; // set no parity, stop bits, data bits
port_settings.c_cflag &= ~CSTOPB;
port_settings.c_cflag &= ~CSIZE;
port_settings.c_cflag |= CS8;
port_settings.c_cflag |= (CLOCAL | CREAD);
iret = tcsetattr(fd, TCSANOW, &port_settings); // apply the settings to the port
return 0;
}
int read_write()
{
unsigned char send_bytes[] = {'h','e','l','l','o'};
char buffer[5];
int n_write = write(fd, send_bytes, 5); //Send data
printf("Wrote the bytes. \n");
usleep(10000000);
int n_read=read(fd,buffer,1);
if (n_read == -1)
printf("Error read %s\n", strerror(errno));
printf("read %d bytes. \n", n_read);
// bufptr=buffer;
// while((n_read=read(fd, bufptr, buffer+sizeof(buffer)-bufptr-1))>0)
//{
// bufptr+=n_read;
//}
printf(buffer);
return 0;
}
int main(void)
{
open_port();
configure_port();
read_write();
close(fd);
return(0);
}