Since I had the opportunity to use serial communication with Raspberry Pi, I will post a memorandum on how to communicate.
By default, the Raspberry Pi has the serial port disabled, so change the setting. Open LXTerminal and enter the command.
pi@raspberrypi:~ $ sudo raspi-config
The following screen will be displayed. Select "5 Interfacing Options". Then select P6 Serial. Select No. Select "Yes". Then you will see a screen like this with the serial port enabled. If you exit raspi-config as it is, you will be asked to choose whether to restart, so restart it. After rebooting, enter the following command to display the enabled serial port ttyS0 under / dev /.
pi@raspberrypi:~ $ ls -l /dev/ttyS*
Since the 8th pin (GPIO14) and 10th pin (GPIO15) of Raspberry Pi are UART pins, Short with a wire jumper.
Check communication using the pyserial library.
serialTest.py
import serial
#Communication establishment
ser = serial.Serial('/dev/ttyS0', '9600', timeout=0.1)
#Data transmission / reception
ser.write('Hello, World!')
print(repr(ser.readline()))
ser.close()
After saving the file, move to the directory where the file is saved in LXTerminal and execute it. If successful, the message you sent will be displayed.
pi@raspberrypi:~/work $ python setialTest.py
Hello World!
I haven't touched the Raspberry Pi so much, so I didn't know that serial communication was turned off by default. I would like to use it for various purposes such as connecting to a sensor or Arduino.
Recommended Posts