Category: MICROPYTHON


Raspberry Pi Pico is a low-cost, high-performance microcontroller board with flexible digital interfaces.

Other Raspberry PI boards are SBC –  Single Board Computer which requires an OS on a SD card.

But PICO is a Microcontroller like Arduino.

RPI boards do not have ANALOG inputs , PICO has 3 ANALOG inputs.

Designed on RP2040 IC (Dual-core Arm Cortex M0+ processor flexible clock running up to 133 MHz)

, this PICO board has 26 GPIO pins including 3 Analog Inputs.

As such RP2040 HAS 30 GPIO pins including 4 Analog inputs, but on board the user is offered with only 26 GPIO pins including  3 Analog Inputs.

  • 264KB of SRAM, and 2MB of on-board Flash memory
  • Castellated module allows soldering direct to carrier boards
  • USB 1.1 with device and host support
  • Low-power sleep and dormant modes
  • Drag-and-drop programming using mass storage over USB
  • 26 × multi-function GPIO pins
  • 2 × SPI, 2 × I2C, 2 × UART, 3 × 12-bit ADC, 16 × controllable PWM channels
  • Accurate clock and timer on-chip
  • Temperature sensor inbuilt
  • Accelerated floating-point libraries on-chip
  • 8 × Programmable I/O (PIO) state machines for custom peripheral support

https://www.raspberrypi.org/products/raspberry-pi-pico/

pico_pins

PICO can be programmed with C / C++ SDK or MicroPython.

In this blog, we work with MicrPython.

To start with Press & Hold the BOOTSEL button on board and connect the USB to Windows PC.

CONNECT

Release the BOOTSEL button to see PICO appear as a mass storage device RPI-RP2.

Image 1

Open the Device Manager , you see PICO under Portable Devices as RPI-RP2.

Image 2

Open the RP2 storage .

Double click on the INDEX.HTM file to visit the official PICO website.

Image 3

Image 4

Scroll down to click Getting started with MicroPython.

Image 5

https://www.raspberrypi.org/documentation/pico/getting-started/static/f70cc2e37832cde5a107f6f2af06b4bc/rp2-pico-20210205-unstable-v1.14-8-g1f800cac3.uf2

Here download the UF2 file , which is USB Flashing Format by Microsoft.

UF2 files can be opened and edited using a variety of Microsoft MakeCode editors.

To transfer a UF2 file to a microcontroller, developers plug their microcontroller into their PC’s USB drive. Their PC then recognizes the microcontroller as a FLASH DRIVE, allowing the developer to drag their UF2 file to the microcontroller and install their MakeCode program.

Image 6

Drag and Drop the UF2 file on to RPI-RP2.

Image 7

RPI-RP2 now disappears indicating Micropython installation is complete.

If you open the Device Manager , PICO appears as USB SERIAL DEVICE and a COM port is allotted.

Image 8

For GUI interface we use THONNY PYTHON.

Download and install Thonny Python

https://thonny.org/

Image 9

Open Thonny Python

Under Tools –> Options

click INTERPRETER

th1

Under Interpreter drop down select

MicroPython Raspberry Pi PICO   and select the COM port allotted to PICO.

PICO is listed only in the newer version of Thonny.

th2

Now click on the RED stop button to get the Interpreter CHEVERON 3 greater than symbol at the bottom.

You can try MicroPython commands here.

Image 10

To blink the on board LED let us start the coding under Editor.

First import PIN Class from machine module.

Functions are called modules in Micropython.

Then import sleep class from utime module for delay.

Create an led object which takes 2 parameters.First is the GPIO PIN , which is 25 where the inbuilt led is connected.

Second parameter to declare this pin as OUTPUT.

Then starts the never ending loop

while True:

After the colon you get an indentation space automatically.

This is equal to braces in Micropython.

Here we toggle the led and provide a delay of 1 second.

Image 11

Click File –> Save As

Image 12

You get 2 options to save.

Select Raspberry Pi PICO to save the file.

Image 13

Provide the filename as

main.py

Auto execution takes place only if the file name is main.py.

So it is a must to provide file name as main.py.

Image 14

Click on the green RUN button

Image 15

Now the LED on board blinks according to code.

C2[3]

To RESET the PICO back to factory condition

there is another UF2 file under Resetting Flash memory.

Download this nuke UF2 file.

Image 16

Press hold the BOOTSEL button and connect the USB to pc.

