68 lines
1.7 KiB
C++
68 lines
1.7 KiB
C++
#include "serial_io.h"
|
|
|
|
struct termios toptions;;
|
|
|
|
void sWrite(int port, char string[], size_t length)
|
|
{
|
|
if(port != -1) write(port, string, length);
|
|
else std::cout<<string;
|
|
}
|
|
|
|
void sWrite(int port, const char string[], size_t length)
|
|
{
|
|
if(port != -1) write(port, string, length);
|
|
else std::cout<<string;
|
|
}
|
|
|
|
ssize_t sRead(int port, void *buf, size_t count)
|
|
{
|
|
return (port != -1) ? read(port, buf, count) : 0;
|
|
}
|
|
|
|
int serialport_init()
|
|
{
|
|
int fd;
|
|
system("stty -F /dev/ttyUSB0 38400 sane -echo");
|
|
fd = open(DEVICE, O_RDWR | O_NOCTTY | O_NDELAY);
|
|
if (fd == -1)
|
|
{
|
|
perror("init_serialport: Unable to open port ");
|
|
return -1;
|
|
}
|
|
|
|
if (tcgetattr(fd, &toptions) < 0)
|
|
{
|
|
perror("init_serialport: Couldn't get term attributes");
|
|
return -1;
|
|
}
|
|
speed_t brate = BAUDRATE;
|
|
cfsetispeed(&toptions, brate);
|
|
cfsetospeed(&toptions, brate);
|
|
// 8N1
|
|
toptions.c_cflag &= ~PARENB;
|
|
toptions.c_cflag &= ~CSTOPB;
|
|
toptions.c_cflag &= ~CSIZE;
|
|
toptions.c_cflag |= CS8;
|
|
// no flow control
|
|
toptions.c_cflag &= ~CRTSCTS;
|
|
|
|
toptions.c_cflag |= CREAD | CLOCAL | IGNPAR; // turn on READ & ignore ctrl lines
|
|
toptions.c_iflag &= ~(IXON | IXOFF | IXANY); // turn off s/w flow ctrl
|
|
|
|
toptions.c_lflag &= ~(ICANON | ISIG | ECHO | ECHOE); // make raw
|
|
toptions.c_oflag &= ~OPOST; // make raw
|
|
|
|
// see: http://unixwiz.net/techtips/termios-vmin-vtime.html
|
|
toptions.c_cc[VMIN] = 0;
|
|
toptions.c_cc[VTIME] = 20;
|
|
fcntl(fd, F_SETFL, FNDELAY);
|
|
|
|
if( tcsetattr(fd, TCSANOW, &toptions) < 0)
|
|
{
|
|
perror("init_serialport: Couldn't set term attributes");
|
|
return -1;
|
|
}
|
|
return fd;
|
|
}
|
|
|