【自我提高】树莓派UART的几种语言控制方法 C 篇

【自我提高】树莓派UART的几种语言控制方法 C语言 篇

首先要安装wiringPi,具体安装过程见一下链接:

https://blog.csdn.net/shileiwu0505/article/details/106365588

对照树莓派 3B+ 引脚对应关系图,PI 3B + V1.2
在这里插入图片描述
上测试代码

#include <wiringSerial.h>
#include <wiringPi.h>

#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>

int main(void)
{
    
    
	int fb,ret,revlen;
	char buf[200];
	char *str = "this is uart test \n";
	fb = serialOpen ("/dev/ttyAMA0", 9600);
	if(fb < 0){
    
    
		printf("serialOpen error \n");
	}
	
	/* 设置文件描述符为非阻塞工作 */
	/* 本例程 read() 函数默认是阻塞,设置非阻塞后,
	   没有可读数据能够立即返回 */
	int flags = fcntl(fb, F_SETFL, O_NONBLOCK);
	fcntl(fb, F_SETFL, flags | O_NONBLOCK);
	while(1)
	{
    
    
			ret = write(fb,str,strlen(str));
			if(ret < 0){
    
    
				printf("write error \n");
			}
			revlen = read(fb,buf,200);		
			if(revlen > 0){
    
    			
				printf("read data %s,len %d\n",buf,revlen);
				write(fb,buf,revlen);
				memset(buf,0,200);
			}
			delay(500);
	}

}

本程序例程实现了,树莓派收到了串口助手发过来信息并回显到串口助手,并且每500ms向串口助手发一次信息 “this is uart test”。

头文件

#include <wiringPi.h>

包含了微秒级别的延迟函数

头文件

#include <wiringSerial.h>

包含了串口设备打开、初始化信息

在网站:
http://wiringpi.com/reference/serial-library/
串口库下面有这么一段话:

Note: The file descriptor (fd) returned is a standard Linux filedescriptor. You can use the standard read(), write(), etc. system calls on this file descriptor as required. E.g. you may wish to write a larger block of binary data where the serialPutchar() or serialPuts() function may not be the most appropriate function to use, in which case, you can use write() to send the data.

意思就是,打开后的串口描述符 fd 支持linux标准读写函数,所以在例程中,我们直接就可以使用write()与read()这两个函数进行读写。

猜你喜欢

转载自blog.csdn.net/shileiwu0505/article/details/106415162