IMG_20210205_182142

Drag and drop the nuke UF2 file on to RPI-RP2 to erase flash memory back to factory condition.

There is no RESET button on PICO.

You can connect a RESET button between RUN and GND pin as shown below :

reset

video :

blog_image

ULTRASONIC sensor is  popular in many applications where measuring distance or sensing objects are required.

The module has two eyes in the front which forms the Ultrasonic transmitter and Receiver.

U11

 

1.Vcc  The Vcc pin powers the sensor, typically with +5V,The current consumed by the sensor is less than 15mA

2.Trigger

Trigger pin is an Input pin. This pin has to be kept high for 10us to initialize measurement by sending Ultrasonic burst of 40KHz.

3.Echo

Echo pin is an Output pin. This pin goes high for a period of time which will be equal to the time taken for the US wave to return back from object to the sensor.

4.Ground

To start the measurement, the trigger pin has to be made high for 10uS and then turned off.

This action will trigger an ultrasonic wave at frequency of 40Hz from the transmitter and the receiver will wait for the wave to return.

Once the wave is returned after it getting reflected by any object the Echo pin goes high for a particular amount of time which will be equal to the time taken for the wave to return back to the sensor.

The amount of time during which the Echo pin stays high is measured by the esp32 as it gives the information about the time taken for the wave to return back to the Sensor. Using this information the distance is measured

As the ultrasonic sensor requires 5v , we use a separate power source.

This sensor will not operate on 3.3v.

Vcc –> 5v

Gnd to Gnd

Trigger –> GPIO 5

Echo  –>  GPIO 18

Both Gnd of 3.3v & that of 5v to be made common.

As the ECHO PIN of ultrasonic gives 5v level , we need a LEVEL SHIFTER in between ECHO & GPIO18

q1

 

IMG_20200328_133155

OLED connections :

Vcc to 3.3v

Gnd – Gnd

SCL –> GPIO 22

SDA –> GPIO 21

We use THONNY PYTHON to test and upload code.

2 library modules are required.

One ssd1306.py for OLED

hcsr04.py module for ultrasonic measurement support.

Download the files from :

http://www.alselectro.com/files/micropython_oled_dht_ultrasonic.zip

 

From ThonnyPython File –> open and browse to the location to select ssd1306.py

Save it to Micropython device as ssd1306.py

Image 14[5]

Same way import the hcsr04.py

and save it on Micropython device.

Image 12

Sample code is provided as main.py

After saving these file , the ESP32 has 4 files

boot.py

main.py

ssd1306.py

hcsr04.py

Image 15

Image 10

In the example code

we import classes Pin,I2C

Then we import modules ssd1306, hcsr04 and time

i2c is initiated with scl pin GPIO22 &  sda pin GPIO21

oled object is initiated by passing arguments width 128, height 64, protocol i2c and address 0x3c.

ultrasonic sensor object is instantiated from HCSR04 Class by passing on trigger pin GPIO5

Echo pin GPIO18

Inside never ending loop

distance_cm() method used to measure distance

oled.text() method to display result on OLED.

Note the conversion to STRING variable while dusplaying on OLED.

Image 11

 

Click on F5 to execute.

The OLED will display the sensor distance reading.

 

U1

VIDEO :

 

blog_image

DHT11 is a low-cost digital sensor for sensing temperature and humidity and can be easily interfaced with ESP32 on Micropython.

DHT11 sensor consists of a capacitive humidity sensing element and a thermistor for sensing temperature.

Temperature range of DHT11 is from 0 to 50 degree Celsius with a 2-degree accuracy.

Humidity range of this sensor is from 20 to 80% with 5% accuracy.

The sampling rate of this sensor is 1Hz .i.e. it gives one reading for every second.

DHT11 operating voltage from 3 to 5 volts. The maximum current consumed  is 2.5mA.

IMG_20200328_113814

DHT11 sensor has four pins- VCC, GND, Data Pin and a not connected pin. A pull-up resistor

of 5k to 10k ohms is needed for communication between sensor and micro-controller.

When you buy as Module , the resistor is provided on pcb , and only 3 pins available.

On module there is also a power LED provided.

Image 1

Connect GPIO 15  —> Data pin of DHT11

Gnd to Gnd , Vcc to 3.3v

OLED connections :

SCL –> GPIO 22

SDA –> GPIO 21

