Page 1 of 1

Run a function periodically

Posted: Thu Jan 03, 2019 9:12 am
by scardig
Hello,

I need to run a function every 200ms so here is some code. Am I on the right way ?

Code: Select all

def tick(timer):
	global master_timer
	if master_timer == 1:
		print("Alert") # exit/reset/....
	master_timer = 1
	
def main():
	global master_timer
	master_timer = 0
	tim = pyb.Timer(4, freq = 5)
	tim.callback(tick)

	while True:
		if master_timer == 1:
			#
			# --- My function here ---
			#
			master_timer = 0
		# feed a watchdog ?

Re: Run a function periodically

Posted: Thu Jan 03, 2019 3:17 pm
by Philosophix
You don't need a while True -loop if you only want to do something when the timer fires. You can have all your conditionals there. Why are you declaring a global master_timer in two places? Just put the master_timer = 0 at the top of the file outside the functions so you can then use it in the functions. Hard to say much more as I don't know what you are trying to accomplish with the timer. Why is the master_timer always set to 1 at the end of the tick function?

Re: Run a function periodically

Posted: Thu Jan 03, 2019 3:38 pm
by scardig
Every 200ms I need to read a sensor value via I2C and forward it via ethernet (the run time of my function should be << 200ms but something may go wrong). So every time the timer fires, master_timer is set to 1 and the IF statement in the main loop will continously check for it so that my funtion will run at a 200ms interval. Is it right ?

Re: Run a function periodically

Posted: Thu Jan 03, 2019 4:49 pm
by Philosophix
In that case the cose seems reasonable. Is it not working?

Re: Run a function periodically

Posted: Thu Jan 03, 2019 6:33 pm
by scardig
Philosophix wrote:
Thu Jan 03, 2019 4:49 pm
In that case the cose seems reasonable. Is it not working?
It's working well :) . I was asking if you can provide a review of the code to spot problems / provide a better solution.

Tnx