2

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;
   }
  }
 }
}
HK boy
  • 1,398
  • 11
  • 17
  • 25

2 Answers2

0

there is a error.

Can you provide the error message? And of course the code will not run directly from Python 2 to 3 until you do the modification from importing the PySerial Library. Python runs and finds the library, but it cannot be used for Python 3, that's why they made 2 libraries for PySerial.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Waged
  • 372
  • 3
  • 14
  • 1
    I guess you should ask for more clarifications in the comments (not as an answer). – Taher A. Ghaleb Nov 30 '18 at 01:48
  • try to download pySerial3 for python3 and compile again(if you can also uninstall pyserial2 from the pc it will help) as I faced this that's why I thought it can help as an answer but anyway you're right, sorry my bad. – Waged Nov 30 '18 at 10:14
-1

after Serial.begin(9600); write ser.begin(9600);

  • 2
    1. Could you please format your code? 2. What does this do? `ser` only looks like part of the python code and `Serial.begin` is in the Arduino code. – General Grievance Aug 25 '20 at 11:48