SlideShare uma empresa Scribd logo
1 de 88
IOT BOOTCAMP
Featuring MicroPython and the ESP32
Marcus Tarquinio
COURSE STRUCTURE
• Lesson 1 – Introduction: IoT, Microcontrollers and a bit of history
• Lesson 2 – Getting started with MicroPython and VS Code
• Lesson 3 – Blinking LEDs and writing your first program
• Lesson 4 – Pulse Width Modulation and its applications
• Lesson 5 – Neopixels, Pyroelectric Infrared sensor and interrupts
• Lesson 6 – Connecting to the internet and using cloud services
• Lesson 7 – Measuring temperature, humidity, distance …
• Lesson 8 – Connected Weather Station
LESSON 1 – INTRODUCTION: IOT, MICROCONTROLLERS AND A BIT OF HISTORY
• What is the goal of this Bootcamp?
• How are the LABs structured?
• IoT
• Microcontrollers, Single Board Computers and more
• Arduino, Raspberry PI
• Espressif (ESP8266 and ESP32)
• Demo
• Moore's Law - After four decades
• M5Stack and the hardware kit
GOAL
Inspire you to build
IoT solutions yourself
• We structured the LABs so people with different
backgrounds can take the most out of them:
• The first slide of each LAB explains what is the expected
outcome of the exercise… if you know how to do it please
give it a try without looking at following slides.
• The detailed instructions have all the steps required to
complete the LAB including the code.
• Some LABs have a Challenge session – the idea here is to
offer possibilities to explore beyond the scope of this
training.
LABS
IOT
• Microcontrollers + wireless communications Damien George
• Typical Examples:
• Nest Thermostat, Philips Hue, predictive maintenance…
Fujitsu’s connected cow
1979 - DHRYSTONE MIPS
VAX 11/780
Dhrystone is a synthetic
computing benchmark intended
to be representative of system
integer performance.
A common representation of
the Dhrystone benchmark is the
DMIPS (Dhrystone MIPS)
obtained when the Dhrystone
score is divided by Dhrystones
per second obtained on the
VAX 11/780.
Computer Clock Speed RAM Cost * DMIPS
VAX 11/780 5 MHz 2 MB $520 000 1
* 150k USD converted into today’s money
FEW YEARS LATER IN 1982
Computer Microprocessor Clock Speed RAM ROM Cost * DMIPS
TK82-C ZILOG Z80A 3,25 MHz 2 KB 8 KB $260 0.58
• Sinclair ZX81 clone
• Based on the ZILOG Z80
microprocessor
* 99 USD converted into today’s money
• Born in Italy in 2005
• Platform based on the Atmel Microcontrollers
• Open source and extensible
• Many shields avaliable
• Great IDE with many libraries
• Limitations
• No built-in wireless connectivity
• Limited processing power
ARDUINO - PROGRAMING MICROCONTROLLERS MADE EASY
Microcontroller Clock Speed RAM ROM Cost DMIPS
AVR ATmega328P 16 MHz 2 KB 32 KB Flash 20 € 10 DMIPS
• Started shipping in 2012
• ARM based developed by UK foundation
• Great processing power
• Huge software repository
• Limitations (for IoT use)
• Energy requirements
• Full OS
RASPBERRY PI - $35 SINGLE BOARD COMPUTER
Microprocessor Clock RAM ROM DMIPS
BCM2711 4 cores 1.5 GHz 1/2/4 GB MicroSD 7 440
ESP8266
• Microcontroller with built-in Wi-Fi
• Introduced in 2014 by Espressif
• Originally used in Wi-Fi modules
… until someone looked at the specs
• Very low price (a couple of dollars)
• Large open source community
Microcontroller Clock Speed RAM ROM DMIPS
Tensilica Xtensa L106 80-160 MHz 160 KB 4 MB Flash 113
• Introduced at the end of 2016
• Faster MCU
• More RAM
• Bluetooth 4.2 and BLE
• More GPIOs
• Capacitive touch inputs
• Temperature sensor
• HAL effect sensor
• Secure boot
ESP32
ESP32
Tensilica
Xtensa LX6
32 bit
2 cores* plus
ULP
160-240 MHz
512 KB RAM
+ 4MB PSRAM
16 MB Flash
+ MicroSD
600 DMIPS*
<$12
• Manufactured on 40nm ULP
• Die size 2960 x 2850 µm
• ESP32-D0WD package
size is 5 x 5mm
ESP32
ESP32 DEVELOPMENT BOARDS
• Adafruit Feather HUZZAH32 $20
• SparkFun ESP32 Thing $22
• Espressif ESP32-PICO-KIT $15
• Picom WiPy 3.0 20€
DEMO 1.1
• Why do I bother you with all
those hardware details?
• After you create a working
prototype it is very easy to go
to the next steps:
• Build a couple of devices using
development boards
• Design your own custom Printed
Circuit Board (PCB) around the
ESP32 chip
MOORE'S LAW - AFTER FOUR DECADES
• Computer performance
• Memory capacity
• Reliability
• Size
• Price
• Power requirements
1970 2010
BREADBOARDS AND SOLDERING
• Typically you would use breadboards for electronics
prototyping and require soldering skills to get the
headers on development boards, sensors and actuators
M5Stack is a (nice) ESP32 based development kit. It has a
320x240 TFT screen, three buttons, SD card slot, internal
speaker and a 9-Axis sensor.
M5STACK
HARDWARE KIT
M5Stack
Fan moduleRGB LEDs
abridgedabridgedabridged
LESSON 2 – GETTING STARTED WITH MICROPYTHON AND VS CODE
• Getting familiar with MicroPython
• Uploading firmware
• LAB
• Visual Studio DEMO
• LAB
• Lesson 0 (pre-requisites)
WHAT IS MICROPYTHON?
• MicroPython is a lean and efficient implementation of Python 3
• It has been optimized to run on microcontrollers and constrained environments
• Yet it is compact enough to run within 256k of code space and 16k of RAM
• MicroPython aims to be as compatible with normal Python as possible,
enabling code to be easily reused on microcontrollers
WHY MICROPYTHON?
• Easy to learn, powerful for advanced users: shallow but long learning curve
• Unlike C/C++, MicroPython code is very readable (easy to maintain)
• The interactive Read-Evaluate-Print Loop (REPL) allows for instant gratification.
You connect to the board and have it execute code without any need for
compiling or uploading - perfect for quick learning and prototyping
• "Unlike the Raspberry Pi, the MicroPython allows you easy access to the bare-
metal of the hardware, which means you can do time-critical operations without
worrying about an operating system getting in your way“
Damien George
GOTO Amsterdam 2016: MicroPython & the Internet of Things
WHY MICROPYTHON?
• Comparing MicroPython to C++ (Arduino) experience
GETTING AND DEPLOYING THE MICROPYTHON FIRMWARE
• The firmware is the MicroPython compiled code. Unlike the Arduino
environment we will flash it once to the M5Stack and use it with different
applications written in high level language.
• Official daily builds are available here.
• For best results it is recommended to erase the entire flash of your device
before putting on new MicroPython firmware.
esptool --chip esp32 --port [COMx] erase_flash
• Syntax to deploy the firmware.
esptool --chip esp32 --port [COMx] --baud 460800 write_flash -z 0x1000
esp32spiram-20190529-v1.11.bin
HANDS-ON LAB 2.1 - UPLOADING FIRMWARE
Goal:
• Upload the official MicroPython firmware into M5Stack
• Connect to the REPL on the M5Stack using VS Code and
run some code
Required:
• M5Stack
• USB cable
• Copy of Esptool and MicroPython firmware
HANDS-ON LAB 2.1 - DETAILED INSTRUCTIONS
Step 1
• Connect the M5Stack to the computer using the provided USB cable
• Open Device Manager (Windows key + “device manager”)
• Take a note of the COM
port number allocated
• It will be the one with
“Silicon Labs CP210x”
HANDS-ON LAB 2.1 - DETAILED INSTRUCTIONS
Step 2
• Now let’s flash the MicroPython firmware to the M5Stack device
• In other words, you will copy MicroPython to the non-volatile memory on the device
• Copy esptool.exe and esp32spiram-20190529-v1.11.bin files to a folder on your
computer
• Open a command prompt (Windows key + “cmd”) and change the directory to the folder
where you have the two files
• Run the following commands replacing [COMx] by the COM port you identified on step 1
esptool --chip esp32 --port [COMx] erase_flash
esptool --chip esp32 --port [COMx] --baud 460800 write_flash -z 0x1000 esp32spiram-20190529-v1.11.bin
HANDS-ON LAB 2.1 - DETAILED INSTRUCTIONS
HANDS-ON LAB 2.1 - DETAILED INSTRUCTIONS
Step 3
• Now that M5Stack has the MicroPython firmware, let’s configure Visual Studio
Code (Pymakr) and connect to the device
If you didn’t install all the prerequisites please start with them (Lesson 0 slides at
the end of the deck)
HANDS-ON LAB 2.1 - CONNECTING VIA SERIAL USB
• Let’s take a few steps to configure the Pymakr extension for first time use.
• Here are the steps:
• Connect your M5Stack device to your computer via USB
• Open Visual Studio Code and check if the Pymakr Plugin has been correctly installed
HANDS-ON LAB 2.1 - CONNECTING VIA SERIAL USB
• Click All commands on the bottom of the Visual Studio Code window and in the list that
appears on the top, click Pymakr > Extra > List Serial Ports. This will list the available
serial ports. If Pymakr is able to auto-detect which port to use, it will be copied to your
clipboard. If not, just manually copy the correct serial port.
HANDS-ON LAB 2.1 - CONNECTING VIA SERIAL USB
• Once again click All commands, then click Pymakr > Global Settings. This will open the
pymakr.json configuration file. Paste the serial address you copied earlier into the field
address. Make sure auto_connect is set to false and then save the file (Ctrl-S).
HANDS-ON LAB 2.1 - CONNECTING VIA SERIAL USB
• Finally make sure you saved the JSON file! Clicking on Pycom Console connects and
disconnects the board
• The Pymakr console should show three arrows >>>, indicating that you are connected.
If it doesn’t, just restart VS Code and/or reset M5Stack.
HANDS-ON LAB 2.1 - RUNNING SOME CODE
• You can type MicroPython code directly on the REPL (Read Evaluate Print Loop).
• This code was executed on the ESP32 microcontroller on the M5Stack. You computer is
only sending the code and reading the output via serial port (like a terminal).
print("Hello ArcelorMittal!")
DEMO 2.1 - USING VS CODE
• Opening folders
• Interface overview
• Pymakr Package
• Upload/Download
• REPL:
• CTRL-C: Stop any running code
• CTRL-D: Soft reset
• CTRL-E: Paste mode
HANDS-ON LAB 2.2 - CREATE AN ACCOUNT ON OPENWEATHERMAP
Goal
• Create an account on OpenWeatherMap
• We will use this cloud service later today to get whether forecast
but It takes a couple of hours for the account activation
Required:
• Your PC with a web browser, internet connectivity and an email
address
• Sign up for an free account here
HANDS-ON LAB 2.2 - DETAILED INSTRUCTIONS
• Check if you received the
OpenWeatherMap Create Account email
HANDS-ON LAB 2.2 - DETAILED INSTRUCTIONS
LESSON 3 – BLINKING LEDS AND WRITING YOUR FIRST PROGRAM
• GPIOs
• RGB LED
• Buttons
• LAB
• A general-purpose input/output (GPIO) is an uncommitted digital signal
pin on an integrated circuit or electronic circuit board whose behavior—
including whether it acts as input or output—is controllable by the user at
run time.
GPIOS
• When we program the GPIO as Output we can control a external device.
GPIOS - OUTPUT
• The traditional first program for hobby electronics is a
blinking light. So let’s blink a three color LED!
• An RGB (Red, Green, Blue) LED look just like regular LEDs,
however, inside its package there are actually three LEDs, one
red, one green and one blue.
RGB LED
• Let’s connect a RGB LED to the M5Stack (ESP32) GPIOs ports. As the name
says, GPIOs are generic pins whose behavior - including whether it is an
input or output pin - is controllable by code.
DEMO 3.1 - GPIOS AND THE MACHINE MODULE
import machine
BlueLED = machine.Pin(26, machine.Pin.OUT)
• In MicroPython we use the Pin function from the
machine module. After importing the machine module,
we pass the GPIO port number as the first parameter
of the Pin function.
• Note that the second parameter configures the GPIO as output.
• The value() method is used to turn the blue LED on and off.
DEMO 3.1 - GPIOS AND THE MACHINE MODULE
BlueLED.value(1)
BlueLED.value(0)
Warning: we are applying 3.3 V directly into the LEDs – that is
above the maximum forward voltage for the Red one.
It is best practice to use a resistor in series with LEDs.
• To make it blink we can use an infinite loop.
• Although the code above will make the LED blink, it does it so fast we can’t
see it. By adding half a second between the changes we can observe it. That
can be done by using the sleep function from the time module.
DEMO 3.1 – WHILE LOOP AND THE TIME MODULE
while True:
BlueLED.value(1)
BlueLED.value(0)
import time
while True:
BlueLED.value(1)
time.sleep(0.5)
BlueLED.value(0)
time.sleep(0.5)
• But we have three LEDs so let’s use them.
• Note that Pin(0 or 1) is a shortcut for Pin.value(0 or 1).
DEMO 3.1 – MULTIPLE GPIOS AND THE THREE COLOR LED
import machine
Red = machine.Pin(21, machine.Pin.OUT)
Green = machine.Pin(22, machine.Pin.OUT)
Blue = machine.Pin(26, machine.Pin.OUT)
Red.value(1)
Red(0)
Blue(1)
Blue(0)
Green(1)
Green(0)
• When we program the GPIO as input we can measure the status of an external
device.
GPIOS - INPUT
• There is a large variety of switches and buttons
available.
• The M5Stack comes with three normally open active
low push buttons. They are connected to GPIOs 39, 38
and 37.
SWITCHES AND BUTTONS
• We can also import only the Pin class from the machine module. This way
we don’t need to reference “machine.” every time we use Pin. Besides, it is
more efficient when you don’t need all the classes from the module (saves
memory).
• The first parameter of the Pin function is the GPIO port number and the
second parameter configures the GPIO as input. To read the status of the
input we use the value method.
DEMO 3.2 – USING INPUT
from machine import Pin
A = Pin(39, Pin.IN)
A.value()
• When writing a program, often we need to test a condition and perform
some action based on this condition.
• In MicroPython that is how you do a simple if statement:
and this is how to do a if-else statement:
IF STATEMENTS
if condition:
indentedStatmentBlock
if condition:
indentedStatmentBlockForTrue
else:
indentedStatmentBlockForFalse
• We can use an if statement to test the status of the INPUT.
and an infinite loop to keep doing it forever.
DEMO 3.2 – IF STATEMENT
if A.value() == 0:
print("Do sommething")
while True:
if A.value() == 0:
print("Do sommething")
else:
print("Do something else")
• We can now write a small program that turns an LED on when a button is
pressed.
DEMO 3.2 – FIRST PROGRAM
from machine import Pin
Blue = Pin(26, Pin.OUT)
A = Pin(39, Pin.IN)
while True:
if A.value() == 0:
Blue(1)
else:
Blue(0)
HANDS-ON LAB 3.1 – LEDS AND BUTTONS
Goal
• Use the three buttons on the M5Stack to turn each of the
three colors LEDs on and off.
Required:
• M5Stack
• Three color LED and grove cables
• Connect your computer to the M5Stack using
the USB cable provided
• Connect the three colors LED to Ports A and
B on the M5Stack as showed
HANDS-ON LAB 3.1 - DETAILED INSTRUCTIONS
M5Stack LED
P
o
r
t
A
G21 Red
G22 Green
+
-
P
o
r
t
B
G26 Blue
G36
+
- GND
• Use VS Code to open the Lab-3.1 LEDs folder
• Select the file leds.py
HANDS-ON LAB 3.1 - DETAILED INSTRUCTIONS
• Review the code
• Now run it on the M5Stack:
• Select the code from the VS Code editor window (CTRL-A)
• Copy it to the clipboard (CTRL-C)
• Click on the terminal and put the REPL in PASTE mode (CTRL-E)
• Paste the code from the clipboard (CTRL-V)
• Exit the PASTE mode (CTRL-D)
• Test the code by pressing the buttons
• What happens when you press more than one button at
the same time?
• Press CTRL-C to stop the code execution.
HANDS-ON LAB 3.1 - DETAILED INSTRUCTIONS
• Although we have not done it on this
lesson, limiting the current into an LED is
very important. LEDs have a non-linear
behavior and its resistance quickly
drops as it turns on.
• To prevent the LEDs burning out a
limiting resistor should be added in
series with them. The value of the
resistor is calculated such that LED
characteristic (or recommended)
forward current is not exceed.
LED CURRENT LIMITING RESISTORS
i = LED forward current in Amps
Vf = LED forward voltage drop in Volts
Vs = supply voltage
LESSON 4 – PULSE WIDTH MODULATION AND ITS APPLICATIONS
• Pulse Width Modulation
• Blinky PWM version
• Fading LEDs
• Rainbow
• Fan Module
• LAB
• SG90 MicroServo
• As its name suggests, Pulse Width Modulation (PWM) is a technique where we
apply a series of “ON-OFF” pulses and vary the duty cycle. The duty cycle is
the percentage of time that the output is “ON” (3.3 Volts) compared to when
it is “OFF” (0 Volts).
PWM - PULSE WIDTH MODULATION
When creating an instance of the PWM class we need to pass ‘pin’, which is a
mandatory argument (‘freq’ and ‘duty’ are optional):
pwm = machine.PWM(pin [, freq=f] [, duty=d])
They can also be modified after creation:
pwm.freq([freq])
• sets the new pwm frequency to freq Hz
• without arguments it returns the current frequency
pwm.duty([duty])
• sets the new pwm duty cycle to duty from 0 to 1023
• without arguments it return the current pwm channel duty cycle
pwm.deinit() # turn off PWM on the pin
PWM - MICROPYTHON
• We can use PWM to blink the LED, achieving the same results as code with a
loop.
in this case the duty cycle is set to 50% (1024/2) and the frequency to 1 Hz or
one pulse per second. Note that the LED will blink in the background, controlled
by the dedicated hardware. This free up the program to do other things!
Let’s increase the frequency. Can you still perceive it blinking?
DEMO 4.1 - BLINKY PWM VERSION
from machine import Pin, PWM
BlueLED = PWM(Pin(26), freq=1, duty=512)
BlueLED.freq(10)
BlueLED.freq(30)
BlueLED.freq(60)
• If we blink the LED very fast, the human eye will no longer be able to see it blinking.
At high frequencies we will only perceive a brighter or dimmer light depending on the
duty cycle.
• By changing the duty cycle we control for how long we keep the LED on in each
period. Or, in other words, to modulate the pulse width.
pwm.deinit()
• DE initializes, frees up the PWM channel and stops PWM output
DEMO 4.1 - BLINKY PWM VERSION
BlueLED.deinit()
BlueLED.duty(300)
BlueLED.duty(100)
BlueLED.duty(700)
• We used so far while True: endless loops. Naturally we can use a logical
expression instead of True as the test condition for the while loop.
• The second ways to do loops in MicroPython is with for. A for loop is used for
iterating over a sequence. It is usually combined with the range() function.
• The range() function returns a sequence of numbers, starting from 0 by default,
and increments by 1 (by default).
LOOPS
while condition:
indentedStatmentBlock
for item in sequence:
indented statements to repeat; may use item
range([start,] sizeOfSequence [,step]))
start: Starting number of the sequence
sizeOfSequence: Generate numbers up to, but not
including this number
step: Difference between each number in the sequence
• By varying the duty cycle of the PWM pulse we can control the brightness of the LED.
• The first for loop starts from 0 and increases the duty cycle up to 1023. The second for loop
does the opposite, starting from 1024 and decreasing the brightness until 1. We need to
add a sleep (1 ms) step so the human eye can see the changes.
DEMO 4.2 - FADING LEDS
Note:
the LED is actually blinking at
the default PWM frequency
(5 kHz - 5000 times per second)
BlueLED.deinit()
from machine import Pin, PWM
from time import sleep
BlueLED = PWM(Pin(26), freq=5000, duty=0)
while True:
for i in range(1024):
BlueLED.duty(i)
sleep(0.001)
for i in range(1024, 0, -1):
BlueLED.duty(i)
sleep(0.001)
DEMO 4.2 - FADING LEDS
• Using PWM with the three LEDs
one can generate any color
DEMO 4.3 - MULTICOLOR LED
from machine import Pin, PWM
RedLED = PWM(Pin(21), duty=0)
GreenLED = PWM(Pin(22), duty=0)
BlueLED = PWM(Pin(26), duty=0)
RedLED.duty(round ( 1024*1/5 ) )
GreenLED.duty(round ( 1024*3/5 ) )
BlueLED.duty(round ( 1024*4/5 ) )
RedLED.deinit()
GreenLED.deinit()
BlueLED.deinit()
• Functions are a convenient way to divide your code into useful blocks, allowing us
to order our code, make it more readable, reuse it and save some time
• Once the function is defined you can invoke it
FUNCTIONS
def function_name(parameters):
indentedStatmentBlock
function_name(parameters)
• A nice “rainbow effect” can be obtained by fading
one LED while keeping the other two at the same level
DEMO 4.4 - RAINBOW
...
def fade(led, begin=0, end=1024, step=1):
for i in range(begin, end, step):
led.duty(i)
sleep(0.001)
...
while True:
fade(GreenLED) # Ramp up green
fade(RedLED, begin=1024,end=0,step=-1) # Ramp down red
fade(BlueLED) # Ramp up blue
fade(GreenLED, begin=1024,end=0,step=-1) # Ramp down green
fade(RedLED) # Ramp up red
fade(BlueLED, begin=1024,end=0,step=-1) # Ramp down blue
• Another way to implement the rainbow code is to use a technique called cross
fading. In this case we change the duty cycle of two LEDs at the same time.
CROSS FADING
DEMO 4.5 - CROSS FADING RAINBOW
from machine import Pin, PWM
from time import sleep
def crossFade(ledUp, ledDown, begin=0, end=1024):
for i in range(begin, end):
ledUp.duty(i)
ledDown.duty(1023-i)
sleep(0.002)
RedLED = PWM(Pin(21), duty=0)
GreenLED = PWM(Pin(22), duty=0)
BlueLED = PWM(Pin(26), duty=0)
while True:
crossFade(GreenLED, RedLED) # Ramp up green / ramp down red
crossFade(BlueLED, GreenLED) # Ramp up blue / ramp down green
crossFade(RedLED, BlueLED) # Ramp up red / ramp down blue
• The Fan motor module has an L9110 single motor driver
integrated circuit (IC). The IC has two inputs INA and INB,
and its output is connected to a small DC motor. This
implements an H-bridge, allowing us to drive the motor
forward or backwards by reversing the direction of the
voltage across it.
• Similarly to the LEDs we can change the motor speed by
varying the duty cycle of a PWM signal.
L9110 FAN MOTOR MODULE
• There are two ways to interface with an H-bridge.
• The first is by controlling both sides of the bridge directly.
DEMO 4.6 - L9110 FAN MOTOR MODULE
INA INB motor direction
False False Stop
False True Forward
True False Reverse
True True Stop
from machine import Pin
inA = Pin(21, Pin.OUT)
inB = Pin(22, Pin.OUT)
inA.value(0)
inB.value(1) # Forward
inB.value(0) # Stop
inA.value(1) # Reverse
... and the other method uses one pin as a PWM output (to set motor speed) and the
second as a digital output (to set its direction).
In this case, we control the direction and the speed of the motor.
DEMO 4.7 - L9110 FAN MOTOR MODULE WITH PWM
INA INB motor direction
False False Stop
False True Forward
True False Reverse
True True Stop
from machine import Pin, PWM
pwmFan = PWM(Pin(21))
reverseFan = Pin(22, Pin.OUT)
pwmFan.duty(717) # 70% duty cycle ( 70 * 1024 / 100 )
# pause
pwmFan.duty(307) # 30% duty cycle ( 30 * 1024 / 100 )
# pause
reverseFan.value(1)
HANDS-ON LAB 4.1 - FAN
Goal
• Attach the FAN module to an appropriate support and use the buttons
to control it:
A: reverse the fan rotation
B: increase the PWM duty cycle
C: decrease the PWM duty cycle
Required:
• M5Stack
• Groove cable
• Fan motor module
• LEGO assortment (to be used as support)
• Connect your computer to the M5Stack using the USB cable provided
• Connect the Fan Module to the M5Stack using the Grove cable and the
diagram below
HANDS-ON LAB 4.1 - DETAILED INSTRUCTIONS
M5Stack Cable FAN
P
o
r
t
A
G22 Yellow INB
G21 White INA
+ Red VCC
- Back GND
HANDS-ON LAB 4.1 - DETAILED INSTRUCTIONS
Warning: the Fan runs very fast so protect
your eyes and fingers!
• Use the LEGO assortment to build a stand
and attach the Fan module to the M5Stack.
Here goes some inspiration but fell free to
build it your way.
• Use VS Code to open the Lab-4.1 Fan
folder
• Select the file fan.py
• Review the code and copy and paste it to
the REPL to run it on the M5Stack
• Refer to Lab 3.1 if you don’t remember how
• Test the code by pressing the buttons
HANDS-ON LAB 4.1 - DETAILED INSTRUCTIONS
G22 G21 motor direction
False False Stop
False True Forward
True False Reverse
True True Stop
Servos are very handy little units, consisting of a motor, a
position sensor and a feedback loop. Rather than telling them
which way to turn, you tell them what position you want them
to be in and they move to that position.
They are controlled by a train of pulses:
- 1 ms will turn the servo one way
- 1.5 ms will put the servo in the middle
- 2 ms will turn it the other way
Servos are not all that precise, especially cheap ones, so if
you go past the acceptable range for the servo you may hear
it whine as it tries to move past its limits, or it may 'hunt'
(wiggle back and forth) if it isn't happy with the frequency of
the pulses. The allowable range of your servos is best
determined by trial and error.
SG90 MICRO SERVO
DEMO 4.8 - SG90 MICROSERVO
from machine import Pin, PWM
# Set the frequency to 50Hz (one cycle per 20ms)
pwmServo = PWM(Pin(26), freq=50, duty=8)
pwmServo.duty(77) # 20ms * 77 / 1024 = 1.50ms)
LESSON 0 – PRE-REQUISITES
• What do you need to install on your computer?
• NodeJS (10.16.2 LTS)
• Visual Studio Code (v1.37.0)
• Pymakr VS Code extension (1.1.3)
• SiLabs CP2104 Driver (v6.7.6)
LESSON 0 – PRE-REQUISITES
• NodeJS
• The first step is to get NodeJS installed on your PC (it is a pre-requisite to the VS Code
extension we will install next). Please download the latest LTS version available from the
NodeJS website.
LESSON 0 – PRE-REQUISITES
• Visual Studio Code
• We will also need you to download and install Visual Studio Code (if you already have it,
skip to the next step).
• Pymakr VS Code extension
• To install the Pymakr extension open VSCode
• Open the Extensions page (5th button in the left pane)
• Search for Pymakr and click the install button next to it
LESSON 0 – PRE-REQUISITES
• On the pymakr.json configuration file:
• Make sure you change the auto_connect
parameter from true to false
• M5Stack does not work well with auto connect
• Save the changes (Ctrl-S)
LESSON 0 – PRE-REQUISITES
LESSON 0 – PRE-REQUISITES
• SiLabs CP2104 Driver
• Download and install the SiLabs CP2104 Driver. Use the Windows 7/8/8.1 version.
• Do NOT use the Windows 10 Universal driver! If you happen to download the universal
version, you may need to manually revert to 6.7.6 on a regular basis as Windows will
repeatedly use the newer, incorrect driver after each Windows update.
https://m5stack.readthedocs.io/en/latest/get-started/establish_serial_connection.html
LESSON 0 – PRE-REQUISITES
• MicroPython
• We will need a copy
of the official
MicroPython
firmware for the
ESP32. Please
download the latest
stable version with
SPIRAM support
from the
micropython.org
website.
LESSON 0 – PRE-REQUISITES
• Esptool
• Finally we will need a copy of the Esptool from
Espressif. This is a Python based tool used to
program the ESP32 flash memory.
• To make it easier we will use a pre-compiled
version of it that can be downloaded as part
of the M5Stack M5Burner solution. The official
python version would work as well but it
requires Python on the host computer.
• Download and open M5Burner.zip
• Extract esptool.exe from the tools folder. We
will only need this file.