Gnd to Gnd , Vcc to 3.3v

 

Thonny Python is used as IDE to develop and upload code on to ESP32.

OLED driver module (library) to be downloaded from :

https://github.com/micropython/micropython/blob/master/drivers/display/ssd1306.py

File –> open

browse to the location of ssd1306.py file to select it.

File –>  Save as

select Micropython device and save it as ssd1306.py file.

 

Image 6

From interpreter of Thonny Python code can be tested line by line.

Import from machine module Pin and I2C Class.

Import dht module , which is inbuilt in Micropython.

Image 11

Declare Pin 15 WHERE WE CONNECT data OF dht11 AS iNPUT.

Create  d , a dht object using class DHT11 ( from dht module) and pass on the argument pin 15.

DHT11 Class is in module dht.

so we use  dht.DHT11  instantiate an object from that class.

Image 2

measure() method is called to read the temperature and humidity values.

temperature()  method gives temp value

humidity() method gives % of humidity.

 

Image 3

 

Driver module for OLED and main.py files can be downloaded from :

http://www.alselectro.com/files/micropython_oled_dht_ultrasonic.zip

You can open the downloaded main.py file in Thonny python.

Click File –> Save as and select Micropython device

save as main.py file.

Do not change the name.It must be main.py , as Micropython after executing boot.py looks for main.py

In the example code

we import classes Pin,I2C

Then we import modules ssd1306, dht and time

i2c is initiated with scl pin GPIO22 &  sda pin GPIO21

oled object is initiated by passing arguments width 128, height 64, protocol i2c and address 0x3c.

d object is initiated using dht.DHT11 Class by passing on GPIO15

Inside never ending loop

measure()  method used to read temperature and humidity values.

temperature()

humidity()

methods used to get the result.

While printing on OLED we need to convert the data to STRING

oled.text( str ( t ),80,20)

 

Image 7

 

Image 4

Click on F5 to execute.

You can see the Temperature reading in Celcius & Humidity reading in % on OLED.

 

IMG_20200328_123149

Video :

 

blog_image

 

ADC3

ldr2_adc

Built in ADC of ESP32 can be used to read analog values from sensors like potentiometer,LDR,Load cell,Thermistor,etc..

On the ESP32 ADC functionality is available on Pins 32-39.

Only the pins of ADC1 are enabled for ADC.  ADC2 is not enabled in Micropython.

pins 36-39 are recommended for analog input due to the available preamplifier.

ESP32 ADC pins by default have 12 bit resolution.

These pins read voltage between 0 to 3.3v & return value between 0 and 4095

To get value bet 0-1023 CHANGE RESOLUTION TO 10 BIT

IMG_20200326_123034

Connect a LDR to+3.3v , other end to Gnd through 10k Resistor.

The junction point of LDR & Resistor is connected to ADC GPIO Pin 36.

Open Thonny Python & use the interpreter to test ADC code.

From machine module import classes Pin & ADC.

Create ad adc object by passing on the GPIO Pin 36.

Read the analog value using read() method.

LDR faced to light gives some resistance , and the value is 1348.

 

ad1

This function returns a whole number between 0 and 4095. Because we know that 0 refers

to 0 V and 4095 refers to 3.3 V

In full dark condition (LDR closed) the value is 4095.

The ADC resolution by default is 12 bits

2 power 12 is 4096.

ad2

We can convert the reading to voltage by multiplying with 0.000805

2 power 12 is 4096

Voltage is 3.3v ,   3.3/4096 = 0.000805

You can see , at full dark condition the ADC value is 3.3v

ad3

As per documentation of ESP32 the maximum ADC volt can be set using attenuation.

ADC.atten(attenuation)

This method allows for the setting of the amount of attenuation on the input of the ADC.

This allows for a wider possible input voltage range, at the cost of accuracy

(the same number of bits now represents a wider range). The possible attenuation options are:

ADC.ATTN_0DB: 0dB attenuation, gives a maximum input voltage of 1.00v – this is the default configuration  (but while testing it shows 3.3v)

ADC.ATTN_2_5DB: 2.5dB attenuation, gives a maximum input voltage of approximately 1.34v

ADC.ATTN_6DB: 6dB attenuation, gives a maximum input voltage of approximately 2.00v

ADC.ATTN_11DB: 11dB attenuation, gives a maximum input voltage of approximately 3.6v

 

