arduino Serial Communication Serial Communication with Python


Example

If you have an Arduino connected to a computer or a Raspberry Pi, and want to send data from the Arduino to the PC you can do the following:

Arduino:

void setup() {
  // Opens serial port, sets data rate to 9600 bps:
  Serial.begin(9600);
}

void loop() {
  // Sends a line over serial:
  Serial.println("Hello, Python!");
  delay(1000);
}

Python:

import serial


ser = serial.Serial('/dev/ttyACM0', 9600)  # Start serial communication
while True:
    data = ser.readline()  # Wait for line from Arduino and read it
    print("Received: '{}'".format(data))  # Print the line to the console