Raspberry Pi development-serial communication programming

1. Configuration:

It is the first time to use the Raspberry Pi serial port to program and need to be configured

Modify the cmdline.txt file:

cd /boot/
sudo vi cmdline.txt

Delete the part between 【】:

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

Modify the inittab file:

cd /etc/
sudo vi inittab

Comment the content of the last line: add # sign before the line

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

Restart the Raspberry Pi:

sudo reboot

2. Related functions:

Include header files:

#include <wiringSerial.h>
Function prototype parameter Description
int serialOpen(char *device, int baud); char *device: The address of the serial port. In Linux, it is the directory where the device is located. The default is usually "/dev/ttyAMA0";int baud: Baud rate;return value: Return the file descriptor on success, return -1 on failure Open and initialize the serial port
void serialClose(int fd); inf fd: File descriptor Close the serial port associated with fd
void serialPutchar(int fd, unsigned char c); int fd: File descriptor;unsigned char c: The data to be sent Send one byte of data to the serial port
void serialPuts(int fd, char *s); inf fd: File descriptor;char *s: The data to be sent Send a string to the serial port
void serialPrintf(int fd, char *message, …); int fd: File descriptor;char *message: Formatted string Send a string to the serial port (similar to the printf(); function in the C language standard library)
int serialDataAvail(int fd); int fd: File descriptor;return value: Return the number of bytes on success, -1 on failure Get the number of bytes available in the serial buffer
int serialGetchar(int fd); int fd: File descriptor;return value: The data read Read a byte of data from the serial port and return it. If there is no data available in the serial port buffer, it will wait for 10 seconds. If there is still no data after 10 seconds, it will return -1, so it is better to call serialDataAvail();judgment before reading. Take multiple characters and use the address offset method to read
void serialFlush(int fd); int fd: File descriptor Clear the data in the serial buffer

Include header files:

#include <wiringSerial.h>
#include <unistd.h>
Function prototype Description
ssize_t read(int fd, void *buf, size_t count); Standard IO library functions under Linux, tofdRead incountBytes of data stored inbufin
ssize_t write(int fd, const void *buf, size_t count); Standard IO library functions under Linux, go tofdWrite incountBytes of data, the content isbufBeforecountBytes of data

Guess you like

Origin blog.csdn.net/lcx1837/article/details/108167506