Setting the attenuation to 11DB gives value of 1.72 volt ( but the document says 3.3v)

So leave it to default 0DB which practically gives 3.3v

ad4

The resolution can be changed to 10 bit by setting width to 10BIT.

Default is 12 BIT.

 

ADC.width(width)

This method allows for the setting of the number of bits to be utilised and returned during ADC reads. Possible width options are:

ADC.WIDTH_9BIT: 9 bit data

ADC.WIDTH_10BIT: 10 bit data

ADC.WIDTH_11BIT: 11 bit data

ADC.WIDTH_12BIT: 12 bit data – this is the default configuration

ad5

 

ad6

After testing with interpreter we shall use the Editor to write code.

Save the file as main.py on to Micropython device.

Click on F5 to execute.

The analog output value is displayed according to light fall on LDR.

adc12

Video :

 

blog_image

 

Pulse width modulation is used in a variety of applications particularly for control. It can be used for the dimming of LEDs, varying speed of motors  and controlling the angle of servo motors

In ESP32 PWM can be initiated on all output-enabled pins.

Image 5

pwm_Image 4

 

PWM is digital, which means that it has two states: on and off.The amount of current that flows to a device like LED can be controlled by varying the time each pulse stays ON.

The longer each pulse is on, the brighter the LED will be.

DUTY CYCLE refers the amount of time the pulse  is ON.

For a square wave the DUTY cycle is 50 % , the pulse is ON for 50% of the time and OFF for 50%

If duty cycle is 100% then the output is equal to Vcc ( 3.3v here) and LED will be full lit.

If duty cycle is 0% , the signal is flat and equal to Gnd voltage 0.

 

Connect an LED at GPIO 15.

Short lead of LED goes to Gnd through  a Resistor 1k.

IMG_20200326_104000

 

We shall use THONNY PYTHON IDE to test and upload python code on to ESP32.

Refer to my previous blog on how to use Thonny Python

https://alselectro.wordpress.com/2020/02/09/micropython-on-esp32/

Let us use the interpreter of Thonny Python to test the code.

First import from machine module the Pin & PWM classes.

Pin module is to control the GPIO pins.

 

pw1

Then create a PWM object called led and pass on the GPIO Pin 15.

Once the led object is created you can use the methods like duty to set the duty cycle and freq to set the frequency.

Duty cycle can be from 0 to 1023.

512 represents 50% , and 1023 = 100%. duty cycle.

led.freq(1) makes the LED flash once per second.

 

pw2

You can create the PWM object and pass on the duty,freq in a single line of code.

pw3

To stop PWM use the method deinit().

pw4

 

IMG_20200326_110131

 

Now let us give the LED a fade effect using PWM.

Micropython executes boot.py file on power on.

Then it looks out for main.py file to execute.

In case you need your own naming for file , then create that file and import  the module and place a call for the function inside main.py.

Though boot.py file has nothing to execute inside , this file exists by default in Micropython.

Image 1

Inside main.py file

import fadeled

fadeled.ledpwm()

fadeled is the module we have to create

& ledpwm() is the function in that module.

Without creating this new module we could have named the file as main.py and write the complete code inside main.py

Image 2

In the never ending loop while True: , we change the duty cycle from 0 to 1023

using in range function.

This gives a fading effect on LED.

Note the indentation after each colon : in python code.

This space or indentation represents braces.

Image 3

Click on File  –> Save as

and select Micropython device to save.

Save the file as fadeled.py

Like this save the main.py file also to ESP32.

 

fade

Now click on F5 or the green arrow button on top to execute.

You can see the LED fading effect.

The PWM method can be used  to position the SERVO motor from 0 to 180 degrees.

All servo motors have 3 wires.Red to 5v, Black or Brown to Gnd

Orange wire is Signal (pwm)

servo

Connect the Servo signal pin at GPIO 23.

As servo requires 5V we use an external power source of 5 Volt.

The Gnd of 5V source and the Gnd of ESP 32 must be made common i.e connected together.This is a must while using 2 different power sources.

IMG_20200326_160116

 

Frequency (1/period) is specific to controlling a servo.

A typical servo motor expects to be updated every 20 ms with a pulse between 1 ms and 2 ms, or in other words, between a 5 and 10% duty cycle on a 50 Hz waveform.

So frequency of 50 hz is a must to control most Servos .This gives a 20 msec pulse.

