i have a trouble with serial communicate (python 3.x -> arduino uno). when i run this code in python 2.5
python 2.5:
import serial
usbport = 'COM3'
ser = serial.Serial(usbport, 9600, timeout=1)
def move(servo, angle):
if (0 <= angle <= 180):
ser.write(chr(255))
ser.write(chr(servo))
ser.write(chr(angle))
else:
print("angle : between 0 and 180 \n")
when i simply type 'move(1,40)', servo1 (which is attached in pin9) moves to 40 angle.
But when i run the same code in python 3.6 , there is a error. error means that i have to write class not . so i encoded '255','servo','angle' to 'utf-8'
python 3.6.6
import serial
usbport = 'COM3'
ser = serial.Serial(usbport,9600,timeout = 1)
def move(servo,angle):
start = 255
start_b = str(start).encode()
ser.write(start_b)
a = str(servo).encode()
b = str(angle).encode()
ser.write(a)
ser.write(b)
But servo doesn't move.
Here is a arduino code
arduino uno
#include <Servo.h>
Servo servo1;
int minPulse = 600;
int maxPulse = 2400;
int userInput[3];
int startbyte;
int servo;
int pos;
int i;
void setup()
{
servo1.attach(9, minPulse, maxPulse);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop()
{
if (Serial.available() > 2) {
// Read the first byte
startbyte = Serial.read();
// If it is really the startbyte (255) ...
if (startbyte == 255) {
for (i=0;i<2;i++) {
userInput[i] = Serial.read();
}
servo = userInput[0];
pos = userInput[1];
if (pos == 255) { servo = 255; }
switch (servo) {
case 1:
servo1.write(pos); // move servo1 to 'pos'
break;
case 99:
if (pos == 180) {
if (pinState == LOW) { pinState = HIGH; }
else { pinState = LOW; }
}
if (pos == 0) {
pinState = LOW;
}
digitalWrite(ledPin, pinState);
break;
}
}
}
}