Mais conteĂşdo relacionado

Mais procurados

ESP32 IoT presentation @ dev.bg
ESP32 IoT presentation @ dev.bgESP32 IoT presentation @ dev.bg
ESP32 IoT presentation @ dev.bgMartin Harizanov
 
Ceis101 final joshua_brown
Ceis101 final joshua_brownCeis101 final joshua_brown
Ceis101 final joshua_brownJoshuaBrown233
 
Aurdino presentation
Aurdino presentationAurdino presentation
Aurdino presentationC.Vamsi Krishna
 
Digital Notice Board in Schools and Colleges by Implementing IoT with Audio A...
Digital Notice Board in Schools and Colleges by Implementing IoT with Audio A...Digital Notice Board in Schools and Colleges by Implementing IoT with Audio A...
Digital Notice Board in Schools and Colleges by Implementing IoT with Audio A...Associate Professor in VSB Coimbatore
 
Arduino & NodeMcu
Arduino & NodeMcuArduino & NodeMcu
Arduino & NodeMcuGuhan Ganesan
 
Reconnaissance of Virtio: What’s new and how it’s all connected?
Reconnaissance of Virtio: What’s new and how it’s all connected?Reconnaissance of Virtio: What’s new and how it’s all connected?
Reconnaissance of Virtio: What’s new and how it’s all connected?Samsung Open Source Group
 
