树莓派和电脑之间的串口通信

一开始我们配置了串口登录树莓派,这样会导致我们后面在用树莓派的时候有些冲突,所以我们需要先修改树莓派串口的一些配置

/* 修改 cmdline.txt文件 */

>cd /boot/

>sudo vim cmdline.txt

删除【】之间的部分

dwc_otg.lpm_enable=0 【console=ttyAMA0,115200】 kgdboc=ttyAMA0,115200 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline rootwait

/*修改 inittab文件 */ //如果没有这个文件,直接跳过即可

>cd /etc/

>sudo vim inittab

注释掉最后一行内容:,在前面加上 # 号

#T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100

sudo reboot 重启

树莓派给电脑发送信息

cpp 复制代码
#include <wiringPi.h>
#include <wiringSerial.h>

int main()
{

     int fd;
     if(WiringPiSetup()==-1){
    
        printf("Setup error\n");
        return -1;
     }   

     fd = serialOpen("/dev/ttyAMA0",9600);
     while(1){
       serialPutchar(fd,"c");  //发送字符
       //serialPuts(fd,"hello i am pi");// 发送字符串
       delayMicroseconds(1000000)//微秒级别 
     }
}

电脑通过串口助手给树莓派发消息

cpp 复制代码
#include <wiringPi.h>
#include <wiringSerial.h>

int main()
{

     int fd;
     int cmd;
     if(WiringPiSetup()==-1){
    
        printf("Setup error\n");
        return -1;
     }   

     fd = serialOpen("/dev/ttyAMA0",9600);
     while(1){
           
        while( serialDataAvail(fd) != -1){

            cmd =serialGetchar(fd); // 通过接收到的指令执行不同的操作
               if(cmd == '2'){
                    printf("daxu 2\n");
                }
        }
     }
}

串口通信相关API

首先要包含头文件 #include <wiringSerial.h>

打开串口

复制代码
int serialOpen (char *device, int baud)

device: 串口的地址,一般默认 "/dev/ttyAMA0"

buad: 波特率

返回值: 正常会返回文件描述符,否则返回-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判断下。

相关推荐
chlk1231 天前
Linux文件权限完全图解:读懂 ls -l 和 chmod 755 背后的秘密
linux·操作系统
舒一笑1 天前
Ubuntu系统安装CodeX出现问题
linux·后端
改一下配置文件1 天前
Ubuntu24.04安装NVIDIA驱动完整指南(含Secure Boot解决方案)
linux
深紫色的三北六号2 天前
Linux 服务器磁盘扩容与目录迁移:rsync + bind mount 实现服务无感迁移(无需修改配置)
linux·扩容·服务迁移
SudosuBash2 天前
[CS:APP 3e] 关于对 第 12 章 读/写者的一点思考和题解 (作业 12.19,12.20,12.21)
linux·并发·操作系统(os)
哈基咪怎么可能是AI2 天前
为什么我就想要「线性历史 + Signed Commits」GitHub 却把我当猴耍 🤬🎙️
linux·github
十日十行3 天前
Linux和window共享文件夹
linux
木心月转码ing3 天前
WSL+Cpp开发环境配置
linux
崔小汤呀4 天前
最全的docker安装笔记,包含CentOS和Ubuntu
linux·后端
何中应4 天前
vi编辑器使用
linux·后端·操作系统