Kivy - Label To Display Real-time Sensor Data
Solution 1:
It's totally possible. But you are missing a few things.
You are trying to connect to the serial port after running your app, that won't work as your app will be stopped when you arrive there. Instead, you want to do this part while your app runs. I would do the try/except to connect to arduino in app.build.
defbuild (self):
try:
self.arduino = serial.Serial('/dev/ttyACM0')
exept:
print("unable to connect to arduino :(")
Clock.schedule_interval(self.update, 1)
return Builder.load_file("main.kv")
then, you want to check for messages in the update method, but you don't want to block, so you only read the amount of data that is waiting in the buffer.
defupdate(self, *args):
arduino = self.arduino
data = arduino.read(arduino.inWaiting())
then you do your processing, i assume your data is something like:
A value
B value
in such case, you can parse it and update the corresponding variable, something like:
defupdate(self, *args):
arduino = self.arduino
data = arduino.read(arduino.inWaiting())
for line in data.split('\n'):
try:
sensor, value = line.strip().split(' ')
except:
print("parse error!")
continueif sensor == 'A':
self.sensor1 = float(value)
elif sensor == 'B':
self.sensor2 = float(value)
else:
print("unknown data! {}".format(line))
would do the job, it's a bit simplistic, as it assumes you always get full lines, but it can be improved later if needed (and it seems enough for a lot of cases in my experience).
Now, we need to make sure that our labels notice the changes of values, for this, kivy uses properties
, which are smarter attributes, you need to declare them on the app class.
classXGApp(App):
sensor1 =NumericProperty(0)
sensor2 = NumericProperty(0)
now, you can make your update display the value directly, through the app instance.
<ContScreen>:FloatLayoutorientation:'vertical'padding: [10,50,10,50]
spacing:50Label:id:'TempLabel1'text:str(app.sensor1)color:1,1,1,1font_size:80pos_hint: {'center_x':0.2, 'center_y':0.6}
Label:id:'TempLabel2'text:str(app.sensor2)color:1,1,1,1font_size:80pos_hint: {'center_x':0.5, 'center_y':0.6}
Post a Comment for "Kivy - Label To Display Real-time Sensor Data"