tags:

views:

382

answers:

3

Right now I am using an arduino to send data from an analog sensor to COM4. I am trying to make a python script that continuously monitors that data and looks for a certain parameter.

I tried something like this but it isn't alerting me correctly

import serial
from Tkinter import *
import tkMessageBox

port = "COM4"
ser = serial.Serial(port,9600)
value = 0

while 1:
    value = ser.read()
    if value > 400:
        tkMessageBox.showwarning(
            "Open file",)
    time.sleep(1)
A: 

If the serial package you are using is pySerial, take note of the definition of the Serial.read() method:

read(size=1)

Parameter: size – Number of bytes to read.

Returns: Bytes read from the port.

Read size bytes from the serial port. If a timeout is set it may return less characters as requested. With no timeout it will block until the requested number of bytes is read.

Changed in version 2.5: Returns an instance of bytes when available (Python 2.6 and newer) and str otherwise.

Although you are trying to process byte objects, you may (depending on Python version) be handling str or bytes (array) objects. These objects do not necessarily correspond to integer values.

Even when receiving byte objects from read(), the largest unsigned integer will be 255. Comparing value with 400 doesn't make sense. Try to find the type of the returned objects with a simple debugging output.

print type(value)

If you need to handle an str object, check the use of ord() for convertion.

(The flush suggestion refers to the original question, which used print, not tkinter).

See how-to-flush-output-of-python-print, and try the command line shell, not the IDE which may affect output buffering.

gimel
It isn't even catching my conditional when I don't print it out :(
jakke34
A: 

Instead of having the Arduino code relay all the analog values to COM4, have it relay a flag only when you meet the conditional.

So arduino code could be:

void loop() {
  sensorValue = analogRead(sensorPin);
  if (sensorValue >= 400){
    Serial.print("1"); // 1 will be the flag that will be sent to COM4
  }

Then your Python code can just look for the flag like this:

import serial
from Tkinter import *
import tkMessageBox

port = "COM4"
ser = serial.Serial(port,9600)
value = 0


while 1:
    value = ser.read();
    print value
    if value == "1":
        tkMessageBox.showwarning("BLAH", "BLAH\n")
        exit()
    else:
        continue
LogicKills
A: 

Assuming that you are using pySerial, serial.read() only reads one byte, which means a maximum value of 255. If your Arduino is sending string values back it's probably best to separate them with newline characters and use serial.readline().

Unless you have specific performance requirements sending strings back from the Arduino will make debugging significanly easier anyway.

Also if you are receiving strings back from the Arduino, your test should be if int(value) > 400:

Dan Head