Zach Murray CEIS 106 Project
Zach Murray CEIS 106 ProjectZach Murray CEIS 106 Project
Zach Murray CEIS 106 ProjectZacharyMurray8
 
IoT based Smart board for Displaying and Forwarding notices using Raspberry Pi
IoT based Smart board for Displaying and Forwarding notices using Raspberry PiIoT based Smart board for Displaying and Forwarding notices using Raspberry Pi
IoT based Smart board for Displaying and Forwarding notices using Raspberry PiSinthana Sambandam
 
Gemini Introduction
Gemini IntroductionGemini Introduction
Gemini IntroductionLynn Langit
 
IOTC08 The Arduino Platform
IOTC08 The Arduino PlatformIOTC08 The Arduino Platform
IOTC08 The Arduino PlatformEoin Brazil
 
[ZigBee 嵌入式系統] ZigBee 應用實作 - 使用 TI Z-Stack Firmware
[ZigBee 嵌入式系統] ZigBee 應用實作 - 使用 TI Z-Stack Firmware[ZigBee 嵌入式系統] ZigBee 應用實作 - 使用 TI Z-Stack Firmware
[ZigBee 嵌入式系統] ZigBee 應用實作 - 使用 TI Z-Stack FirmwareSimen Li
 
Yocto - Embedded Linux Distribution Maker
Yocto - Embedded Linux Distribution MakerYocto - Embedded Linux Distribution Maker
Yocto - Embedded Linux Distribution MakerSherif Mousa
 
