我是Pyserial的新手,我目前正在使用它从微控制器读取一堆数据,数据格式如(1,2,3,4,....),我想保存这些数据要么是文本文件还是Matlab,我应该如何实现呢?谢谢!
答案 0 :(得分:1)
在这里,这里是一个链接到我一直在创建的存储库,总结了不同的方法:
https://github.com/gskielian/Arduino-DataLogging/blob/master/PySerial/README.md
Pyserial是从Arduino中获取数据的绝佳方式,它既健壮又易于实现。
以下示例显示了一种非常简单的方法,可以帮助您入门。
但是,请注意arduino不会经常向您的程序发送数据 - 您可能会遇到来自缓冲区溢出的错误。
#try首先想要了解pyserial
<强> naive.py 强>
import serial
ser = serial.Serial('/dev/ttyACM0',115200)
f = open('dataFile.txt','a')
while 1 :
f.write(ser.readline())
f.close()
f = open('dataFile.txt','a')
<强> naive.ino 强>
void setup() {
Serial.begin(115200);
}
void loop() {
Serial.println(analogRead(A0));
delay(1000);
}
当你准备好了,考虑让arduino只在你的python程序提示时发送数据:
<强> 8robust.py 强>
#!/usr/bin/python
import serial, time
ser = serial.Serial('/dev/ttyACM0', 115200, timeout = 0.1)
#if you only want to send data to arduino (i.e. a signal to move a servo)
def send( theinput ):
ser.write( theinput )
while True:
try:
time.sleep(0.01)
break
except:
pass
time.sleep(0.1)
#if you would like to tell the arduino that you would like to receive data from the arduino
def send_and_receive( theinput ):
ser.write( theinput )
while True:
try:
time.sleep(0.01)
state = ser.readline()
print state
return state
except:
pass
time.sleep(0.1)
f = open('dataFile.txt','a')
while 1 :
arduino_sensor = send_and_receive('1')
f.write(arduino_sensor)
f.close()
f = open('dataFile.txt','a')
<强> robust.ino 强>
void setup () { pinMode(13, OUTPUT); Serial.begin(115200); }
void loop() {
if (Serial.available()) {
ch = Serial.read();
if ( ch == '1' ) {
Serial.println(analogRead(A0)); // if '1' is received, then send back analog read A0
}
else if (ch == '2') {
digitalWrite(13,HIGH); // if '2' is received, turn on the led attached to 13
}
else if (ch == '3') {
digitalWrite(13,LOW); // if '3' is received then turn off the led attached 13
} else {
delay(10);
}
}
}