hawkar
hawkar

Reputation: 159

Sending a character to the Arduino serial port using Python's Pyserial

I have setup an Arduino to send data when it receives an 'S' byte. This works in the Arduino serial monitor. However, I am plotting the data on Python, using Pyserial to contact the serial port. Here is my Arduino sketch to make clear what I am saying:

#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);
}

As I said this works fine. But on Python when I try this:

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

or this:

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

The arduino doesn't recieve it for some reason and the data doesn't flow through the serial port to Python. I do not know the problem. As you can see I have tried converting to bytes and it still doesn't work.

Here is my full Python code:

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()

Upvotes: 2

Views: 13601

Answers (1)

Grant Gibson
Grant Gibson

Reputation: 813

This caught me out when I started with Arduino serial. When you open the serial connection (e.g. via Python) the Arduino resets, missing the next few characters.

I usually do something like:

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

Hope that helps.

Upvotes: 6

Related Questions