With a 1.5 ms pulse, the servo motor will be at the natural 90 degree position. With a 1 ms pulse, the servo will be at the 0 degree position, and with a 2 ms pulse, the servo will be at 180 degrees.

Duty cycle from 20 to 120 facilitates position of servo fro 0 to 180 degrees.

ser1

servo object is created by passing on PWM Pin as GPIO 23 and frequency as 50

1/50hz = 0.02 = 20 msec which is required to update most servos.

We set the duty cycle to 20  to position servo at 9 degree.

duty 70 –>  90 degree

duty 120 – > 180 degree

VIDEO :

 

blog_image

The ESP32 with MICROPYTHON has 2 WI-FI interfaces

ACCESS POINT INTERFACE

STATION INTERFACE

Normally in a Home Network we have a Router which is connected to Internet Service Provider.

This Router can be Ethernet capable, wireless capable or both.Nowadays mostly Routers are WIFI enabled.Over WIFI you can connect your laptop,mobile or ESP32 to the Router to get internet access.

In this scenario the ROUTER acts as ACCESS POINT & the devices that connect to it act as CLIENTS.

In Micropython CLIENT is also called as STATION.

When a Client/Station connects with the Router , the Router provides an IP address to the device connected.

Suppose the IP of Router is 192.168.0.1 which is also called as GATEWAY IP (this IP is printed on the back of Router) , the Clients will be given IP in the range 192.168.0.xxx  .

The last octet only will change on first come first basis.That means the IP offered by DHCP method is DYNAMIC which changes on next power on.

To make it STATIC you can open the Gateway IP on a browser to set up configuration of Router.Here you can note the MAC address of the CLIENT and set the IP to static , so that it will be always offered the same IP on every power ON.

 

IMG_20200211_125844

 

In the second scenario STATION INTERFACE

the ESP32 device can act as ACCESS POINT instead of Router & other devices like mobile or ESP modules can connect with it over WI FI.

IMG_20200211_125822

 

In this post we shall explore the ways by which ESP32 acts as a CLIENT/STATION and connect with an ACCESS POINT like Router over WIFI automatically on Power ON.

For Micropython IDE we use THONNY PYTHON

Refer my previous post on getting started with Thonny python

https://alselectro.wordpress.com/2020/02/09/micropython-on-esp32/

https://thonny.org/

 

This interface can be managed using the network module from MicroPython.

First import the network module.

Then create an object that represents this interface:

Create a WLAN network interface object. One of the Supported interfaces are

network.STA_IF (station or client, connects to upstream WiFi access points)

Make that network  interface active.

Image 4

 

Image 5

 

Scan for the available wireless networks using

station.scan()

Scanning is only possible on STA interface. Returns list of tuples with the information about surrounding WiFi access points:

The tuples returned here have the parameters of each available Wi-Fi connection. In particular, the first element in each tuple is the SSID name, the third element is the channel number, and the fourth is the RSSI or signal strength indicator.

(ssid, bssid, channel, RSSI, authmode, hidden)

ssid is the service set identifier

bssid is hardware address of an access point, in binary form, returned as bytes object. You can use ubinascii.hexlify() to convert it to ASCII form.

RSSI signal strength in negative value

There are five values for authmode:  0- open ,1 –WEP , 2 –WPA-PSK , 3- WPA2-PSK ,4 WPA/WPA2-PSK

and two for hidden:  0 (false)-VISIBLE,  1- HIDDEN

You can check the connection using method isconnected()

Image 6

As we have not yet connected it returns FALSE.

Connect to WI FI using your SSID name and its password.

Image 8

ifconfig() method returns the parameters of the connection

IP Address allotted along with Subnet mask,Gateway IP & DNS Server

 

Image 9

 

As we have tested the connection using Micropython Interpreter , we can implement auto connection to WIFI as follows :

Micropython executes

boot.py

on power up first.Then it looks out for

main.py

Under Thonny python IDE click File –> New

This file we shall save as boot.py

Image 2

 

For intimation we shall include only a print statement

print(‘RUN : boot.py’)

Click on File –> Save As

You get 2 options 1. to store on your computer for later modification

2. On the Micropython device (ESP32)  directly.

Provide the file name as boot.py and save it on MicroPython device.

 

Image 10

Again File –> New

to create the second file main.py

Here we import module ConnectWifi & call the function connect()

The module & function have to be created by us.

For now save it on ESP32 as file main.py.

