MicroCounter

Being a big fan of Python, I recently got a MicroPython Board.
MicroPython is a simple to use micro controller which runs Python 3. To put code onto it, you simple mount it as you would do with a USB flash drive, copy your main.py to it and restart your MicroPython.
As a simple “Hello world.” program, I wrote this counting script. Every time you press the built-in button, it counts up by one. Using the four built-in LEDs and binary number representation, this counter can count from 0 to 15 and then wraps back.

MicroCounter Counting


# Python 3 Code, MicroPython Implementation
# Jonathan Frech  9th of September, 2016
#         edited 23rd of September, 2016

# import
import pyb

# LEDs, switch and current number
leds = [pyb.LED(1), pyb.LED(2), pyb.LED(3), pyb.LED(4)]
sw = pyb.Switch()
n = 0

# update LEDs
def update():
	# go through LEDs
	for _ in range(0, len(leds)):
		# check if LED needs to be on or off
		if int( n/2**(_+1) ) % 2 == 0:
			leds[_].off()
		else:
			leds[_].on()

# main loop
while True:
	update()

	# check for the switch
	if sw():
		n += 1
		update()
		pyb.delay(100)

	# wait a bit
	else:
		pyb.delay(5)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s