【发布时间】:2022-11-01 17:11:00
【问题描述】:
我的项目应该将数据从 Arduino IDE 发送到 Python(并打印出来),然后将这些值用于进一步的操作。问题是信息(应该是浮点数的字符串)以空字符串的形式出现。这正在破坏整个项目,因为我无法完成以下操作。
这是我的 Arduino 代码:
bool state=false;
int f=100, dt=0;
char command;
unsigned long t=0, lt=0;
void setup() {
Serial.begin(115200);
dt=int(1000\*1/(float)f);
}
void loop() {
if (Serial.available()) {
command = Serial.read();
switch (command) {
case 'S': state=!state;
break;
}
lt=millis(); }
if (state) {
t=millis();
if ((t-lt)\>=dt) {
float a = analogRead(A1);
float b = 1024;
Serial.println(((((a/b-0.5)\*3.3)/1009))\*1000);
lt=t; }
} }
这是我的 Arduino 串行监视器中的一些内容:
0.69
0.96
1.09
0.82
0.72
0.84
0.77
0.79
0.75
0.75
0.81
0.78
0.76
0.80
0.74
0.93
0.75
0.80
0.82
0.78
0.80
我的python代码:
with serial.Serial('/dev/cu.usbmodem101', baudrate=115200, timeout=0) as arduino:
try:
kb = pynput.keyboard.Controller()
key = pynput.keyboard.Key.space
while True:
data = arduino.readline().decode().strip()
print(data)
time.sleep(0.01)
if data:
emg=float(data)
print(emg)
if (emg>0.80 or emg<-0.80):
print("Trigger")
kb.press(key)
kb.release(key)
except Exception as e:
print(e)
arduino.close()
print('Serial communication closed')
我的 python 输出实际上是一个巨大的空间,因为它一直打印空字符串 kkkk。
如果你能帮助我,我会非常感激:) 谢谢你!!
【问题讨论】:
-
据我所知,您的 Python 代码永远不会向 Arduino 发送
S,因此state变量永远不会设置为 true - 所以 Arduino 永远不会真正发回任何东西。
标签: python arduino arduino-ide