简体   繁体   中英

How to make my Python code behave like arduino serial monitor?

I am using serial communication with Arduino Leonardo .

When I test with Serial Monitor it seems to works fine. When I enter "1 500 500", mouse tends to move as expected.

But when I test with python, mouse does not seem to move and that results in "Num : 1"

How to make Python behave like an arduino serial monitor ?

Below is my python code :

import serial

ser = serial.Serial(
    port='COM10',
    baudrate=9600,
)
num = str.encode('1')
ser.write(num)
ser.write(b'500')
ser.write(b'500')

while True:
    cnt = 0
    if ser.readable():
        cnt = cnt+1
        print("Num :", cnt)
        res = ser.readline()
        res = res.decode()
        print(res)

Arduino code

#include "Keyboard.h" // Keyboard library
#include "Mouse.h"    // Mouse library
#include <MouseTo.h>

int inNum;
int inX;
int inY;

// Procedure of pressing key and moving mouse
void procedure();


void setup() {
  Serial.begin(9600);
  Keyboard.begin();
  Mouse.begin();
  MouseTo.setCorrectionFactor(0.5);
  MouseTo.setScreenResolution(1920, 1080);
}

void loop() {
  if(Serial.available())
  {
    inNum = Serial.parseInt();
    procedure(inNum);
  }

}

void procedure(int num){
  switch (num)
  {
    case 1:
      inX = Serial.parseInt();
      inY = Serial.parseInt();
      MouseTo.setTarget(inX, inY);
      while(!MouseTo.move()){};
      Mouse.click(MOUSE_LEFT);
      delay(200);
      MouseTo.setTarget(0, 0);
      while(!MouseTo.move()){};
      Serial.write("Done");
      break;
    case 2:
      MouseTo.setTarget(960, 540);
      while(!MouseTo.move()){};
      break;
    default:
      //MouseTo.setTarget(1920, 1080);
      //while(!MouseTo.move()){};
      Serial.write("default");
      Serial.write(num);
      break;
  }
}

You have two issues preventing you from getting what you want.

First, the way you parse integers on your Arduino code is expecting a separator. It reads until it finds something that is not a number. To fix that just add spaces on the strings you send, or colon or whatever you like. Otherwise Serial.parseInt() will not be able to read anything because you are only sending numbers from Python.

Second, you cannot read in Python with serial.readline() if you use raw write ( Serial.write() ) from the Arduino. Again, Python is expecting a line terminating caharcter. To fix that, add \\r\\n to the string you send or use Serial.println() instead. If you don't want to add those terminating characters you can read bytes in a loop until the buffer is empty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM