博客
关于我
串口数据交互(树莓派)
阅读量: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/

你可能感兴趣的文章
php curl_init函数用法(http://blog.sina.com.cn/s/blog_640738130100tsig.html)
查看>>
php curl_multi批量发送http请求
查看>>
php curl请求微信发红包接口出现错误:Peer's Certificate issuer is not recognized.
查看>>
PHP curl请求错误汇总和解决方案
查看>>
php declare(ticks=1)
查看>>
UVA 10474
查看>>
php echo 输出 锘?... 乱码问题
查看>>
PHP empty、isset、isnull的区别
查看>>
ReferenceQueue的使用
查看>>
PHP FastCGI进程管理器PHP-FPM的架构
查看>>
referenceQueue用法
查看>>
Springboot处理跨域的方式(附Demo)
查看>>
php flush()刷新不能输出缓冲的原因分析
查看>>
Referenced classpath provider does not exist: org.maven.ide.eclipse.launchconfig
查看>>
Refactoring-Imporving the Design of Exsiting Code — 代码的坏味道
查看>>
PHP imap 远程命令执行漏洞复现(CVE-2018-19518)
查看>>
php include和require
查看>>
ref 和out 区别
查看>>
php JS 导出表格特殊处理
查看>>
php json dom解析
查看>>