Linux on ARM 64-bit Architecture
Linux on ARM 64-bit ArchitectureLinux on ARM 64-bit Architecture
Linux on ARM 64-bit ArchitectureRyo Jin
 
07 connection to the process v1.00_en
07 connection to the process v1.00_en07 connection to the process v1.00_en
07 connection to the process v1.00_enconfidencial
 
Graduation project "home automation system"
Graduation project "home automation system"Graduation project "home automation system"
Graduation project "home automation system"Mohamed Motamed
 

Mais procurados (20)

ESP32 IoT presentation @ dev.bg
ESP32 IoT presentation @ dev.bgESP32 IoT presentation @ dev.bg
ESP32 IoT presentation @ dev.bg
 
Ceis101 final joshua_brown
Ceis101 final joshua_brownCeis101 final joshua_brown
Ceis101 final joshua_brown
 
Aurdino presentation
Aurdino presentationAurdino presentation
Aurdino presentation
 
Digital Notice Board in Schools and Colleges by Implementing IoT with Audio A...
Digital Notice Board in Schools and Colleges by Implementing IoT with Audio A...Digital Notice Board in Schools and Colleges by Implementing IoT with Audio A...
Digital Notice Board in Schools and Colleges by Implementing IoT with Audio A...
 
Arduino & NodeMcu
Arduino & NodeMcuArduino & NodeMcu
Arduino & NodeMcu
 
Reconnaissance of Virtio: What’s new and how it’s all connected?
Reconnaissance of Virtio: What’s new and how it’s all connected?Reconnaissance of Virtio: What’s new and how it’s all connected?
Reconnaissance of Virtio: What’s new and how it’s all connected?
 
Skype
SkypeSkype
Skype
 
Zach Murray CEIS 106 Project
Zach Murray CEIS 106 ProjectZach Murray CEIS 106 Project
Zach Murray CEIS 106 Project
 
IoT based Smart board for Displaying and Forwarding notices using Raspberry Pi
IoT based Smart board for Displaying and Forwarding notices using Raspberry PiIoT based Smart board for Displaying and Forwarding notices using Raspberry Pi
IoT based Smart board for Displaying and Forwarding notices using Raspberry Pi
 
EMBEDDED C
EMBEDDED CEMBEDDED C
EMBEDDED C
 
Gemini Introduction
Gemini IntroductionGemini Introduction
Gemini Introduction
 
IOTC08 The Arduino Platform
IOTC08 The Arduino PlatformIOTC08 The Arduino Platform
IOTC08 The Arduino Platform
 
[ZigBee 嵌入式系統] ZigBee 應用實作 - 使用 TI Z-Stack Firmware
[ZigBee 嵌入式系統] ZigBee 應用實作 - 使用 TI Z-Stack Firmware[ZigBee 嵌入式系統] ZigBee 應用實作 - 使用 TI Z-Stack Firmware
[ZigBee 嵌入式系統] ZigBee 應用實作 - 使用 TI Z-Stack Firmware
 
Platform Drivers
Platform DriversPlatform Drivers
Platform Drivers
 
Yocto - Embedded Linux Distribution Maker
Yocto - Embedded Linux Distribution MakerYocto - Embedded Linux Distribution Maker
Yocto - Embedded Linux Distribution Maker
 
Getting started with BeagleBone Black - Embedded Linux
Getting started with BeagleBone Black - Embedded LinuxGetting started with BeagleBone Black - Embedded Linux
Getting started with BeagleBone Black - Embedded Linux
 
Linux on ARM 64-bit Architecture
Linux on ARM 64-bit ArchitectureLinux on ARM 64-bit Architecture
Linux on ARM 64-bit Architecture
 
07 connection to the process v1.00_en
07 connection to the process v1.00_en07 connection to the process v1.00_en
07 connection to the process v1.00_en
 
Graduation project "home automation system"
Graduation project "home automation system"Graduation project "home automation system"
Graduation project "home automation system"
 
Embedded TCP/IP stack for FreeRTOS
Embedded TCP/IP stack for FreeRTOSEmbedded TCP/IP stack for FreeRTOS
Embedded TCP/IP stack for FreeRTOS
 

