I'm implementing a simply arduino project that read values from a temperature sensor and print it on Serial when the user sends the command '0;'.
In the Arduino I'm using CmdMessenger to handle the commands as snippet on the bottom of page. It seams to work, since I successful interact with it via Serial Monitor. But what I want is communicating with it via a Python programming using pySerial. So I implement the piece of code below. The program runs, but it seems it's not sending data to serial correctly.
Py main program:
from temp_read import *
dObject = Temperature('COM3')
print dObject.queryTemperature()
Py class:
import serial
class Temperature:
def __init__(self, comPath='/dev/ttyACM0', bauds=115200):
self.serialConnection = serial.Serial(comPath, bauds, timeout=0)
def queryTemperature(self):
if (not self.serialConnection.isOpen()):
self.serialConnection.open()
# prints True:
print self.serialConnection.isOpen()
self.serialConnection.write(bytes(b'0;\r'))
while self.serialConnection.inWaiting() == 0:
pass
# don't reach this point. It stops on loop above
iw = self.serialConnection.inWaiting()
temp = (self.serialConnection.read(iw))
return temp
Sketch
#include <CmdMessenger.h>
#include <OneWire.h>
#include <DallasTemperature.h>
int pinTemp = 13;
CmdMessenger cmdMessenger = CmdMessenger (Serial);
OneWire oneWire (pinTemp);
DallasTemperature sensors (&oneWire);
enum {
kReadTemperature,
kStatus,
};
void attachCommandCallbacks (){
cmdMessenger.attach (onUnknownCommand);
cmdMessenger.attach (kReadTemperature, onReadTemperature);
}
void onStatus (){
Serial.println ("status");
}
void onUnknownCommand (){
Serial.println ("unknow");
}
void onReadTemperature (){
Serial.println ("readTemp");
sensors.requestTemperatures();
delay (1500);
float temp = sensors.getTempCByIndex(0);
cmdMessenger.sendCmd(kStatus, (float) temp);
}
void setup() {
Serial.begin(115200);
sensors.begin ();
cmdMessenger.printLfCr();
attachCommandCallbacks();
}
void loop() {
cmdMessenger.feedinSerialData();
}
UPDATE: when I run the python program in debug mode with pycharm it works.