因为我的USB-TTL模块出了问题,所以只好使用GPIO口和树莓派实现通信,在此记录。
Article Directory
This article uses the GPIO port of the Raspberry Pi to realize the UART communication function. If readers want to use USB to TTL to realize UART communication, please refer to the article: Realize serial communication with upper and lower computers of Raspberry Pi through UART
GPIO pin function diagram (4B)
More specific:
Hardware connection
PYB | raspberry pie |
---|---|
TX(X3) | RX(15) |
RX(X4) | TX(14) |
GND | GND |
UART communication code
PC Raspberry Pi
# -*- coding:utf-8 -*-
import serial
import time
ser = serial.Serial("/dev/ttyAMA0", 9600)
ser.flushInput()
ser.write("begin".encode("utf-8"))
def main():
while True:
count = ser.inWaiting()
if count != 0:
recv = ser.read(count)
ser.write("Recv some data is : ".encode("utf-8"))
ser.write(recv)
ser.write("\n".encode("utf-8"))
print(ser.readline())
ser.flushInput()
if __name__ == '__main__':
main()
PYB end of lower computer
from pyb import UART
class Serial:
def __init__(self, uart):
self.uart = uart
def data_check(self):
return self.get_data()
def send_data(self):
data = "hi i'm pyboard!\n"
data.encode("utf-8")
self.uart.write(data)
# print("send!")
def get_data(self):
start = utime.ticks_ms()
data = self.uart.readline()
if data != None:
print("get data!!!!!")
try:
data.decode("utf-8")
except:
pass
end = utime.ticks_ms()
print("running time:", end - start)
print(data)
return True
else:
return False
uart = UART(2, 9600)
ser = serial.Serial(uart)
while True:
ser.send_data()
ser.get_data()
Communication effect
Raspberry Pi
ALL 端
Obtained by program timing: each UART communication takes 19ms
Serial port transmission rate under different baud rates
Try to increase the UART baud rate of the Raspberry Pi and PYB to 115200. After restarting, I found that each serial communication takes only 2ms!
Reference article: