0

I'm starting to learn how to work with Arduino, particularly communication between a Python code running on a PC and an Arduino Uno.

So I decided to start with what I thought to be a easy task. That is, sending the user input from Python. There are 2 values, one delay between Arduino LED (port 13) and the servo angle.

It didn't work and I couldn't find any answers, hope you can help me.

Arduino Code -

#include <Servo.h>

const int ledPin = 13; // pin the LED is attached to
int incomingByte = 1000;      // variable stores  serial data
int pos = 0; 
int incoming[2];
Servo myservo;

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
  myservo.attach(9);
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
   digitalWrite(ledPin, HIGH);
   myservo.write(180);
   delay(1000);
   digitalWrite(ledPin, LOW);
   myservo.write(0);
}

void loop()
{

  if (Serial.available()>=2) 
  {
     for (int i = 0; i < 1; i++)
     {
      incoming[i] = Serial.read();
     }
    digitalWrite(ledPin, HIGH);
    delay(incoming[0]);
    digitalWrite(ledPin, LOW);
    myservo.write(incoming[1]);
  }
}

Python (3.7) code -

import serial
import time

ser = serial.Serial('COM5', 9600, timeout=1)


user_input = '1'
while user_input != 'q':
    user_input = input("'Blink time is or q = quit' : ") 
    servo_input = input("What position servo go? ")
    byte_command = str.encode(user_input)                 
    ser.write(byte_command)                              
    servo_command = str.encode(servo_input)
    ser.write(servo_command)
    time.sleep(0.5)                                      

print('\nq entered. Exiting the program')
ser.close()
  • Arduino resets on new USB connection and spends some seconds in bootloader after that. wait two seconds in Python after connecting to Arduino. – Juraj Apr 21 at 10:54
-2

Well I did it in the simplest way.

I just sent a string to C++ and deconstructed it with sscanf().

  • Would you care to expand upon your answer? As it stands, it is rather terse. – Greenonline May 30 at 10:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.