博客
关于我
串口数据交互(树莓派)
阅读量:710 次
发布时间:2019-03-21

本文共 1260 字,大约阅读时间需要 4 分钟。

树莓派串口配置与开发指南

本文将详细介绍树莓派串口的配置方法以及与之相关的功能开发。

一、串口配置

树莓派的UART功能在不同型号上有所不同。在树莓派3上,由于蓝牙和UART分别使用了硬件外设,这会导致串口配置需要特别注意。为了解决树莓派3的串口频率不稳定问题,可以选择关闭蓝牙模块,将UART重新分配给GPIO串口。

二、接线说明

按照R-T, T-R顺序,用USB转TTL模块连接引脚15和引脚16。

三、文件修改

在命令行中编辑文件:
sudo vi /boot/cmdline.txt
删除或注释掉`console=serial0,115200`这一行。

四、系统重启

sudo reboot

五、相关功能函数

本文提供了几个常用的串口操作函数:

1、打开并初始化串口

指定设备地址和波特率进行初始化:
int serialOpen (char *device, int baud) { // device参数为串口设备路径,默认为"/dev/ttyAMA0" // baud为波特率 return open(device, O_RDWR | O_NONBLOCK); }

2、发送字符串到串口

void serialPuts (int fd, char *s) { // fd是文件描述符,s需以'\0'结尾 write(fd, s, strlen(s)+1); }

3、获取串口缓存数据量

int serialDataAvail (int fd) { return fcntl(fd, F_GETFL) & O_W discriminator; }

4、读取单个字符

int serialGetchar (int fd) { return read(fd, &c, 1); }

六、程序实现示例

开发中常用的串口通信功能包括数据发送和接收。

1、发送数据到主机

#include
#include
int main() { int fd; wiringPiSetup(); fd = serialOpen("/dev/ttyAMA0", 9600); while(1) { serialPuts(fd, "hen shuai\r\n"); delayMicroseconds(1000000); } return 0; }
串口助手的波特率需与程序设置一致,本例为9600bps。

2、串口数据通信

#include
#include
#include
int main() { int fd; int cmd; wiringPiSetup(); fd = serialOpen("/dev/ttyAM0", 9600); while(1) { while(serialDataAvail(fd) != -1) { cmd = serialGetchar(fd); printf("接收到数据: %d\n", cmd); } } return 0; }
树莓派3
串口配置
UART
波特率
C语言
编程示例

转载地址:http://owoez.baihongyu.com/

你可能感兴趣的文章
Nginx+Django-Python+BPMN-JS的整合工作流实战项目
查看>>
Nginx+Keepalived+LVS集群实战
查看>>
Nginx+Keepalived实现简单版高可用主备切换
查看>>
Nginx+Lua 开发高性能Web应用实战
查看>>
nginx+mysql+redis+mongdb+rabbitmq 自动化部署脚本
查看>>
nginx+php的搭建
查看>>
nginx+tomcat+memcached
查看>>
nginx+tomcat单个域名及多个域名配置
查看>>
Nginx+Tomcat实现动静分离
查看>>
nginx+Tomcat性能监控
查看>>
nginx+uwsgi+django
查看>>
nginx+vsftp搭建图片服务器
查看>>
Nginx-http-flv-module流媒体服务器搭建+模拟推流+flv.js在前端html和Vue中播放HTTP-FLV视频流
查看>>
nginx-vts + prometheus 监控nginx
查看>>
Nginx/Apache反向代理
查看>>
Nginx: 413 – Request Entity Too Large Error and Solution
查看>>
nginx: [emerg] getpwnam(“www”) failed 错误处理方法
查看>>
nginx: [emerg] the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf/nginx.conf:
查看>>
nginx:Error ./configure: error: the HTTP rewrite module requires the PCRE library
查看>>
Nginx:objs/Makefile:432: recipe for target ‘objs/src/core/ngx_murmurhash.o‘解决方法
查看>>