如何使用 Pyserial 从 Arduino 接收 5 位数据?
How to receive 5-digit data from Arduino using Pyserial?
我正在尝试从 Arduino 接收数据(数组)到我的 Python 脚本中,在我尝试接收 5 位或更多位数字之前一切似乎都工作正常。一些搜索表明这可能与 Pyserial 一次只读取一定数量的字节有关,但我无法理解我需要更改什么才能读取我的数组。请看看我的代码:
Arduino代码:
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代码:
import serial
ser1 = serial.Serial('COM6', 9600)
#receive some data
for i in range(5):
arduinoData = ser1.readline().decode('ascii')
print(arduinoData)
根据 运行 这个代码我得到:
1245
2211
-32038(为什么这个值被转换成负数?)
4212
5235
这是Arduino端的溢出错误。
有符号整数 (int
) 可以取值从 -32768
到 32767
(因为它是两个字节,每个 8
位构成 16
字节数,范围从 -2^15
到 2^15-1
)。由于 33498
大于该上限,因此它环绕为负值。
要弥补这一点,请将您的整数数组更改为支持比 32767
更大的正整数的数据类型 - 例如 uint_16
.
如果你有兴趣,我们可以准确理解为什么负数是 -32038
。
这是因为所有有符号整数都使用two's complement表示。
在那个系统中,1000001011011010
(33498
) 是 -32038
。
为了进行该转换,我们将其取反(以获得它的正表示(通过反转其所有位并添加 1
:
1000001011011010 --> 0111110100100101 --> 0111110100100110 == 32038
你的作业
int data[] = {1245,2211,33498,4212,5235};
超出 int
正数范围的数字溢出,因此 data
数组已包含负数。
修复你的 C 代码
unsigned int data[] = {1245,2211,33498,4212,5235};
按预期发送数据。
我正在尝试从 Arduino 接收数据(数组)到我的 Python 脚本中,在我尝试接收 5 位或更多位数字之前一切似乎都工作正常。一些搜索表明这可能与 Pyserial 一次只读取一定数量的字节有关,但我无法理解我需要更改什么才能读取我的数组。请看看我的代码: Arduino代码:
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代码:
import serial
ser1 = serial.Serial('COM6', 9600)
#receive some data
for i in range(5):
arduinoData = ser1.readline().decode('ascii')
print(arduinoData)
根据 运行 这个代码我得到:
1245
2211
-32038(为什么这个值被转换成负数?)
4212
5235
这是Arduino端的溢出错误。
有符号整数 (int
) 可以取值从 -32768
到 32767
(因为它是两个字节,每个 8
位构成 16
字节数,范围从 -2^15
到 2^15-1
)。由于 33498
大于该上限,因此它环绕为负值。
要弥补这一点,请将您的整数数组更改为支持比 32767
更大的正整数的数据类型 - 例如 uint_16
.
如果你有兴趣,我们可以准确理解为什么负数是 -32038
。
这是因为所有有符号整数都使用two's complement表示。
在那个系统中,1000001011011010
(33498
) 是 -32038
。
为了进行该转换,我们将其取反(以获得它的正表示(通过反转其所有位并添加 1
:
1000001011011010 --> 0111110100100101 --> 0111110100100110 == 32038
你的作业
int data[] = {1245,2211,33498,4212,5235};
超出 int
正数范围的数字溢出,因此 data
数组已包含负数。
修复你的 C 代码
unsigned int data[] = {1245,2211,33498,4212,5235};
按预期发送数据。