0

I'm trying to receive data (arrays) from Arduino into my Python script, everything seems to be working fine until I try receiving a 5 or more digit number. Some searching suggests this probably has to do with Pyserial reading only a certain number of bytes at a time, but I am unable to understand what I need to change to be able to read my arrays. Please take a look at my codes: Arduino code:

int data[] = {1245,2211,33498,4212,5235};
void setup() {
Serial.begin(9600);
}

void loop() {
for (int i=0; i<5; i++)
{
  Serial.println(data[i]);
}

  //Commented this out because it'd give me garbage value in python
  //delay(1000);
}

Python Code:

import serial
ser1 = serial.Serial('COM6', 9600) 
#receive some data
for i in range(5):
   arduinoData = ser1.readline().decode('ascii')
   print(arduinoData)

Upon running this code I get:

1245

2211

-32038 (Why was this value converted into a negative number?)

4212

5235

AbdurRehman Khan
  • 615
  • 4
  • 17

2 Answers2

4

This is an overflow error on the Arduino side.

A signed integer (int) can take values from -32768 to 32767 (as it is two bytes, each 8 bit making a 16 byte number so ranging from -2^15 to 2^15-1). Since 33498 is greater than that upper limit, it wraps around to a negative.

To redeem this, change your array of ints to a data type which supports larger positive intergers than 32767 - such as uint_16.


If you are interested, we can understand exactly why the negative number was -32038.

This is because all signed integers are represented using two's complement.

And in that system, 1000001011011010 (33498) is -32038.

To do that conversion, we negate it (to get it's positive representation( by inverting all its bits and add 1:

1000001011011010 --> 0111110100100101 --> 0111110100100110 == 32038
Joe Iddon
  • 18,600
  • 5
  • 29
  • 49
1

Your assignment

int data[] = {1245,2211,33498,4212,5235};

overflows for numbers outside the positive range of int, so the data array already contains the negative numbers.

Fix your c code

unsigned int data[] = {1245,2211,33498,4212,5235};

to send the data as intended .

rocksportrocker
  • 6,639
  • 2
  • 28
  • 46