Semelhante a Iot Bootcamp - abridged - part 1

Tos tutorial
Tos tutorialTos tutorial
Tos tutorialmanikainth
 
microbit Microbit programming Microbit programming
microbit Microbit programming Microbit programmingmicrobit Microbit programming Microbit programming
microbit Microbit programming Microbit programmingssuser5feb2c1
 
Introduction to FreeRTOS
Introduction to FreeRTOSIntroduction to FreeRTOS
Introduction to FreeRTOSICS
 
Developing micro controller applications
Developing micro controller applicationsDeveloping micro controller applications
Developing micro controller applicationsSteve Mylroie
 
A Reimplementation of NetBSD Based on a Microkernel by Andrew S. Tanenbaum
A Reimplementation of NetBSD Based on a Microkernel by Andrew S. TanenbaumA Reimplementation of NetBSD Based on a Microkernel by Andrew S. Tanenbaum
A Reimplementation of NetBSD Based on a Microkernel by Andrew S. Tanenbaumeurobsdcon
 
Republic of IoT 2018 - ESPectro32 and NB-IoT Workshop
Republic of IoT 2018 - ESPectro32 and NB-IoT WorkshopRepublic of IoT 2018 - ESPectro32 and NB-IoT Workshop
Republic of IoT 2018 - ESPectro32 and NB-IoT WorkshopAlwin Arrasyid
 
Track 5 session 5 - st dev con 2016 - stm32 hands on seminar - cloud connec...
Track 5   session 5 - st dev con 2016 - stm32 hands on seminar - cloud connec...Track 5   session 5 - st dev con 2016 - stm32 hands on seminar - cloud connec...
Track 5 session 5 - st dev con 2016 - stm32 hands on seminar - cloud connec...ST_World
 
Embedded systems introduction
Embedded systems introductionEmbedded systems introduction
Embedded systems introductionSagar Adroja
 
Embedded Systems Introduction
Embedded Systems IntroductionEmbedded Systems Introduction
Embedded Systems IntroductionSagar Adroja
 
Null mumbai-iot-workshop
Null mumbai-iot-workshopNull mumbai-iot-workshop
Null mumbai-iot-workshopNitesh Malviya
 
Webinar: STM32WB - microcontrolador dual-core certificado BLE 5.0
Webinar: STM32WB - microcontrolador dual-core certificado BLE 5.0Webinar: STM32WB - microcontrolador dual-core certificado BLE 5.0
Webinar: STM32WB - microcontrolador dual-core certificado BLE 5.0Embarcados
 
Sistem mikroprosessor
Sistem mikroprosessorSistem mikroprosessor
Sistem mikroprosessorfahmihafid
 
EE6602 Embedded System
EE6602 Embedded SystemEE6602 Embedded System
EE6602 Embedded Systemrmkceteee
 
BSides LV 2016 - Beyond the tip of the iceberg - fuzzing binary protocols for...
BSides LV 2016 - Beyond the tip of the iceberg - fuzzing binary protocols for...BSides LV 2016 - Beyond the tip of the iceberg - fuzzing binary protocols for...
BSides LV 2016 - Beyond the tip of the iceberg - fuzzing binary protocols for...Alexandre Moneger
 
C# on a CHIPs
C# on a CHIPsC# on a CHIPs
C# on a CHIPsMirco Vanini
 
IoT: Internet of Things with Python
IoT: Internet of Things with PythonIoT: Internet of Things with Python
IoT: Internet of Things with PythonLelio Campanile
 
Summer training embedded system and its scope
Summer training  embedded system and its scopeSummer training  embedded system and its scope
Summer training embedded system and its scopeArshit Rai
 

Semelhante a Iot Bootcamp - abridged - part 1 (20)

Tos tutorial
Tos tutorialTos tutorial
Tos tutorial
 
microbit Microbit programming Microbit programming
microbit Microbit programming Microbit programmingmicrobit Microbit programming Microbit programming
microbit Microbit programming Microbit programming
 
Introduction to FreeRTOS
Introduction to FreeRTOSIntroduction to FreeRTOS
Introduction to FreeRTOS
 
Developing micro controller applications
Developing micro controller applicationsDeveloping micro controller applications
Developing micro controller applications
 
A Reimplementation of NetBSD Based on a Microkernel by Andrew S. Tanenbaum
A Reimplementation of NetBSD Based on a Microkernel by Andrew S. TanenbaumA Reimplementation of NetBSD Based on a Microkernel by Andrew S. Tanenbaum
A Reimplementation of NetBSD Based on a Microkernel by Andrew S. Tanenbaum
 
Republic of IoT 2018 - ESPectro32 and NB-IoT Workshop
Republic of IoT 2018 - ESPectro32 and NB-IoT WorkshopRepublic of IoT 2018 - ESPectro32 and NB-IoT Workshop
Republic of IoT 2018 - ESPectro32 and NB-IoT Workshop
 
Track 5 session 5 - st dev con 2016 - stm32 hands on seminar - cloud connec...
Track 5   session 5 - st dev con 2016 - stm32 hands on seminar - cloud connec...Track 5   session 5 - st dev con 2016 - stm32 hands on seminar - cloud connec...
Track 5 session 5 - st dev con 2016 - stm32 hands on seminar - cloud connec...
 
Embedded systems introduction
Embedded systems introductionEmbedded systems introduction
Embedded systems introduction
 
Embedded Systems Introduction
Embedded Systems IntroductionEmbedded Systems Introduction
Embedded Systems Introduction
 
Null mumbai-iot-workshop
Null mumbai-iot-workshopNull mumbai-iot-workshop
Null mumbai-iot-workshop
 
Esp8266 Workshop
Esp8266 WorkshopEsp8266 Workshop
Esp8266 Workshop
 
Webinar: STM32WB - microcontrolador dual-core certificado BLE 5.0
Webinar: STM32WB - microcontrolador dual-core certificado BLE 5.0Webinar: STM32WB - microcontrolador dual-core certificado BLE 5.0
Webinar: STM32WB - microcontrolador dual-core certificado BLE 5.0
 
Micro controller & Micro processor
Micro controller & Micro processorMicro controller & Micro processor
Micro controller & Micro processor
 
Sistem mikroprosessor
Sistem mikroprosessorSistem mikroprosessor
Sistem mikroprosessor
 
Unit I_MT2301.pdf
Unit I_MT2301.pdfUnit I_MT2301.pdf
Unit I_MT2301.pdf
 
EE6602 Embedded System
EE6602 Embedded SystemEE6602 Embedded System
EE6602 Embedded System
 
BSides LV 2016 - Beyond the tip of the iceberg - fuzzing binary protocols for...
BSides LV 2016 - Beyond the tip of the iceberg - fuzzing binary protocols for...BSides LV 2016 - Beyond the tip of the iceberg - fuzzing binary protocols for...
BSides LV 2016 - Beyond the tip of the iceberg - fuzzing binary protocols for...
 
C# on a CHIPs
C# on a CHIPsC# on a CHIPs
C# on a CHIPs
 
IoT: Internet of Things with Python
IoT: Internet of Things with PythonIoT: Internet of Things with Python
IoT: Internet of Things with Python
 
Summer training embedded system and its scope
Summer training  embedded system and its scopeSummer training  embedded system and its scope
Summer training embedded system and its scope
 

Último

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel AraĂşjo
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 

Último (20)

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 

