Search code examples
pythonarduinoserial-porthardwareservo

Python doesn't write to Arduino serial


I am new to Arduino, I just want to rotate servo motor left and right. My arduino code looks like this:

#include <Servo.h>

int servoPin = 9;

Servo myServo;
int pos1 = 0;

void setup() {

  Serial.begin(9600);
  myServo.attach(servoPin);

}

void loop() {
  myServo.write(180);
  delay(1000);
  myServo.write(0);
  delay(1000);
}

And it works perfectly. Now I want to achieve the same thing with python, so my python code looks like this:

import serial
import time

ser = serial.Serial('/dev/ttyACM0', 9600)
while True:
    print("Writing")
    ser.write("180;".encode())
    time.sleep(1)
    ser.write("0;".encode())
    time.sleep(1)

ser.close()

This code prints "Writing" in log but does absolutely nothing.


Solution

  • You are writing commands properly to the Arduino, the Arduino is just not listening. You need to read the Serial port on the Arduino end if you expect to see the servo move. Here is an example of reading from the serial port from the Arduino docs at https://www.arduino.cc/en/Serial/Read

    int incomingByte = 0;   // for incoming serial data
    
    void setup() {
            Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
    }
    
    void loop() {
    
            // send data only when you receive data:
            if (Serial.available() > 0) {
                    // read the incoming byte:
                    incomingByte = Serial.read();
    
                    // say what you got:
                    Serial.print("I received: ");
                    Serial.println(incomingByte, DEC);
            }
    }
    

    Modify this with some if-else logic or string to integer conversion to send the servo commands you need.