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

你可能感兴趣的文章
python day10
查看>>
Python Day17 Django 03
查看>>
python day21
查看>>
python decode和encode
查看>>
Python del 语句
查看>>
Python Dict 理解创建和更新字典
查看>>
Python Discord Bot - python clear_reaction() 清除所有反应而不是特定反应
查看>>
python django mysql写入中文乱码_django自动创建的mysql表里面中文乱码问题
查看>>
python docx的超链接网址和链接文本
查看>>
python elasticsearch 导出数据到json文件导入到另一个es中
查看>>
python进阶(1):json的使用
查看>>
python ETL工具 pyetl
查看>>
Python eval 函数说明
查看>>
python eval简介
查看>>
python excel 饼图 简书_Python实现绘画多个饼图
查看>>
python excel接口自动化测试框架!
查看>>
Python exec 函数解析:探索动态代码执行的无限可能!
查看>>
Python EXEC和__NAME__
查看>>
Python exe文件打包神器-Nuitka!
查看>>
python file
查看>>