1.半双工和全双工
全双工:允许通信双方同时互传数据;
半双工:在一方发送时,另一方只能接收。
串口通信工作方式为:
全双工
通过串口通信可实现:
多机通信
2.初次使用树莓派串口通信需要配置
cd /boot/
sudo vim cmdline.txt
删除
console=serial0,115200
修改后内容即如下所示:
dwc_otg.lpm_enable=0 console=tty1 console=serial0,115200 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait
目的:解除串口用于信息的打印,打印启动字符以及一些调试界面等。目的是把串口用于正常的数据通信
然后重启
sudo reboot
3.树莓派常用串口通信API
使用时需要包含头文件:#include <wiringSerial.h>
int serialOpen (char *device, int baud) |
device:串口的地址,在Linux中就是设备所在的目录。 默认一般是”/dev/ttyAMA0″,我的是这样的。 baud:波特率 返回:正常返回文件描述符,否则返回-1失败。 |
打开并初始串口 |
void serialPutchar (int fd, unsigned char c) |
fd:文件描述符 c:要发送的数据 |
发送一个字节的数据到串口 |
void serialPuts (int fd, char *s) |
fd:文件描述符 s:发送的字符串,字符串要以’\0’结尾 |
发送一个字符串到串口 |
int serialDataAvail (int fd) |
fd:文件描述符 返回:串口缓存中已经接收的,可读取的字节数,-1代表错误 |
获取串口缓存中可用的字节数。 |
int serialGetchar (int fd) |
fd:文件描述符 返回:读取到的字符 |
从串口读取一个字节数据返回。 如果串口缓存中没有可用的数据,则会等待10秒,如果10后还有没,返回-1 所以,在读取前,做好通过serialDataAvail判断下 |
void serialClose (int fd) | fd:文件描述符 | 关闭fd关联的串口 |
示例代码:
#include<wiringPi.h>
#include<stdlib.h>
#include<stdio.h>
#include<wiringSerial.h>
int main()
{
int fd;
int cmd;
int a=wiringPiSetup();
if(a==-1){
printf("System error!\n");
exit(-1);
}
fd=serialOpen("/dev/ttyAMA0",9600);
while(1){
while(serialDataAvail(fd) != -1){
cmd = serialGetchar(fd);
if(cmd == '2'){
serialPuts(fd,"cmd = 2!\r\n");
}
if(cmd == '3'){
serialPuts(fd,"cmd = 3!\r\n");
}
if(cmd == '4'){
serialPuts(fd,"cmd = 4!\r\n");
}
}
// serialPuts(fd,"lit-1010!\r\n");
// delayMicroseconds(1000000);
}
serialClose(fd);
return 0;
}
向串口依次发送2 3 4 4
版权声明:本文为Li_t0010原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。