For some details of the serial port configuration, please refer to other blog posts, which will not be introduced here.
Raspberry Pi communicates with the computer
Raspberry Pi sends data to the computer
#include <wiringSerial.h>
#include <wiringPi.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int fd;
if(wiringPiSetup() == -1)
{
printf("硬件接口初始化失败!\n");
exit(-1);
}
fd=serialOpen("/dev/ttyAMA0",9600);//打开并初始化串口,波特率9600
if(fd != -1){
printf("serial open success\n");
printf("fd=%d\n",fd);
}
while(1)
{
serialPutchar(fd,'u');//发送数据
delayMicroseconds(1000000);
serialPrintf(fd,"handsome!\r\n");
delayMicroseconds(1000000);
serialPuts(fd,"Because you are Leo\r\n");
delayMicroseconds(1000000);
}
return 0;
}
The computer sends data to the Raspberry Pi
Here you need to upgrade the permissions of ttyAMA0 :
sudo chmod 0777 /dev/ttyAMA0
#include <stdlib.h>
#include <wiringSerial.h>
#include <wiringPi.h>
#include <stdio.h>
int main()
{
int fd;
int ret;
if(wiringPiSetup() == -1)
{
printf("硬件接口初始化失败!\n");
exit(-1);
}
fd=serialOpen("/dev/ttyAMA0",9600);//打开并初始化串口,波特率9600
if(fd != -1){
printf("serial open success\n");
printf("fd=%d\n",fd);
}
while(1)
{
while(serialDataAvail(fd) !=-1)//判断是否有数据发送过来
{
ret=serialGetchar(fd);
printf("ret=%d\n",ret);
}
}
return 0;
}