Remember not to change the file name, as Micropython will look to execute only main.py automatically.

Image 3

Finally we have to create the file ConnectWifi.py

and create  the function connect()

In this function replace the ssid,password with that of yours.

Save this file on to Micropython Device.

Image 1

Download the .py files from here :

http://www.alselectro.com/files/wifi_code.zip

Finally click on F5 or the Green arrow button to execute.

 

Image 11

ESP32 will auto connect to your SSID.

Video support :

 

blog_image

MICROPYTHON ON ESP32

 

ESP32 is a powerful device for IOT development with WIFI & Bluetooth.Compared to NodeMCU it has more ADC pins , DAC & much more.

ESP32 can be programmed by many ways including Arduino core.

This post is on programming ESP32 using MICROPYTHON.

MicroPython is a lean and fast implementation of the Python 3 programming language that is optimised to run on a microcontroller.

MicroPython has advantages over traditional programming software such as C/C++ because it is essentially a live development environment and you write and debug code much faster…in fact 5-10 times faster than C++.

when a device boots up using MicroPython it does not consume much memory and thus doesn’t incur current drain.Micropython also has a number of Micropython specific libraries for accessing hardware level features.

Adafruit also introduced  CircuitPython ,Soon after MicroPython started picking up the pace. However,  CircuitPython offers support for the Adafruit range of hardware only.

Python allows for rapid feedback. This is because you can interactively enter commands and get a response using the  REPL –read–eval–print loop. You could even tweak your code and run it right away, rather than iterating through code-compile-upload-execute cycles.

title_th

This post is on implementing MICROPYTHON on ESP32.

 

esp32

As a programming environment , many IDE s are available , of which THONNY IDE is simple & powerful.

Thonny IDE : An integrated development environment (IDE– Integrated Development Environment) for Python that is designed for beginners. It stands out for its simplicity of installation and use, ease of writing and debugging of code, possibility of incorporating plugins and its good documentation.

uPyCraft IDE : It is anIDE specifically oriented for MicroPython, which makes it one of the besteditorsfor this use. It allows you to upload the MicroPython firmware to the microcontroller in a very simple way (as an alternative toesptool.py)

Visual Studio Code (VSCode) , using the PyMakr extension: It is avery sophisticatedIDE , which supports many practical functionalities working with code, but is only recommended for advanced users

PYCHARM is for advanced users.There is community edition for free.There’s a PyCharm plugin that adds MicroPython support to your IDE. It’s available right in the plugin marketplace

visit  https://thonny.org/  & download the installer relevant for you (available for Windows,Mac & Linux)

Image 4

Install THONNY IDE by double clicking the downloaded installer.

Image 5

 

Image 6

Open THONNY IDE .

The top portion is the EDITOR where you write your Micropython code.

Bottom is the SHELL.

As we’ve not yet installed Micropython interpreter, the Shell displays the default Python prompt.

‘>>>’ is the prompt of the interactive Python interpreter, meaning that the interpreter is ready to get Python statements typed in.

The PROMPT Is called CHEVRONS.

 

Image 7

To get the Micropython prompt, click on Tools –> Options

Image 8

Under options window click on INTERPRETER.

Image 9

Under first drop down menu select MICROPYTHON (ESP32)

Under Port , select the port number where ESP32 is connected.

Click on Firmware install bar.

Image 10r

Micropython firmware .bin file can be downloaded from

http://micropython.org/download

Under ESP32 select the GENERIC .bin file & download it.

http://micropython.org/resources/firmware/esp32-idf3-20200209-v1.12-154-gce40abcf2.bin

Now , from the Thonny install firmware window , click browse and locate the downloaded .bin file.

 

Image 13

Click on install button to start the firmware installation.

You need to press & hold the BOOT button on ESP32 module for a moment.

Image 14

You may get an error stating ESPTOOL is not installed.

From within Thonny IDE itself you can install it.

Click Tools  –>  Manage Plug ins..

Image 11

Under plug in window search for esptool & install it.

Image 12

Now if you install firmware , you can see the writing starts at location 0x1000

Image 15

 

Image 16

Once the firmware is installed you can see the Micropython prompt under SHELL.

Image 17

You can type in help() to see a list of python commands to access modules ,network, etc..

Image 18

help(“modules”)

displays the list of modules available.

Image 19

machine, uos, esp , time , network are some of the frequently used modules.

Image 20

 

