1

我是 Pyserial 的新手,我目前正在使用它从微控制器读取一堆数据,数据格式类似于 (1,2,3,4,....),我想将这些数据保存到一个文本文件或Matlab,我应该如何实现这个?谢谢!

4

1 回答 1

2

给你,这是我一直在创建的存储库的链接,总结了不同的方法:

https://github.com/gskielian/Arduino-DataLogging/blob/master/PySerial/README.md

下面的说明


PySerial

Pyserial 是从 Arduino 中获取数据的绝佳方式,它既健壮又易于实现。

以下示例显示了一种非常简单的方法,可以帮助您入门。

但是,请注意 arduino 不会不断地向您的程序发送数据——您可能会遇到缓冲区溢出导致的错误。

朴素的 Pyserial 和 Sketch

#先试试这个来感受一下pyserial

天真.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')

天真.ino

void setup() {
  Serial.begin(115200);
}

void loop() {
  Serial.println(analogRead(A0));
  delay(1000);
}

强大的 Pyserial 和 Sketch

准备好后,考虑让 arduino 仅在 python 程序提示时发送数据:

8健壮的.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')

健壮的.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);
     }
   }    
}
于 2014-01-23T05:34:55.600 回答