使用Python的Pyseri向Arduino串行端口发送字符

2024-06-07 22:33:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经设置了一个Arduino,当它接收到一个'S'字节时发送数据。这在Arduino串行监视器中工作。但是,我在Python上绘制数据,使用Pyserial来联系串行端口。这是我的Arduino素描,我想说的是:

#include <eHealth.h>


unsigned long time;
unsigned long interval = 8;
byte serialByte;

// The setup routine runs once when you press reset:
void setup() {
  Serial.begin(9600);  
}

// The loop routine runs over and over again forever:
void loop() {
  if(Serial.available()>0){
    serialByte = Serial.read();
    if(serialByte == 'S'){  
      while(1){
        float ECG = eHealth.getECG();
        time = time + interval;
        Serial.print(time);
        Serial.print(" ");
        Serial.print(ECG, 3); 
        Serial.println("");

        if(Serial.available()>0){
          serialByte = Serial.read();
          if (serialByte == 'F') break;
        }
      }
    }
  }
  delay(interval);
}

就像我说的,这很管用。但在Python上,当我尝试以下操作时:

import serial
ser = serial.Serial('/dev/tty.usbmodem1411', 9600)
ser.write(bytearray('S','ascii'))

或者这个:

import serial
ser = serial.Serial('/dev/tty.usbmodem1411', 9600)
ser.write('S')

arduino由于某种原因没有接收到它,数据也没有通过串行端口流向Python。我不知道这个问题。如你所见,我已经尝试过转换成字节,但仍然没有成功。

以下是我的完整Python代码:

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg, NavigationToolbar2QTAgg
import matplotlib.figure as mfig
import PyQt4.QtGui as gui, PyQt4.QtCore as core
import collections
import time
import random

import serial
ser = serial.Serial('/dev/tty.usbmodem1411', 9600)
ser.write('S')


refreshMillis = 8
N = 200
xs = collections.deque(maxlen=N)
ys = collections.deque(maxlen=N) 

app = gui.QApplication([])

fig = mfig.Figure()
canvas = FigureCanvasQTAgg(fig)

ax = fig.add_subplot(111)
ax.set_ylim([0,5])
# ax.title("Arduino Electrocardiogram")
ax.set_xlabel("Time (ms)")
ax.set_ylabel("Voltage (V)")
line2D, = ax.plot(xs,ys)
canvas.show()


def process_line():
    line = ser.readline()
    data = map(float,line.split(" "))
    xs.append(data[0])
    ys.append(data[1])
    line2D.set_data(xs,ys)
    print data
    xmin, xmax = min(xs),max(xs)
    if xmin == xmax:
        ax.set_xlim([xmin,xmin+1])
    else:
        ax.set_xlim([xmin,xmax])
    canvas.draw()

    zipString = zip(xs,ys)
    f = open("plot_store","w")
    for line in zipString:
        f.write(" ".join(str(x) for x in line) + "\n")
    f.close()




timer = core.QTimer()
timer.timeout.connect(process_line)
timer.start(refreshMillis)

app.exec_()

ser.flush()
ser.close()

Tags: importdataiftimelineserialaxarduino
1条回答
网友
1楼 · 发布于 2024-06-07 22:33:47

我从Arduino连续剧开始的时候就知道了。当您打开串行连接(例如,通过Python)时,Arduino会重置,缺少接下来的几个字符。

我通常会这样做:

ser = serial.Serial('COM6', 9600)
time.sleep(3)
ser.write('Hello world')

希望能有所帮助。

相关问题 更多 >

    热门问题