我正在做一个程序来打开,写入和读取端口ttyUSB0,我有下一个程序,我什么都不写。任何人都可以帮我吗?打开,写入和读取ttyUSB0
我的问题是,我有写或读功能的问题,因为我不能读写ttyUSB0端口,我搜索解决方案来写和读ttyUSB0端口。
#include <sys/time.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <termios.h>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
using namespace std;
int serial_open(char *serial_name, speed_t baud)
{
struct termios newtermios;
int fd;
fd = open(serial_name,O_RDWR | O_NOCTTY);
newtermios.c_cflag= CBAUD | CS8 | CLOCAL | CREAD;
newtermios.c_iflag=IGNPAR;
newtermios.c_oflag=0;
newtermios.c_lflag=0;
newtermios.c_cc[VMIN]=1;
newtermios.c_cc[VTIME]=0;
cfsetospeed(&newtermios,baud);
cfsetispeed(&newtermios,baud);
if (tcflush(fd,TCIFLUSH)==-1) return -1;
if (tcflush(fd,TCOFLUSH)==-1) return -1;
if (tcsetattr(fd,TCSANOW,&newtermios)==-1) return -1;
return fd;
}
void serial_send(int serial_fd, char *data, int size)
{
write(serial_fd, data, size);
}
int serial_read(int serial_fd, char *data, int size, int timeout_usec)
{
fd_set fds;
struct timeval timeout;
int count=0;
int ret;
int n;
do {
FD_ZERO(&fds);
FD_SET (serial_fd, &fds);
timeout.tv_sec = 0;
timeout.tv_usec = timeout_usec;
ret=select (FD_SETSIZE,&fds, NULL, NULL,&timeout);
if (ret==1) {
n=read (serial_fd, &data[count], size-count);
count+=n;
data[count]=0;
}
} while (count<size && ret==1);
return count;
}
void serial_close(int fd)
{
close(fd);
}
int main(int argc, char *argv[])
{
int serial_fd, n, longitud,;
char *device=”at”;
char *data;
longitud=strlen(device);
serial_fd = serial_open("/dev/ttyUSB0",B38400);
if (serial_fd == -1) {
printf ("Error opening the serial device: %s\n",argv[1]);
perror("OPEN");
exit(0);
}
printf("SERIAL OPEN:%s\n", device);
serial_send(serial_fd, device, longitud);
printf ("String sent------> %s\n",device);
n=serial_read(serial_fd,data,longitud,10000);
printf("Se ha recibido %s \n Tamaño: %d\n n:%d \n serial_fd:%d\n",data, longitud,n,serial_fd);
puts(data);
serial_close(serial_fd);
// cout << "Hello world!" << endl;
return 0;
}
执行['read'(http://man7.org/linux/man-pages/man2/read.2.html)或['写'](http://man7.org/linux/man-pages/man2/write.2.html)系统调用返回一个错误代码?你有没有检查错误是什么?总是检查错误,并*错误是什么(通过检查['errno']完成(http://man7.org/linux/man-pages/man3/errno.3.html),使用[ 'perror'](http://man7.org/linux/man-pages/man3/perror.3.html)或者使用['strerror']获取一个字符串(http://man7.org/linux/man-页/ man3/strerror.3.html))。 –
随着开放我返回一个'3',与写我不会返回任何东西,并阅读我返回一个'0',这'0'是我没有收到任何东西 – Igor
当'read'返回零时,它意味着“连接”已关闭,或已达到“文件结束”。你真的需要检查'写'返回。并且所有其他系统调用(以及* do *记得在系统调用返回失败时检查'errno'(例如'-1'))。 –