To control GPIO pins you need to import machine module.

the  machine module of MicroPython, which is the  “library”  of functions and  classes , to control the hardware of the microcontroller.

The machine module  has 12 functions and 12 classes :

  • Functions : reset (), reset_cause (), enable_irq (), disable_irq (), freq (), idle (), time_pulse_us (), sleep (), lightsleep (), deepsleep (), wake_reason () and unique_id ().
  • Classes : Timer (), WDT (), Pin () , Signal (), TouchPad (), ADC (), DAC (), I2C (), PWM (), RTC (), SPI () and UART () ) .

We can see this listing in Thonny using the function help(machine).

Image 1

To control an LED on / off, the following must be done:

  • First, the Pin class of the machine module is imported , which allows controlling the inputs / outputs (General Purpose Input / Output – GPIO -) of the microcontroller – and therefore, of its corresponding pins on the board. Since pin 02 ( GPIO 02 ) is connected to the integrated LED, you also have control over it.
  • Then an object that we will call pin_02 is  initialized to identify it, turning GPIO 02 “2” into an output pinPin.OUT ”.

Among the classes of the module, the class

Pin()

is used to create objects to control inputs / outputs of the microcontroller ( GPIO ), which will help us to turn on /off the LED.

Additionally, if we ask for information about the class Pin() we can see that it has 5 methods – Pin.init (), Pin.value (), Pin.off (), Pin.on () and Pin.irq () – :

 

In order to use this class , we need to know how your constructor  and its methods work .

The constructor is the subroutine whose mission is to initialize the object . The constructor of the Pin class is:

class machine.Pin (id, mode, pull, *, alt)

The arguments of the constructor are:

The arguments to turn on the blue LED integrated in the ESP32 DEVKIT  board  will be the following:

  • id 2 ” since the on board LED is connected with pin 02 ( GPIO 02 ).
  • mode Pin.OUT ” to make pin 02 become a voltage output pin .
  • pull None ” to not configure pull-up or pull-down resistors (they are only useful in the case of being an input pin Pin.IN -). It is not necessary to define this argument.
  • value 1 ” to turn on the LED-3.3V voltage output.

Once the code has been executed, we will have initialized an object , which has been assigned the name pin_02 , whose initial values convert pin 2 (GPIO 02) into an output pin and its status is on (3.3V voltage) .

The methods that we can use once the object is created  allow us to manipulate (modify) its functionalities . In the Pin class we have the following:

  • Pin.init () : Modify theinitial arguments of the constructor . You can modify the mode , pull , * (value) and alt argumentswhen new values ​​are defined.
  • Pin.value () : allows you to read the presence / absence of input voltage of the pin (without an argument is provided) or set an output voltage on the pin providing the argument. The arguments can be “ 0 ” off (0.0V) and “ 1 ” on (3.3V). Booleans can be usedas arguments.
  • Pin.off () : Sets a pin output voltage of 0.0V- off.
  • Pin.on () : sets an output voltage of the 3.3V pin – on -.
  • Pin.irq () : enables external interruptions in the pin , as long as it is an input pin .

Put together

First from machine module import the class Pin.

Then assign the built in LED GPIO pin 2 & declare it as Pin.OUT

The pin that is connected to the led is instantiated & the second argument is set as OUT ,indicating

that the pin acts as OUTPUT.

tImage 21

Now  led.value(1) makes the on board LED ON.

led.value ( 0) makes it OFF.

We have controlled the LED from Interpreter. Now we shall write the complete code in the EDITOR Section to blink the LED repeatedly.

Here we make use of the sleep class of time function to introduce delay.

Never ending loop is created using

while True:

Notice the loop starts by  colon :  & instead of braces micropython uses indentation.

 

Image 22

Click File  –>  Save as

& select Micropython device

 

Image 23

Provide the file name as main.py

You can notice , by default already boot.py is available on device.

Micropython will first execute boot.by & then looks out to execute file named main.py.

So you cannot upload file in other name to execute.If you use some other name , then the file will be executed once.After power reboot it will not execute.

Image 24

Once the file is stored click on F5 or the Run green button.

Image 25

The script is uploaded and the on board LED blinks.

To stop execution you can press the STOP Red button.

Now the chevrons >>> appear at the shell.

You can write new code & save it to device , again in the name main.py.

This is how to upload new code.

Image 26

VIDEO :

 

blog_image