You need to constantly monitor serial data in Python

Right now I'm using Arduino to send data from an analog sensor to COM4. I am trying to make a python script that constantly monitors this data and is looking for a specific parameter.

I tried something like this, but it does not warn 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)
+5
source share
3 answers

If the package serialyou are using is pySerial , pay attention to the definition of the Serial.read()method :

read(size=1)

Parameter: size - the number of bytes read.

Returns: bytes read from the port.

. - , . - , .

2.5: , (Python 2.6 ) str .

byte, ( Python) str bytes (array). .

byte read() 255. value 400 . .

print type(value)

str, ord() .

( flush , print, tkinter).

. how-to-flush-output-of-python-print , IDE, .

+3

, Arduino COM4, ​​ , .

, arduino :

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

Python :

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
0

, pySerial, serial.read() , 255. Arduino , , serial.readline().

Unless you have specific performance requirements, sending strings from Arduino will make debugging much easier.

Also, if you are returning rows from Arduino, your test should be if int(value) > 400:

0
source

All Articles