【RPi树莓派使用指南】树莓派串口通信介绍

来源:互联网 发布:艾瑞咨询好吗 知乎 编辑:程序博客网 时间:2024/05/21 13:57

树莓派的外部接口中含一路UART串行接口,利用该接口可以实现树莓派与Arduino、GPRS模块、GPS等其他外部系统的对接。

由于这一路串口兼做Linux的控制台输出口,所以在使用前必须先将调试输出功能关闭,方法如下:

1. 去除Kernel的启动信息

/boot/cmdline.txt中,去除parameterconsole=ttyAMA0,115200,并保存;

2. 去除Kernel的调试信息

同样在/boot/cmdline.txt中,去除 kgdboc=ttyAMA0,115200,并保存;

3. 关闭登陆提示

 /etc/inittab中去除T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100,保存。

经过以上三步,就可以正常使用串行口了。

编程时可以使用C语言以文件形式操作串口,也可以利用python的pySerial库进行编程。

这里以C语言为例,贴出示例代码:

#include <unistd.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <stdio.h>#include <string.h> intmain(intargc, char*argv[]){    intfd, len;    fd = open("/dev/ttyAMA0", O_RDWR, S_IRUSR | S_IWUSR);    chartemp;     while(1)    {        len = read(fd, &temp, 1);        write(fd, &temp, 1);        if(len > 0)        {            printf("%c", temp);        }        else        {            usleep(10);        }    }     close(fd);     return0; }

转载自:http://www.yfworld.com/?p=1666
0 0
原创粉丝点击