1

I need to send mouse coordinates from python to arduino. As you know there is X and Y axis and there is some negative values like -15 or -10 etc. on those axis. Arduino's serial only accepts Bytes so bytes are limited with 0 to 256. My problem is starts right here. I cant send negative values from python to arduino. Here is my code for python :

def mouse_move(x, y):
    pax = [x,y]
    arduino.write(pax)
    print(pax)

For example when x or y is negative value like -5 , Program crashes because byte array is 0-256 .

here is my arduino's code:

#include <Mouse.h>

byte bf[2];
void setup() {
  Serial.begin(9600);
  Mouse.begin();
}

void loop() {
  if (Serial.available() > 0) {
    Serial.readBytes(bf, 2);
    Mouse.move(bf[0], bf[1], 0);
    Serial.read();
  }
}
  • Is [0,255] even enough to transport mouse coordinates with enough precision? I guess you would have to decide to send coordinates on more bytes (like eg 4 bytes per direction) and implement you own convention for negative, for instance reserve most significant bit for sign – Jean-Marc Volle Sep 21 '20 at 10:58

1 Answers1

1

You need to send more bytes to represent each number. Let's say you use 4 bytes per number. Please note that this code needs to be adapted to the arduino endianess. On python side you would have to do something like:

def mouse_move(x, y):
    bytes = x.to_bytes(4, byteorder = 'big') + y.to_bytes(4, byteorder = 'big')
    arduino.write(bytes)

    print(pax)

On receiver side you need to reconstruct the number from their bytes constituants something like:

byte bytes[4] 
void loop() {
  int x,y; /* use arduino int type of size 4 bytes  */
  if (Serial.available() > 0) {
    Serial.readBytes(bytes, 4);
    x = bytes[0] << 24 | bytes[1] << 16 |  bytes[2] << 8 |  bytes[0]
    Serial.readBytes(bytes, 4);
    y = bytes[0] << 24 | bytes[1] << 16 |  bytes[2] << 8 |  bytes[0]
    Mouse.move(x, y, 0);
    Serial.read();
  }
}
Jean-Marc Volle
  • 3,113
  • 1
  • 16
  • 20
  • Thank you for comment, actually i cant compile your code to mine. To understand the basics of this subject can you tell me the which keywords i should search on web ? – Beat By Venom Sep 21 '20 at 11:30
  • Hello. You can have a look here to understand how number are coded in memory or in your case how they can be transmitted over a serial link: https://www.embedded.com/endianness/ – Jean-Marc Volle Sep 21 '20 at 12:22