Fun with Electronics and Coding
Short link to this page: bit.ly/db-tas-23-3
In this class, for beginning and experienced programmers and “digital makers”, you’ll create several fun projects combining coding with wiring up buttons, sensors and motors, while strengthening your programming skills, and being exposed to the big ideas of computer science.
Resources and Self-Directed Learning Time Activities
- Mr. Briccetti’s YouTube Channel with many programming lessons for you to explore on your own
- MakeCode
- Block-based Programming Environments
- MicroBlocks
- Blockly Games
- Snap!
- Run Snap!
- Snap! Reference Manual
- Snap! Crash Course
- “Why Do We Have to Learn This Baby Language?” from Brian Harvey, Teaching Professor Emeritus, University of California, Berkeley
- micro:bit Python editor
- Python Programming on repl.it
- p5.js
- Tinkercad
- Beauty and Joy of Computing Curricula
- BJC Sparks for Middle School and Early High School
- BJC for High School (you are free to explore this if you run out of things to do in the middle school curriculum)
- code.org
- Teachable Machine
- Create something with gates and Hot Wheels track
- Design something with Illustrator, cut with the laser cutter, and assemble
- Create something and 3D print it
Hardware
We’ll work with several tiny computers and microcontrollers including some of the following:
The Raspberry Pi is a full-featured, but small, computer.
The Circuit Playground Express is less powerful than the Raspberry Pi, but includes many sensors and lights, and consumes less power.
The Arduino is a very popular microcontroller, with a large community creating software for it.
Software
- Python is one of the most popular programming languages, and it’s suitable for beginning programmers as well as professionals.
- JavaScript/TypeScript is another of the most popular programming languages.
- C++ is used for programming Arduinos.
- MakeCode for Circuit Playground Express makes it easy to program the CPX using blocks.
- Tinkercad Circuits lets you try out your electronics circuits in a simulator before assembling them with real components.
Projects
The best projects might be the ones students come up with themselves, but here are some ideas:
Multiplayer Reaction/Memory Lights Game
Inspired by Simon game
Features:
- Raspberry Pi tiny computer
- Python and TypeScript (a better JavaScript) programming languages
- making a web application (webapp) with the Flask framework
- Hypertext Markup Language (HTML) and Cascading Style Sheets (CSS)
- electronics fundamentals
- connecting components on a breadboard
- reading button presses
- lighting multicolor LEDs
Smart Thermostat
Make a smart thermostat to control your home temperature.
Dave’s YouTube Electronics Playlist should provide more ideas.
The Teacher
Dave Briccetti is a highly skilled programmer and experienced computer science teacher. Watch him teach on his YouTube channel.
Bring to Class
Bring your own laptop computer running macOS, Windows, or Linux, or use one provided by the school. The school will provide hardware to use during the class, and you’re welcome to bring your own hardware.
Circuit Wiring
Button Battery and LED
Connect the LED’s long lead (wire) to the positive (+) side of the battery.
Lighting an LED On a Breadboard
micro:bit
We’ll use the micro:bit. They have a lot of features, including:
- LEDs
- sound
- sensors (light, heat, acceleration, etc.)
- motor control ability
Breakout Boards
A breakout board makes it easier to connect a device such as the micro:bit to other components. It is easier to connect a servo motor to the micro:bit because the breakout board has headers, pins that connect directly to the servo’s female connectors.
Trying Out the micro:bit
Use the USB cable in the kit to connect the micro:bit to your computer. Be gentle. The micro:bit should power up and then engage you for a few minutes in an interesting way that shows some of its features.
Connect to the Breakout Board
Gently insert the micro:bit into the connector on the breakout board.
Connect the Servo
Make a Program
We’ll use MakeCode.
Here’s Dave’s example.
Download Directly to the micro:bit (No Drag and Drop Needed)
This requires Chrome or Edge. Click on the gear icon and choose Connect device. Once connected, push Download and that’s all that’s needed.
Battery Pack
You can disconnect the micro:bit from the computer once you have it programmed, and instead power it from a battery pack. Connect the battery pack as shown here (red to +, black to -). When disconnecting, don’t pull the wires. Pull on the plastic piece instead.
Play Time
Play with the servo, the LEDs, sound, the accelerometer, whatever you like! Make something.
Radio Communication
This is one of Dave’s favorite features. These devices can communicate with each other using radio transmissions. If we have time we’ll play with it.
Explore Tutorials and Play
We learned that # is not called a hashtag. It’s an octothorp, pound sign, number sign, or hash. (A hashtag is made up of a hash followed by a tag.)
Here is a game idea:
from random import randint
player_name = input('What is your name? ').lower()
special_mode = player_name in ['mom', 'dad', 'sue']
tokens = 10
while tokens > 0:
print('You have', tokens, 'tokens')
bet = min(tokens, int(input('How much do you bet? ')))
number = randint(1, 5)
guess = int(input('Guess the number from 1 to 5: '))
if guess == number and not special_mode:
tokens += bet * 5
print('Right!')
else:
tokens -= bet
print('Too bad')
We wrote programs on the Circuit Playground Express with blocks:
- turn on a pattern of light colors
- make a light move in circles around the CPX
Python
Math quiz game
from random import randint
from time import time
right = 0
wrong = 0
while True:
m1 = randint(2, 9)
m2 = randint(11, 99)
product = m1 * m2
start_time = time()
answer = int(input(f'{m1} × {m2} = ? (Enter 0 to stop) '))
if answer == 0:
break
stop_time = time()
duration = stop_time - start_time
if answer == product:
right += 1
print(f'Right, in {duration:.2f} seconds')
else:
wrong += 1
print('wrong')
print(f'You got {right} right and {wrong} wrong')
We used the Talking Name Picker to quiz students on parts of the program.
Python
Silly Sentences
from random import choice
from time import sleep
adjectives = ['silly', 'happy', 'playful']
nouns = ['monkey', 'grocer', 'fisherman', 'turkey', 'boy', 'girl']
verbs = ['jumps', 'walks', 'eats', 'swims', 'plays']
adverbs = ['quickly', 'eagerly', 'reluctantly', 'menacingly']
while True:
print(f'The {choice(adjectives)} {choice(nouns)} {choice(verbs)} {choice(adverbs)} ')
sleep(2)
Turtle Graphics
from turtle import fd, lt
def polygon(sides):
for _ in range(sides):
fd(200)
lt(360 / sides)
polygon(5)
polygon(6)
input()
Reaction/Memory Game
We’ll start working on a multiplayer game where you have to push buttons matching a sequence received from the game server (another micro:bit), and be correct, and be faster than the other players.
Server Code
sequence_length = 2
def make_sequence() -> str:
global sequence_length
seq = ''
for _ in range(sequence_length):
seq += '12'[randint(0, 1)]
sequence_length += 1
return seq
def send_sequence():
radio.send_value("pattern", int(make_sequence()))
def on_received_value(name, value):
if name == 'winner':
basic.show_number(radio.received_packet(RadioPacketProperty.SERIAL_NUMBER))
basic.show_icon(IconNames.HEART)
basic.pause(1000)
basic.clear_screen()
radio.on_received_value(on_received_value)
input.on_logo_event(TouchButtonEvent.PRESSED, send_sequence)
Client Code
current_seq = ''
responding = False
remaining_seq = ''
def on_received_value(name, value):
global remaining_seq
if name == 'pattern':
for letter in str(value):
if letter == '1':
basic.show_leds("""
##...
##...
##...
##...
##...
""")
else:
basic.show_leds("""
...##
...##
...##
...##
...##
""")
basic.clear_screen()
basic.pause(100)
responding = True
remaining_seq = str(value)
def check_for_win():
if not remaining_seq:
radio.send_value("winner", 0)
basic.show_icon(IconNames.HEART)
basic.pause(2000)
basic.clear_screen()
def process_response(button_char: str):
global remaining_seq
if remaining_seq:
if remaining_seq[0] == button_char:
remaining_seq = remaining_seq[1:]
check_for_win()
else:
basic.show_icon(IconNames.CONFUSED)
remaining_seq = ''
def on_button_pressed_a():
process_response('1')
def on_button_pressed_b():
process_response('2')
radio.on_received_value(on_received_value)
input.on_button_pressed(Button.A, on_button_pressed_a)
input.on_button_pressed(Button.B, on_button_pressed_b)
Python
Storing more complicated data
- lists
- dictionaries
Reverse Guessing Game
low = 1
high = 100
guess = 0
def produce_guess():
global guess
guess = (low + high) // 2
basic.show_number(guess)
def on_button_pressed_a():
global high
high = guess - 1
produce_guess()
def on_button_pressed_b():
global low
low = guess + 1
produce_guess()
input.on_button_pressed(Button.A, on_button_pressed_a)
input.on_button_pressed(Button.B, on_button_pressed_b)
produce_guess()
Programming Arduino using TinkerCad Circuits
Python Review and Quiz
- lists, dictionaries
- Reverse guessing game
RGB and Human Vision
TA Dorian Shows His 8-Bit Breadboard Computer Work in Progress
Circuit Wiring
Lighting an LED In TinkerCad Circuits
Why do we need a resistor?
Delayed Gate Controller Program for micro:bit
Snap! Project: Treasure Chest
Raspberry Pi Demo
Delayed Gate Controller Program for micro:bit
Beauty and Joy of Computing for Middle School
2023-07-24
- Makecode for micro:bit
- Intro to Python
- Self-directed learning time
2023-07-25
- Makecode for micro:bit
- Servos and radios
- Python
- Quiz on yesterday’s code
- Number guessing game, without the high and low responses
- p5.js
- Trying out the elevator sim
- Painting program
- noStroke, fill, rect, ellipse, mouseX, mouseY
2023-07-26
- Quiz on Makecode and p5.js
- Makecode boat project with radios and two micro:bits
- Quiz on Python
- Finish guessing game by adding high and low responses
- Make a math multiplication game
2023-07-27
- Quiz on Python
- Python with EduBlocks
- Number guessing game
- Coin toss simulator
2023-07-28
- Quiz on Python
- p5.js
- 3D
- a cube near each corner of the canvas (translate, box)
- 3D
- micro:bits and such
- different buttons send radio codes which, when received, cause different actions
2023-07-31
- Quiz on Python
- More Python
- functions
- including what they look like in 10 popular languages
- lists
- functions
2023-08-01
- Python quiz/practice
- functions
- lists
- Ultrasonic sensor with Makecode for micro:bit
2023-08-02
- Self-directed learning time
- Finish ultrasonic sensor project if you like
- Tinkercad circuits
- Battery pack with motor and switch
- Potentiometer
- Arduino programming
- Blinking the builtin LED and an external LED
- Burglar alarm with a passive infrared sensor
- Break
- Acropolis Robot, Mantis Demo
2023-08-03
- microblocks.fun
- Playstation VR2 fun
2023-08-04
- p5.js
- review of spinning cube
- moving rectangle
- HSB and changing hues, saturation, and brightness
- Python
- functions
- lists
- dictionaries