需要在虚拟机上设置关于串口的东西吗?还是直接打开两个终端就可以啦?
想在虚拟机Linux Ubuntu上实现串口的自发自收功能,
#include <termios.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#define MAXSIZE 1024
#define FAILE -1
#define SUSSESS 0
int main(int argc, char* argv[])
{
struct termios opt;
char buf[MAXSIZE];
int fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);//打开串口
cfsetispeed(&opt, B9600);//设置波特率,使用函数cfsetispeed、 cfsetospee
cfsetospeed(&opt, B9600);
tcflush(fd, TCIOFLUSH);//处理要写入的引用对象
tcsetattr(fd, TCSANOW, &opt);//激活配置。
fcntl(fd, F_SETFL, 0);//恢复串口的状态为阻塞状态,用于等待串口? isatty(STDIN_FILENO);//测试打开的文件描述府是否引用一个终端设备,以进一步确认串
memset(buf, 0, sizeof(buf));
printf("请输入要发送的内容\n");
for (;;)
{
int len = write(fd, buf, 1024);
if (len == 0)
return -1;
sleep(1);
}
}
这样设置发送可以吗?
接收的程序:
#include <termios.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#define MAXSIZE 1024
#define FAILE -1
#define SUSSESS 0
int main(int argc, char* argv[])
{
struct termios opt;
char buf[MAXSIZE];
int fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);//打开串口
cfsetispeed(&opt, B9600);//设置波特率,使用函数cfsetispeed、 cfsetospee
cfsetospeed(&opt, B9600);
tcflush(fd, TCIOFLUSH);//处理要写入的引用对象
tcsetattr(fd, TCSANOW, &opt);//激活配置。
fcntl(fd, F_SETFL, 0);//恢复串口的状态为阻塞状态,用于等待串口? isatty(STDIN_FILENO);//测试打开的文件描述府是否引用一个终端设备,以进一步确认串
memset(buf, 0, sizeof(buf));
while(1) {
if((nread = read(fd,buff,1024))>0){
buff[nread] = '\0';
printf("\nrecv:%d\n",nread);
printf("%s",buff);
}
}
}