Iot Bootcamp - abridged - part 1

  • 1. IOT BOOTCAMP Featuring MicroPython and the ESP32 Marcus Tarquinio
  • 2. COURSE STRUCTURE • Lesson 1 – Introduction: IoT, Microcontrollers and a bit of history • Lesson 2 – Getting started with MicroPython and VS Code • Lesson 3 – Blinking LEDs and writing your first program • Lesson 4 – Pulse Width Modulation and its applications • Lesson 5 – Neopixels, Pyroelectric Infrared sensor and interrupts • Lesson 6 – Connecting to the internet and using cloud services • Lesson 7 – Measuring temperature, humidity, distance … • Lesson 8 – Connected Weather Station
  • 3. LESSON 1 – INTRODUCTION: IOT, MICROCONTROLLERS AND A BIT OF HISTORY • What is the goal of this Bootcamp? • How are the LABs structured? • IoT • Microcontrollers, Single Board Computers and more • Arduino, Raspberry PI • Espressif (ESP8266 and ESP32) • Demo • Moore's Law - After four decades • M5Stack and the hardware kit
  • 4. GOAL Inspire you to build IoT solutions yourself
  • 5. • We structured the LABs so people with different backgrounds can take the most out of them: • The first slide of each LAB explains what is the expected outcome of the exercise… if you know how to do it please give it a try without looking at following slides. • The detailed instructions have all the steps required to complete the LAB including the code. • Some LABs have a Challenge session – the idea here is to offer possibilities to explore beyond the scope of this training. LABS
  • 6. IOT • Microcontrollers + wireless communications Damien George • Typical Examples: • Nest Thermostat, Philips Hue, predictive maintenance… Fujitsu’s connected cow
  • 7. 1979 - DHRYSTONE MIPS VAX 11/780 Dhrystone is a synthetic computing benchmark intended to be representative of system integer performance. A common representation of the Dhrystone benchmark is the DMIPS (Dhrystone MIPS) obtained when the Dhrystone score is divided by Dhrystones per second obtained on the VAX 11/780. Computer Clock Speed RAM Cost * DMIPS VAX 11/780 5 MHz 2 MB $520 000 1 * 150k USD converted into today’s money
  • 8. FEW YEARS LATER IN 1982 Computer Microprocessor Clock Speed RAM ROM Cost * DMIPS TK82-C ZILOG Z80A 3,25 MHz 2 KB 8 KB $260 0.58 • Sinclair ZX81 clone • Based on the ZILOG Z80 microprocessor * 99 USD converted into today’s money
  • 9. • Born in Italy in 2005 • Platform based on the Atmel Microcontrollers • Open source and extensible • Many shields avaliable • Great IDE with many libraries • Limitations • No built-in wireless connectivity • Limited processing power ARDUINO - PROGRAMING MICROCONTROLLERS MADE EASY Microcontroller Clock Speed RAM ROM Cost DMIPS AVR ATmega328P 16 MHz 2 KB 32 KB Flash 20 € 10 DMIPS
  • 10. • Started shipping in 2012 • ARM based developed by UK foundation • Great processing power • Huge software repository • Limitations (for IoT use) • Energy requirements • Full OS RASPBERRY PI - $35 SINGLE BOARD COMPUTER Microprocessor Clock RAM ROM DMIPS BCM2711 4 cores 1.5 GHz 1/2/4 GB MicroSD 7 440
  • 11. ESP8266 • Microcontroller with built-in Wi-Fi • Introduced in 2014 by Espressif • Originally used in Wi-Fi modules … until someone looked at the specs • Very low price (a couple of dollars) • Large open source community Microcontroller Clock Speed RAM ROM DMIPS Tensilica Xtensa L106 80-160 MHz 160 KB 4 MB Flash 113
  • 12. • Introduced at the end of 2016 • Faster MCU • More RAM • Bluetooth 4.2 and BLE • More GPIOs • Capacitive touch inputs • Temperature sensor • HAL effect sensor • Secure boot ESP32 ESP32 Tensilica Xtensa LX6 32 bit 2 cores* plus ULP 160-240 MHz 512 KB RAM + 4MB PSRAM 16 MB Flash + MicroSD 600 DMIPS* <$12
  • 13. • Manufactured on 40nm ULP • Die size 2960 x 2850 Âľm • ESP32-D0WD package size is 5 x 5mm ESP32
  • 14.
  • 15. ESP32 DEVELOPMENT BOARDS • Adafruit Feather HUZZAH32 $20 • SparkFun ESP32 Thing $22 • Espressif ESP32-PICO-KIT $15 • Picom WiPy 3.0 20€
  • 16. DEMO 1.1 • Why do I bother you with all those hardware details? • After you create a working prototype it is very easy to go to the next steps: • Build a couple of devices using development boards • Design your own custom Printed Circuit Board (PCB) around the ESP32 chip
  • 17. MOORE'S LAW - AFTER FOUR DECADES • Computer performance • Memory capacity • Reliability • Size • Price • Power requirements 1970 2010
  • 18. BREADBOARDS AND SOLDERING • Typically you would use breadboards for electronics prototyping and require soldering skills to get the headers on development boards, sensors and actuators
  • 19. M5Stack is a (nice) ESP32 based development kit. It has a 320x240 TFT screen, three buttons, SD card slot, internal speaker and a 9-Axis sensor. M5STACK
  • 20. HARDWARE KIT M5Stack Fan moduleRGB LEDs abridgedabridgedabridged
  • 21. LESSON 2 – GETTING STARTED WITH MICROPYTHON AND VS CODE • Getting familiar with MicroPython • Uploading firmware • LAB • Visual Studio DEMO • LAB • Lesson 0 (pre-requisites)
  • 22. WHAT IS MICROPYTHON? • MicroPython is a lean and efficient implementation of Python 3 • It has been optimized to run on microcontrollers and constrained environments • Yet it is compact enough to run within 256k of code space and 16k of RAM • MicroPython aims to be as compatible with normal Python as possible, enabling code to be easily reused on microcontrollers
  • 23. WHY MICROPYTHON? • Easy to learn, powerful for advanced users: shallow but long learning curve • Unlike C/C++, MicroPython code is very readable (easy to maintain) • The interactive Read-Evaluate-Print Loop (REPL) allows for instant gratification. You connect to the board and have it execute code without any need for compiling or uploading - perfect for quick learning and prototyping • "Unlike the Raspberry Pi, the MicroPython allows you easy access to the bare- metal of the hardware, which means you can do time-critical operations without worrying about an operating system getting in your way“ Damien George GOTO Amsterdam 2016: MicroPython & the Internet of Things
  • 24. WHY MICROPYTHON? • Comparing MicroPython to C++ (Arduino) experience
  • 25. GETTING AND DEPLOYING THE MICROPYTHON FIRMWARE • The firmware is the MicroPython compiled code. Unlike the Arduino environment we will flash it once to the M5Stack and use it with different applications written in high level language. • Official daily builds are available here. • For best results it is recommended to erase the entire flash of your device before putting on new MicroPython firmware. esptool --chip esp32 --port [COMx] erase_flash • Syntax to deploy the firmware. esptool --chip esp32 --port [COMx] --baud 460800 write_flash -z 0x1000 esp32spiram-20190529-v1.11.bin
  • 26. HANDS-ON LAB 2.1 - UPLOADING FIRMWARE Goal: • Upload the official MicroPython firmware into M5Stack • Connect to the REPL on the M5Stack using VS Code and run some code Required: • M5Stack • USB cable • Copy of Esptool and MicroPython firmware
  • 27. HANDS-ON LAB 2.1 - DETAILED INSTRUCTIONS Step 1 • Connect the M5Stack to the computer using the provided USB cable • Open Device Manager (Windows key + “device manager”) • Take a note of the COM port number allocated • It will be the one with “Silicon Labs CP210x”
  • 28. HANDS-ON LAB 2.1 - DETAILED INSTRUCTIONS Step 2 • Now let’s flash the MicroPython firmware to the M5Stack device • In other words, you will copy MicroPython to the non-volatile memory on the device • Copy esptool.exe and esp32spiram-20190529-v1.11.bin files to a folder on your computer • Open a command prompt (Windows key + “cmd”) and change the directory to the folder where you have the two files • Run the following commands replacing [COMx] by the COM port you identified on step 1 esptool --chip esp32 --port [COMx] erase_flash esptool --chip esp32 --port [COMx] --baud 460800 write_flash -z 0x1000 esp32spiram-20190529-v1.11.bin
  • 29. HANDS-ON LAB 2.1 - DETAILED INSTRUCTIONS
  • 30. HANDS-ON LAB 2.1 - DETAILED INSTRUCTIONS Step 3 • Now that M5Stack has the MicroPython firmware, let’s configure Visual Studio Code (Pymakr) and connect to the device If you didn’t install all the prerequisites please start with them (Lesson 0 slides at the end of the deck)
  • 31. HANDS-ON LAB 2.1 - CONNECTING VIA SERIAL USB • Let’s take a few steps to configure the Pymakr extension for first time use. • Here are the steps: • Connect your M5Stack device to your computer via USB • Open Visual Studio Code and check if the Pymakr Plugin has been correctly installed
  • 32. HANDS-ON LAB 2.1 - CONNECTING VIA SERIAL USB • Click All commands on the bottom of the Visual Studio Code window and in the list that appears on the top, click Pymakr > Extra > List Serial Ports. This will list the available serial ports. If Pymakr is able to auto-detect which port to use, it will be copied to your clipboard. If not, just manually copy the correct serial port.
  • 33. HANDS-ON LAB 2.1 - CONNECTING VIA SERIAL USB • Once again click All commands, then click Pymakr > Global Settings. This will open the pymakr.json configuration file. Paste the serial address you copied earlier into the field address. Make sure auto_connect is set to false and then save the file (Ctrl-S).
  • 34. HANDS-ON LAB 2.1 - CONNECTING VIA SERIAL USB • Finally make sure you saved the JSON file! Clicking on Pycom Console connects and disconnects the board • The Pymakr console should show three arrows >>>, indicating that you are connected. If it doesn’t, just restart VS Code and/or reset M5Stack.
  • 35. HANDS-ON LAB 2.1 - RUNNING SOME CODE • You can type MicroPython code directly on the REPL (Read Evaluate Print Loop). • This code was executed on the ESP32 microcontroller on the M5Stack. You computer is only sending the code and reading the output via serial port (like a terminal). print("Hello ArcelorMittal!")
  • 36. DEMO 2.1 - USING VS CODE • Opening folders • Interface overview • Pymakr Package • Upload/Download • REPL: • CTRL-C: Stop any running code • CTRL-D: Soft reset • CTRL-E: Paste mode
  • 37. HANDS-ON LAB 2.2 - CREATE AN ACCOUNT ON OPENWEATHERMAP Goal • Create an account on OpenWeatherMap • We will use this cloud service later today to get whether forecast but It takes a couple of hours for the account activation Required: • Your PC with a web browser, internet connectivity and an email address
  • 38. • Sign up for an free account here HANDS-ON LAB 2.2 - DETAILED INSTRUCTIONS
  • 39. • Check if you received the OpenWeatherMap Create Account email HANDS-ON LAB 2.2 - DETAILED INSTRUCTIONS
  • 40. LESSON 3 – BLINKING LEDS AND WRITING YOUR FIRST PROGRAM • GPIOs • RGB LED • Buttons • LAB
  • 41. • A general-purpose input/output (GPIO) is an uncommitted digital signal pin on an integrated circuit or electronic circuit board whose behavior— including whether it acts as input or output—is controllable by the user at run time. GPIOS
  • 42. • When we program the GPIO as Output we can control a external device. GPIOS - OUTPUT
  • 43. • The traditional first program for hobby electronics is a blinking light. So let’s blink a three color LED! • An RGB (Red, Green, Blue) LED look just like regular LEDs, however, inside its package there are actually three LEDs, one red, one green and one blue. RGB LED
  • 44. • Let’s connect a RGB LED to the M5Stack (ESP32) GPIOs ports. As the name says, GPIOs are generic pins whose behavior - including whether it is an input or output pin - is controllable by code. DEMO 3.1 - GPIOS AND THE MACHINE MODULE import machine BlueLED = machine.Pin(26, machine.Pin.OUT) • In MicroPython we use the Pin function from the machine module. After importing the machine module, we pass the GPIO port number as the first parameter of the Pin function.
  • 45. • Note that the second parameter configures the GPIO as output. • The value() method is used to turn the blue LED on and off. DEMO 3.1 - GPIOS AND THE MACHINE MODULE BlueLED.value(1) BlueLED.value(0) Warning: we are applying 3.3 V directly into the LEDs – that is above the maximum forward voltage for the Red one. It is best practice to use a resistor in series with LEDs.
  • 46. • To make it blink we can use an infinite loop. • Although the code above will make the LED blink, it does it so fast we can’t see it. By adding half a second between the changes we can observe it. That can be done by using the sleep function from the time module. DEMO 3.1 – WHILE LOOP AND THE TIME MODULE while True: BlueLED.value(1) BlueLED.value(0) import time while True: BlueLED.value(1) time.sleep(0.5) BlueLED.value(0) time.sleep(0.5)
  • 47. • But we have three LEDs so let’s use them. • Note that Pin(0 or 1) is a shortcut for Pin.value(0 or 1). DEMO 3.1 – MULTIPLE GPIOS AND THE THREE COLOR LED import machine Red = machine.Pin(21, machine.Pin.OUT) Green = machine.Pin(22, machine.Pin.OUT) Blue = machine.Pin(26, machine.Pin.OUT) Red.value(1) Red(0) Blue(1) Blue(0) Green(1) Green(0)
  • 48. • When we program the GPIO as input we can measure the status of an external device. GPIOS - INPUT
  • 49. • There is a large variety of switches and buttons available. • The M5Stack comes with three normally open active low push buttons. They are connected to GPIOs 39, 38 and 37. SWITCHES AND BUTTONS
  • 50. • We can also import only the Pin class from the machine module. This way we don’t need to reference “machine.” every time we use Pin. Besides, it is more efficient when you don’t need all the classes from the module (saves memory). • The first parameter of the Pin function is the GPIO port number and the second parameter configures the GPIO as input. To read the status of the input we use the value method. DEMO 3.2 – USING INPUT from machine import Pin A = Pin(39, Pin.IN) A.value()
  • 51. • When writing a program, often we need to test a condition and perform some action based on this condition. • In MicroPython that is how you do a simple if statement: and this is how to do a if-else statement: IF STATEMENTS if condition: indentedStatmentBlock if condition: indentedStatmentBlockForTrue else: indentedStatmentBlockForFalse
  • 52. • We can use an if statement to test the status of the INPUT. and an infinite loop to keep doing it forever. DEMO 3.2 – IF STATEMENT if A.value() == 0: print("Do sommething") while True: if A.value() == 0: print("Do sommething") else: print("Do something else")
  • 53. • We can now write a small program that turns an LED on when a button is pressed. DEMO 3.2 – FIRST PROGRAM from machine import Pin Blue = Pin(26, Pin.OUT) A = Pin(39, Pin.IN) while True: if A.value() == 0: Blue(1) else: Blue(0)
  • 54. HANDS-ON LAB 3.1 – LEDS AND BUTTONS Goal • Use the three buttons on the M5Stack to turn each of the three colors LEDs on and off. Required: • M5Stack • Three color LED and grove cables
  • 55. • Connect your computer to the M5Stack using the USB cable provided • Connect the three colors LED to Ports A and B on the M5Stack as showed HANDS-ON LAB 3.1 - DETAILED INSTRUCTIONS M5Stack LED P o r t A G21 Red G22 Green + - P o r t B G26 Blue G36 + - GND
  • 56. • Use VS Code to open the Lab-3.1 LEDs folder • Select the file leds.py HANDS-ON LAB 3.1 - DETAILED INSTRUCTIONS
  • 57. • Review the code • Now run it on the M5Stack: • Select the code from the VS Code editor window (CTRL-A) • Copy it to the clipboard (CTRL-C) • Click on the terminal and put the REPL in PASTE mode (CTRL-E) • Paste the code from the clipboard (CTRL-V) • Exit the PASTE mode (CTRL-D) • Test the code by pressing the buttons • What happens when you press more than one button at the same time? • Press CTRL-C to stop the code execution. HANDS-ON LAB 3.1 - DETAILED INSTRUCTIONS
  • 58. • Although we have not done it on this lesson, limiting the current into an LED is very important. LEDs have a non-linear behavior and its resistance quickly drops as it turns on. • To prevent the LEDs burning out a limiting resistor should be added in series with them. The value of the resistor is calculated such that LED characteristic (or recommended) forward current is not exceed. LED CURRENT LIMITING RESISTORS i = LED forward current in Amps Vf = LED forward voltage drop in Volts Vs = supply voltage
  • 59. LESSON 4 – PULSE WIDTH MODULATION AND ITS APPLICATIONS • Pulse Width Modulation • Blinky PWM version • Fading LEDs • Rainbow • Fan Module • LAB • SG90 MicroServo
  • 60. • As its name suggests, Pulse Width Modulation (PWM) is a technique where we apply a series of “ON-OFF” pulses and vary the duty cycle. The duty cycle is the percentage of time that the output is “ON” (3.3 Volts) compared to when it is “OFF” (0 Volts). PWM - PULSE WIDTH MODULATION
  • 61. When creating an instance of the PWM class we need to pass ‘pin’, which is a mandatory argument (‘freq’ and ‘duty’ are optional): pwm = machine.PWM(pin [, freq=f] [, duty=d]) They can also be modified after creation: pwm.freq([freq]) • sets the new pwm frequency to freq Hz • without arguments it returns the current frequency pwm.duty([duty]) • sets the new pwm duty cycle to duty from 0 to 1023 • without arguments it return the current pwm channel duty cycle pwm.deinit() # turn off PWM on the pin PWM - MICROPYTHON
  • 62. • We can use PWM to blink the LED, achieving the same results as code with a loop. in this case the duty cycle is set to 50% (1024/2) and the frequency to 1 Hz or one pulse per second. Note that the LED will blink in the background, controlled by the dedicated hardware. This free up the program to do other things! Let’s increase the frequency. Can you still perceive it blinking? DEMO 4.1 - BLINKY PWM VERSION from machine import Pin, PWM BlueLED = PWM(Pin(26), freq=1, duty=512) BlueLED.freq(10) BlueLED.freq(30) BlueLED.freq(60)
  • 63. • If we blink the LED very fast, the human eye will no longer be able to see it blinking. At high frequencies we will only perceive a brighter or dimmer light depending on the duty cycle. • By changing the duty cycle we control for how long we keep the LED on in each period. Or, in other words, to modulate the pulse width. pwm.deinit() • DE initializes, frees up the PWM channel and stops PWM output DEMO 4.1 - BLINKY PWM VERSION BlueLED.deinit() BlueLED.duty(300) BlueLED.duty(100) BlueLED.duty(700)
  • 64. • We used so far while True: endless loops. Naturally we can use a logical expression instead of True as the test condition for the while loop. • The second ways to do loops in MicroPython is with for. A for loop is used for iterating over a sequence. It is usually combined with the range() function. • The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default). LOOPS while condition: indentedStatmentBlock for item in sequence: indented statements to repeat; may use item range([start,] sizeOfSequence [,step])) start: Starting number of the sequence sizeOfSequence: Generate numbers up to, but not including this number step: Difference between each number in the sequence
  • 65. • By varying the duty cycle of the PWM pulse we can control the brightness of the LED. • The first for loop starts from 0 and increases the duty cycle up to 1023. The second for loop does the opposite, starting from 1024 and decreasing the brightness until 1. We need to add a sleep (1 ms) step so the human eye can see the changes. DEMO 4.2 - FADING LEDS Note: the LED is actually blinking at the default PWM frequency (5 kHz - 5000 times per second) BlueLED.deinit() from machine import Pin, PWM from time import sleep BlueLED = PWM(Pin(26), freq=5000, duty=0) while True: for i in range(1024): BlueLED.duty(i) sleep(0.001) for i in range(1024, 0, -1): BlueLED.duty(i) sleep(0.001)
  • 66. DEMO 4.2 - FADING LEDS
  • 67. • Using PWM with the three LEDs one can generate any color DEMO 4.3 - MULTICOLOR LED from machine import Pin, PWM RedLED = PWM(Pin(21), duty=0) GreenLED = PWM(Pin(22), duty=0) BlueLED = PWM(Pin(26), duty=0) RedLED.duty(round ( 1024*1/5 ) ) GreenLED.duty(round ( 1024*3/5 ) ) BlueLED.duty(round ( 1024*4/5 ) ) RedLED.deinit() GreenLED.deinit() BlueLED.deinit()
  • 68. • Functions are a convenient way to divide your code into useful blocks, allowing us to order our code, make it more readable, reuse it and save some time • Once the function is defined you can invoke it FUNCTIONS def function_name(parameters): indentedStatmentBlock function_name(parameters)
  • 69. • A nice “rainbow effect” can be obtained by fading one LED while keeping the other two at the same level DEMO 4.4 - RAINBOW ... def fade(led, begin=0, end=1024, step=1): for i in range(begin, end, step): led.duty(i) sleep(0.001) ... while True: fade(GreenLED) # Ramp up green fade(RedLED, begin=1024,end=0,step=-1) # Ramp down red fade(BlueLED) # Ramp up blue fade(GreenLED, begin=1024,end=0,step=-1) # Ramp down green fade(RedLED) # Ramp up red fade(BlueLED, begin=1024,end=0,step=-1) # Ramp down blue
  • 70. • Another way to implement the rainbow code is to use a technique called cross fading. In this case we change the duty cycle of two LEDs at the same time. CROSS FADING
  • 71. DEMO 4.5 - CROSS FADING RAINBOW from machine import Pin, PWM from time import sleep def crossFade(ledUp, ledDown, begin=0, end=1024): for i in range(begin, end): ledUp.duty(i) ledDown.duty(1023-i) sleep(0.002) RedLED = PWM(Pin(21), duty=0) GreenLED = PWM(Pin(22), duty=0) BlueLED = PWM(Pin(26), duty=0) while True: crossFade(GreenLED, RedLED) # Ramp up green / ramp down red crossFade(BlueLED, GreenLED) # Ramp up blue / ramp down green crossFade(RedLED, BlueLED) # Ramp up red / ramp down blue
  • 72. • The Fan motor module has an L9110 single motor driver integrated circuit (IC). The IC has two inputs INA and INB, and its output is connected to a small DC motor. This implements an H-bridge, allowing us to drive the motor forward or backwards by reversing the direction of the voltage across it. • Similarly to the LEDs we can change the motor speed by varying the duty cycle of a PWM signal. L9110 FAN MOTOR MODULE
  • 73. • There are two ways to interface with an H-bridge. • The first is by controlling both sides of the bridge directly. DEMO 4.6 - L9110 FAN MOTOR MODULE INA INB motor direction False False Stop False True Forward True False Reverse True True Stop from machine import Pin inA = Pin(21, Pin.OUT) inB = Pin(22, Pin.OUT) inA.value(0) inB.value(1) # Forward inB.value(0) # Stop inA.value(1) # Reverse
  • 74. ... and the other method uses one pin as a PWM output (to set motor speed) and the second as a digital output (to set its direction). In this case, we control the direction and the speed of the motor. DEMO 4.7 - L9110 FAN MOTOR MODULE WITH PWM INA INB motor direction False False Stop False True Forward True False Reverse True True Stop from machine import Pin, PWM pwmFan = PWM(Pin(21)) reverseFan = Pin(22, Pin.OUT) pwmFan.duty(717) # 70% duty cycle ( 70 * 1024 / 100 ) # pause pwmFan.duty(307) # 30% duty cycle ( 30 * 1024 / 100 ) # pause reverseFan.value(1)
  • 75. HANDS-ON LAB 4.1 - FAN Goal • Attach the FAN module to an appropriate support and use the buttons to control it: A: reverse the fan rotation B: increase the PWM duty cycle C: decrease the PWM duty cycle Required: • M5Stack • Groove cable • Fan motor module • LEGO assortment (to be used as support)
  • 76. • Connect your computer to the M5Stack using the USB cable provided • Connect the Fan Module to the M5Stack using the Grove cable and the diagram below HANDS-ON LAB 4.1 - DETAILED INSTRUCTIONS M5Stack Cable FAN P o r t A G22 Yellow INB G21 White INA + Red VCC - Back GND
  • 77. HANDS-ON LAB 4.1 - DETAILED INSTRUCTIONS Warning: the Fan runs very fast so protect your eyes and fingers! • Use the LEGO assortment to build a stand and attach the Fan module to the M5Stack. Here goes some inspiration but fell free to build it your way.
  • 78. • Use VS Code to open the Lab-4.1 Fan folder • Select the file fan.py • Review the code and copy and paste it to the REPL to run it on the M5Stack • Refer to Lab 3.1 if you don’t remember how • Test the code by pressing the buttons HANDS-ON LAB 4.1 - DETAILED INSTRUCTIONS G22 G21 motor direction False False Stop False True Forward True False Reverse True True Stop
  • 79. Servos are very handy little units, consisting of a motor, a position sensor and a feedback loop. Rather than telling them which way to turn, you tell them what position you want them to be in and they move to that position. They are controlled by a train of pulses: - 1 ms will turn the servo one way - 1.5 ms will put the servo in the middle - 2 ms will turn it the other way Servos are not all that precise, especially cheap ones, so if you go past the acceptable range for the servo you may hear it whine as it tries to move past its limits, or it may 'hunt' (wiggle back and forth) if it isn't happy with the frequency of the pulses. The allowable range of your servos is best determined by trial and error. SG90 MICRO SERVO
  • 80. DEMO 4.8 - SG90 MICROSERVO from machine import Pin, PWM # Set the frequency to 50Hz (one cycle per 20ms) pwmServo = PWM(Pin(26), freq=50, duty=8) pwmServo.duty(77) # 20ms * 77 / 1024 = 1.50ms)
  • 81. LESSON 0 – PRE-REQUISITES • What do you need to install on your computer? • NodeJS (10.16.2 LTS) • Visual Studio Code (v1.37.0) • Pymakr VS Code extension (1.1.3) • SiLabs CP2104 Driver (v6.7.6)
  • 82. LESSON 0 – PRE-REQUISITES • NodeJS • The first step is to get NodeJS installed on your PC (it is a pre-requisite to the VS Code extension we will install next). Please download the latest LTS version available from the NodeJS website.
  • 83. LESSON 0 – PRE-REQUISITES • Visual Studio Code • We will also need you to download and install Visual Studio Code (if you already have it, skip to the next step).
  • 84. • Pymakr VS Code extension • To install the Pymakr extension open VSCode • Open the Extensions page (5th button in the left pane) • Search for Pymakr and click the install button next to it LESSON 0 – PRE-REQUISITES
  • 85. • On the pymakr.json configuration file: • Make sure you change the auto_connect parameter from true to false • M5Stack does not work well with auto connect • Save the changes (Ctrl-S) LESSON 0 – PRE-REQUISITES
  • 86. LESSON 0 – PRE-REQUISITES • SiLabs CP2104 Driver • Download and install the SiLabs CP2104 Driver. Use the Windows 7/8/8.1 version. • Do NOT use the Windows 10 Universal driver! If you happen to download the universal version, you may need to manually revert to 6.7.6 on a regular basis as Windows will repeatedly use the newer, incorrect driver after each Windows update. https://m5stack.readthedocs.io/en/latest/get-started/establish_serial_connection.html
  • 87. LESSON 0 – PRE-REQUISITES • MicroPython • We will need a copy of the official MicroPython firmware for the ESP32. Please download the latest stable version with SPIRAM support from the micropython.org website.
  • 88. LESSON 0 – PRE-REQUISITES • Esptool • Finally we will need a copy of the Esptool from Espressif. This is a Python based tool used to program the ESP32 flash memory. • To make it easier we will use a pre-compiled version of it that can be downloaded as part of the M5Stack M5Burner solution. The official python version would work as well but it requires Python on the host computer. • Download and open M5Burner.zip • Extract esptool.exe from the tools folder. We will only need this file.