Connecting Microcontrollers: Direct Serial Connection

Arduino

#include <Arduino.h>#define LED 4void setup()
{
Serial.begin(9600);
pinMode(LED, OUTPUT);
}
void blink() {
digitalWrite(LED, HIGH);
delay(200);
digitalWrite(LED, LOW);
}
void loop()
{
delay(1000);
blink();
}
void checkAndProcessSerialData() {
if (Serial.available()) {
char ch = Serial.read();
if (ch > 0) {
Serial.print(ch);
}
}
}
// ...void loop()
{
delay(1000);
blink();
checkAndProcessSerialData()
}

Raspberry Pi

> pip3 install pyserialLooking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Collecting pyserial
Downloading https://files.pythonhosted.org/packages/07/bc/587a445451b253b285629263eb51c2d8e9bcea4fc97826266d186f96f558/pyserial-3.5-py2.py3-none-any.whl (90kB)
100% |████████████████████████████████| 92kB 1.3MB/s
Installing collected packages: pyserial
Successfully installed pyserial-3.5
from serial import Serial
from time import sleep
arduino = serial.Serial('/dev/ttyACM0', 9600, timeout=1)while True:
arduino.write(("Hello!").encode())
print(str(arduino.readline()))
sleep(2)
  • Line 1 & 2: Import the required libraries, the just now installed serial and the core library time
  • Line 4: Using the imports Serial class, we create an instance that connects to the attached Arduino - check whether its /dev/ttyACM0 or /dev/ttyUSB0 - sets the baud rate, and a timeout value to control when the connection should be recreated again.
  • Line 6: Similar to an Arduino code, we start a loop that never terminates…
  • Line 7: We send the message “Hello” to the Serial connection and encode it so that the characters are send as bytes
  • Line 8: We read from the serial connection and print it to the console
  • Line 9: Wait for 2 seconds.
python3 01_write_serial.py 
b''
b'Echo\r\n'
b'Echo\r\n'
b'Echo\r\n'

Reading Serial Data Correctly

print(str(arduino.readline(), 'utf-8').rstrip('\r\n'))
python3 01_write_serial.py 
Echo
Echo
Echo

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store