树莓派通过usart串口与ch340的电脑通讯

开放串口硬件功能

需要修改cmdline.txt文件:

sudo vi /boot/config.txt

在文件末尾加入

#ENABLE UART
enable_uart=1
dtoverlay=pi3-disable-bt 

在关闭串口调试,打开硬件串口
进入树莓派设置页面

sudo raspi-config

选择Interfacing Options ->Serial ->no -> yes
树莓派通过usart串口与ch340的电脑通讯_第1张图片
树莓派通过usart串口与ch340的电脑通讯_第2张图片
到这里我们的串口引脚就可以正常接收、输出数据了

wiringPi库的API

打开硬件串口:

fd = serialOpen("/dev/ttyAMA0",115200);

发送一个字符:

serialPutChar(fd,'c');

发送一个字符串:

srialPuts(fd,"aaaa");

检测接收字符串的状态

seralDataAvail(fd);		//没接收到数据返回-1

关闭串口

serialColse(fd);

接收大数据量的字符串用:

read(fd,cmd,sizeof(cmd));

代码验证

#include
#include
#include
#include 

 int main(void)
{
    int fd,len;
    char Buf[104] = {'\0'};
    char a;
    if((fd = serialOpen("/dev/ttyAMA0",115200))<0)//若无法通信,可检查更改串口波特率
    {
        printf("serial ERROR!!!\n");
    }
    printf("This is just for test================== BY WAN\n");

    serialPuts(fd,"START NOW====>");
    while(1)
    {
        if(serialDataAvail(fd) != -1)
        {
            len = read(fd,Buf,sizeof(Buf));
            printf("usart get data : %s",Buf);
			serialPuts(fd,Buf);
        }
    }
    return 0;
}

你可能感兴趣的:(linux)