文章目录
前言
第一次用串口连接两台Linux设备进行通行,慢慢的还要在串口通信的基础上实现其他的通信协议,看别人的开源代码已经看得神魂颠倒,神志不清,差点在暴毙的边缘了,该好好整理一下串口编程的一些基本知识了,帮助自己疏通一下
设备说明:
Ubuntu 1404:使用USB转串口
树莓派:直接使用接杜邦线的物理串口
串口编程
俗话说Linux下一切设备皆文件,接触越多越是能切身体会到这一点,
termios结构体
串口编程参考博文
树莓派端
test.c如下:
#include "serial.h"
#include <stdio.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <stdlib.h>
int main()
{
SerialPort self;
int portNo=0;//在结构体uart_dev[]数组中第一个元素才是树莓派的路径名
int rt=0;
char buf[512];
char *str="I am Raspberry!";
self=SerialPort_create(portNo,115200,8,'N',1);
rt=SerialPort_open(self,portNo);
if(rt<0)
{
printf("at line %s open serial failture!\n",__LINE__);
return -1;
}
while(1)
{
memset(buf,0,sizeof(buf));
rt=SerialPort_readByte(self->fd, buf,sizeof(buf));
if(rt<0)
{
printf("at line %s read port failture!\n",__LINE__);
close(self->fd);
return -2;
}
printf("read %d bytes from buf is:%s\n",rt,buf);
sleep(3);
memset(buf,0,sizeof(buf));
memcpy(buf,str,strlen(str));
rt=SerialPort_write(self->fd, buf,0,strlen(str));
if(rt<0)
{
printf("at line %s write port failture!\n",__LINE__);
return -3;
}
printf("send %d bytes to buf is:%s\n",rt,buf);
}
return 0;
}
Ubuntu 1404端
test.c
#include "serial.h"
#include <stdio.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <stdlib.h>
int main()
{
SerialPort self;
int portNo=1;//在结构体uart_dev[]数组中第二个元素才是Ubuntu 1404 USB转串口的路径名
int rt=0;
char buf[512];
char *str="I am Ubuntu!";
self=SerialPort_create(portNo,115200,8,'N',1)