Run a function periodically

The official pyboard running MicroPython.
This is the reference design and main target board for MicroPython.
You can buy one at the store.
Target audience: Users with a pyboard.
Post Reply
scardig
Posts: 18
Joined: Wed Jan 10, 2018 8:32 am

Run a function periodically

Post by scardig » Thu Jan 03, 2019 9:12 am

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 ?

Philosophix
Posts: 24
Joined: Wed Jan 02, 2019 11:45 am

Re: Run a function periodically

Post by Philosophix » Thu Jan 03, 2019 3:17 pm

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?

scardig
Posts: 18
Joined: Wed Jan 10, 2018 8:32 am

Re: Run a function periodically

Post by scardig » Thu Jan 03, 2019 3:38 pm

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 ?

Philosophix
Posts: 24
Joined: Wed Jan 02, 2019 11:45 am

Re: Run a function periodically

Post by Philosophix » Thu Jan 03, 2019 4:49 pm

In that case the cose seems reasonable. Is it not working?

scardig
Posts: 18
Joined: Wed Jan 10, 2018 8:32 am

Re: Run a function periodically

Post by scardig » Thu Jan 03, 2019 6:33 pm

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

Post Reply