我对arduino和python都是新手,一直找不到有效的答案。目前,我的项目要求我从文本文件向我的arduino uno发送数据。我一直在尝试使用python程序从文本文件中读取值并将它们发送到我的arduino。然后,arduino应使用这些值操作电机。我尝试过更简单的测试,比如向电机发送高电平和低电平信号,但当发送整数和浮点作为analogWrite()的输入时,问题似乎出现了。我更愿意使用浮动来获得更高的精度,但工作系统更重要
编辑:通过将b'number'更改为number.encode()进行修复。我仍然对Serial.available()问题的解决方法感到好奇
Arduino:
const int motorPin = 9;
float input = 0;
void setup() {
pinMode(motorPin, OUTPUT);
Serial.begin(9600);
}
void loop(){
if (Serial.available()) {
Serial.println("data has been entered");
float x = Serial.parseFloat();
if (x > 0) {
input = x;
analogWrite(motorPin, input);
}
}
Serial.print(input);
Serial.println(" was used");
}
作为补充说明,我还遇到了一个问题,即Serial.available()在读取所有值后总是返回true,而我会额外读取一个值0。这就是第二个if语句的理由。如果有更好的工作,请告诉我。如果数据中有0,我希望读取它们
Python:
import serial
import time
#Set by deault to COM4 -- change as needed
arduino = serial.Serial('COM4', 9600)
#Allow connection between the ports to clear
time.sleep(2)
#Start an infinite loop to send data from acceleration text file to Arduino
f = open("accel_vals-1.txt", "r")
while 1:
#will need to check later on if file can write while loop is running
for number in f:
arduino.write(b'number')
print(number + " entered")
time.sleep(1)
#Close file after program ends
f.close()
文本文件:
0
10
20
30
40
50
60
70
80
90
100
90
80
70
60
50
40
30
20
10
0
100
200
250
200
100
0
目前没有回答
相关问题 更多 >
编程相关推荐