I have the following code in which I am trying to send time to an Arduino to be displayed on an OLED. the Arduino side works well, if commands are sent individually it will display. However, I want the time to be updated every second. With some tweaking I am able to get it to update ever 2 seconds or so, with sometimes showing two times at once. I tried using threading but I'm not sure if its correct or not. Here is the python script:
import serial
import kivy
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.widget import Widget
from datetime import datetime, timedelta
import time
from kivy.clock import Clock
import threading
ard_connected = False
try:
ard = serial.Serial(
port='COM10',
baudrate = 9600
)
ard.flush()
ard_connected = True
except:
print("Arduino Not Connected")
Builder.load_file('Layout.kv')
class GUILayout(Widget):
def ShowTime(self, state):
threading.Timer(1, self.ShowTime).start()
now = datetime.now()
a = timedelta(seconds=1)
while state == 'down':
if (ard_connected):
current_time = now.strftime("%H:%M:%S")
ard.write(current_time.encode())
ard.flush()
now += a
if (ard_connected):
ard.write(" ".encode())
ard.flush()
class GUI(App):
def build(self):
updateClock = GUILayout()
Clock.schedule_interval(updateClock.ShowTime, 0.5)
return updateClock
if __name__ == '__main__':
GUI().run()
and the .kv file:
<GUILayout>
BoxLayout:
orientation: "vertical"
size: root.width, root.height
GridLayout:
cols: 2
ToggleButton:
text: "Time"
on_state: root.ShowTime(self.state)
backgrund_normal: ""
background_color: (150/255,150/255,150/255,1)