这是一个复杂的错误,我已经有几个星期了,我不知道如何修复它。我有一个热敏电阻阵列插在四个第一个模拟管脚上,它们在Python脚本上返回温度,该脚本通过串行端口与Arduino通信。以下是Arduino代码:
float R1 = 2000;
float c1 = 8.7956830817e-4, c2 = 2.52439152444e-04, c3 = 1.94859260345973e-7;
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT);
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
}
int getVoltage(int i) {
return analogRead(i);
}
float getTemp(int i) {
int V = getVoltage(i);
float R2 = R1 * (1023.0 / (float)V - 1.0); \\minus 1 for 1 index based
float logR2 = log(R2);
float T = (1.0 / (c1 + c2*logR2 + c3*logR2*logR2*logR2));
return T - 273.15;
}
String getTempString(int i) {
float temp = getTemp(i);
String result;
if(temp > 99.99){
return String(temp, 2);
} else {
return String(temp, 3);
}
}
void loop() {
if (Serial.available() > 0) {
digitalWrite(13, HIGH);
// read the incoming byte:
String input = Serial.readStringUntil('\n');
digitalWrite(13, LOW);
//send the temperature
char* response = new char[6];
int channelNumber = String(input[0]).toInt() - 1;//-1 to make it index based 1
getTempString(channelNumber).toCharArray(response, 6);
//delay(20);
Serial.write(response, 6);
Serial.write('\n');
}
}
下面是Python代码:
from serial import Serial
import time
ser = Serial('COM5', 9600, timeout=1)
def readTempChannel(i):
global ser
ser.write(i+b'\n')
raw = str.rstrip(ser.readline())
try:
return float(raw)
except Exception:
ser.close()
ser = Serial('COM5', 9600, timeout=1)
return 5.0[![enter image description here][1]][1]
if __name__ == "__main__":
while 1:
channel1 = readTempChannel('1')
channel2 = readTempChannel('2')
channel3 = readTempChannel('3')
channel4 = readTempChannel('4')
print('%.2f, %.2f, %.2f, %.2f' % (channel1, channel2, channel3, channel4))
问题是,我在前10秒得到值,但在那之后,我要么得到空字符串,要么从Arduino中得到非数字的随机字符
我尝试关闭并重新打开串行端口,这是可行的(有时),但它增加了流的延迟,我需要通信在我的应用程序没有任何延迟的高速发生。我在这篇文章中添加了一个屏幕截图,显示PuTTY终端上的错误(Python代码在Beaglebone上运行,它是Python 2.7)
所以,如果你们中有人能帮我解决这个错误,我将非常感激
这是一个在没有所有物理硬件的情况下很难解决的问题,但我可以与您分享我在arduino中使用pyserial的经验:
在python方面,我没有使用新行:
我还使用下面的一行暂停python程序,直到它收到响应——这对于流控制非常重要
在arduino侧,我使用以下命令读入串行命令并执行命令:
尝试将上面的一些内容集成到代码中,然后回复我-就像我说的,没有硬件很难解决硬件问题,我这里的代码来自很久以前的一个项目
相关问题 更多 >
编程相关推荐