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()