Go Down

Topic: ESP8266 micropython- Tutorial 1: Introduction (Read 163 times) previous topic - next topic

muzi

What is microPython?
Damien George is a computer engineer and is doing some robotic projects. One day, he suddenly had an idea: is it possible to use Python language to control microcontroller and to realize the control of robot?

We know that Python is a relatively easy scripting language and has a strong community support. Some people use it as a first language. Unfortunately, it cannot achieve some very basic control.

Damien spent six months to build MicroPython. It is based on ANSI C. Syntax is the same as Pyton 3. It has its own parser, compiler, virtual machine and class library, etc. Currently, it supports a lot of 32-bit processors, such as STM32 series, esp8266 modules, esp32 modules, rtl8195a, nrf51822 and so on.

After reading, you can have a preliminary understanding of micropython. It is recommended to manually enter the code for actual operation to deepen understanding.



Variable Data Type, Character Type
Character type is any text enclosed in single quotes' or "double quotation marks", such as 'abc', "xyz". ' ' or " " is just symbol representing character, not a part of string. Therefore, string 'abc' only has three characters, a, b, c. If ' is also a character, we use " " to enclose it. For example "I'm Ok" includes 6 characters, I, ', m, space, O, K. For example:

>>>str="hello DFRobot"
>>>Print(str)
hello DFRobot

str is a defined string variable and assigned to helloDFRobot. Then output the string.

Boolean Type
A Boolean value only has two values, either True or False (note that the first letter should be uppercase).

For example:

>>>True
True
>>>3>2
True
>>>5>7
False

and operation is collation operation. Only when all are True, result of and operation is True
>>>Trueand True
True
>>>Trueand False
False

or operation is either-or operation. As long as one of them is True, result of or operation is True
>>>Trueor True
True
>>>Trueor  False
True

not operation is not-operation. It is unary operation, which changes True into False, and False into True
>>>not True
False
>>>not 1>5
True

Boolean value is often used in conditional judgment, eg:
>>>def int(age):
if age>=18:
 print('adult')
else:
 print('teenager')


Actual result is as follows:

Integer
Creating a new integer variable and assigning variable is the same process. For a=123 or b=-123, sign on the left of equal mark is variable name, and sign on the right is the value to be assigned to. It is very simple. Data of natural assignment should be whole number, which is simply explained as (positive integer and negative integer). Currently, operators in front of variables of integer data type supported by micropython are: plus (+), minus (-), multiplied by (×), divided by (/) and power (**).

Floating Point Type

Floating point number is decimal. It is called floating point number because the decimal point position of a floating point number can be changed when expressed in scientific notation, for example, 1.23×109 and 12.3×108 are completely the same. Floating point number can be written in mathematics like 1.23, 3.14, -9.01, etc. However, for extremely large or small floating point number, it is must be written in scientific notation. Replacing 10 in e, 1.23×109 is 1.23e9, or 12.3e8. 0.000012 can be written as 1.2e-5. If you cannot understand, you just remember---floating point number is inaccurate decimal. There may be approximation error for floating point operation.
>>>pi=3.14
>>>print(pi)
3.14

In different platforms (such as: esp32 arduino, esp8266 arduino wifi bee, ameba, etc.), the output π value may be different.

Tuple
Tuple is an ordered list. Tuple and list are very similar, but tuple cannot be modified once initialized. When displaying tuple with only one element, it will add a comma, eg:

>>>t=(1,)
>>>t
(1,)


What we defined in the above is a tuple, t=(1,).

If there is no comma, the defined is not tuple, eg:

>>>t=(1)
>>>t
1


When outputting two tuples as they are combined, the result is all elements of the two tuples, eg:

>>>t1=(1,2,3)
>>>t2 = (4,5,6)
(1,2,3,4,5,6)


List

Content of list can be changed. List is an ordered collection. You can always add and delete the elements.

>>>l=[1,2,3,4]
>>>print(l)
[1,2,3,4]


Define a list of l=[1,2,3,4].


Variable 1 is a list. By using len() function, we can get the element number of list.
>>>len(l)
4


Use index to access elements at different locations of the list. Remember that index starts at 0.
>>>l[2]
3
>>>l[0]
1


If you want to replace an element into another, you can directly assign to the corresponding index location.
>>>l[1]=9
>>>print(l)
[1,9,3,4]

List is a variable ordered table. You can insert element to the specified location. For example, for position of index no. 1, insert(i,x) is inserting x at position i. The remaining elements are pushed back. If i is greater than the list length, it is added to the end. If i is less than 0, it is added at the begging.
>>>l.insert(1,6)
>>>print(l)
[1,6,2,3,4]


To delete element at the specified position, use po(i) method. i is the index position.
>>>l.pop(2)
3
>>>print(l)
[1,2,4]


Dict
microPython has a build-in dictionary: full name of dict is dictionary. It is also called map in C++ and java and other languages, using key-value storage, generally stored in the method of red-black tree in memory, and with fast search speed.
>>>d={'df':4, 'yu':18, 'wu':15}
>>>d['yu']
18

Dict means dictionary. It will be a little complicated to write dict to represent dictionary in use, so we use d to represent dict. If not, we can directly use dict.

In addition to defining at initialization for putting data into dict, we can also use key:
>>>d['li']=12
>>>d=['li']
12

As a key only corresponds to one value, when inputting value to key for many times, the latest value will replace the previous value.
>>>d['jack']=10
>>>d['jack']
10
>>> d['jack']=9
>>> d['jack']
9


To delete a key, use pop(key) method. The corresponding value will also be deleted from dict
>>>d.pop('yu')
18
>>>d
{'df':4', 'wu':15}


Quote

For immutable objects (including: int, string, float, numeric type number, tuple), a is created as a copy of b. a and b will point to different memory addresses. a and b are independent.
eg:
>>>a="I am ouki"
>>>b=a
>>>print(b)
I am ouki
>>>a="hello DFRobot"
>>>Print(b)
I am ouki


We define a=" I am ouki", then assign value of a to b. It is I am ouki when outputting the value of b, and the value of a is still I am ouki at this time. We now assign a new value, a="helloDFRobot", to a, and then we output b. The value of b will not change. It is still I am ouki.

For variable objects (including: dictionary, list), a is created as a quote of b. Elements of a and b share the same memory address and are shared.

Basic Syntax Semicolon and Colon
It doesn't need semicolon at the end of each line, which is not the same as other language. Of course, writing semicolon is also ok. For condition and function, it should be followed by colon. If not, it will report the following error:


Loop

for Loop

for loop can traverse items of any sequence, such as a list or a string. Syntax of for loop is as follows:
    foriterating_var in sequence:
    statements(s)
eg:
>>>for i in range(5):
. . .        print(i)
0
1
2
3
4

Actual result is as follows:


While loop

While statement is used to circularly executing program, that is, circularly executing a program under certain conditions to handle the same tasks which needs to be repeated. The

basic form is:
While judgment condition:
Execute statement….
eg:
>>>i=9
>>>while(i>0):
. . .    print(i)
. . .        i-=1
9
8
7
6
5
4
3
2
1

Actual result is as follows:

The executable statement can be a single statement or statement block. Judgment condition can be any expression. Any non-zero, or null value is true. When judgment condition is false, the loop ends.


reference: ESP8266 micropython- Tutorial 1: Introduction

muzi

We take blink and breathing light as examples to learn the use of micropython on ameba. However, currently ameba doesn't support Timer, and there is no breathing light demo.

Blink Program
Code: [Select]
   from machine import Pin
   import time
   led = Pin('PC_1',Pin.OUT)
   while True:
    led.value(1)
    time.sleep(0.5)
    led.value(0)
    time.sleep(0.5)


Using micropython on ameba for the first time, we must burn micropython onto ameba board. The burning method is very simple. Download the following link and then unpack it. We will get a ram_all.bin file (if there is problem of unpacking under windows, think about unpacking under linux or virtual machine). Burn the file onto ameba board, and then we can use micropython on ameba. Of course we need a terminal (putty) to write micropython
Link: https://github.com/cwyark/micropython/releases/download/v1.8.3/ram_all.tar


After ameba is linked to PC, we need to install a driver. At the completion of installation, we can see MBED (a mobile device) in my computer. https://developer.mbed.org/media/downloads/drivers/mbedWinSerial_16466.exe.


Then right-click->my computer->management->device manager->port. We can see the port number of ameba. Here you can see my port no. is COM7.
烧录方法:
Burning method:



After completing driver installation, you can see a mobile device MBED in my computer. Double click to open it. Copy the unpacked ram_all.bin file to MBED. Meanwhile you can see that the green light is flashing, which reflects burning. When it stops flashing, burning is completed.


After finishing preparation, open putty terminal. The following interface will appear. Follow the arrow to modify selection.

After finishing preparation, open putty terminal. The following interface will appear. Follow the arrow to modify selection.

These are default selection of 115200 8 1 None None.

After finishing setting, click open. Then click enter key several times. There will be an interface as follows.

Press Ctrl+E in the terminal. There will be a paste command line as follows

Copy the blink program and then right-click in the terminal to finish the copy as shown below. Press Ctrl+D for completing copy. Press Ctrl+C to cancel copy.

It is very simple. Led light is flashing. Press Ctrl+C for exit after completion (currently, ameba doesn't support the command).

Use of micropython on esp32

esp32

Temporarily, esp32 doesn't support Timer, therefore there is no breathing light demo.


Blink Program

Code: [Select]
from machine import Pin
   import time
   led = Pin(13,Pin.OUT)
   try:
     whileTrue:
       led.value(1)
       time.sleep(0.5)
       led.value(0)
       time.sleep(0.5)
   except:
     led.value(0)

Method for burning micropython firmware


Use the official programming tools to burn. Before burning, we need to compile micropython firmware first. Refer to the official compiling method. You can directly use my compiled firware: micropython firmware to save the trouble. Note that flash initial address of each firmware cannot be changed. Address of official firmware compiling method is:
https://github.com/micropython/micropython-esp32/tree/esp32/esp32


After downloading the official burning tool, double click the burning tool, as shown below:

There will be two interfaces after opening:

Click ESP32DownloadTool on the right interface. We can see the interface of burning firmware. Now we are not far from success. Keep going! At this time, import the three compiled or downloaded bin files of micropython into burning tool. Check the port no. in my computer. Right-click->my computer->management->device manager->port. Note: be sure the address is right, otherwise burning may not be successful or it cannot work normally after burning.

After burning, close burning tool. Open and operate terminal putty of micropython. Select port No. (COM12), connection type(Serial).


Other settings are as follows. Click Open after setting.

Press enter key several times after Open. We can enter micropython language at putty terminal.

Press Ctrl+E to enter paste mode. Right-click in the mode to paste program. Press Ctrl+D to complete pasting. Micropython will execute the program of pasting.

Now led light is flashing. Isn't it quite simple to light blink! After completion, press Ctrl+C to exit executing program. Led light stops flashing.


Use of micropython on esp8266

Blink and breathing light are supported on esp8266. Let's learn how to operate blink and breathing light on esp8266 by using micropython!




Blink program

Code: [Select]
  from machineimport Pin
   import time
   led = Pin(14,Pin.OUT)
   try:
    while True:
     led.value(1)
     time.sleep(0.5)
     led.value(0)
     time.sleep(0.5)
   except:
     led.value(0)


Breathing light program:

Code: [Select]
   from machineimport Pin,Timer,PWM
   pwm =PWM(Pin(14),100)
   polar = 0
   duty = 0
   def setLed(t):
    global duty,polar
    if(polar == 0):
      duty+=16
      if(duty >= 1008):
        polar = 1
    else:
      duty -= 16
      if(duty <= 0):
        polar = 0
        pwm.duty(duty)
        tim = Timer(1)
        tim.init(period=10,mode=Timer.PERIODIC, callback=setLed)
   try:
    while True:
      pass
   except:
    tim.deinit()
    pwm.deinit()


Firstly, we need to link esp8266 to PC, and then find the port no. of esp8266 in the same method as that of esp32 and ameba. My port no. here is COM9 (you need to find your own).
To use micropython on esp8266, we must burn the micropython firmware of esp8266 to board. There is compiled firmware on micropython official website for downloading. Address is: http://micropython.org/download.


Open and run terminal putty of micropython. Select port no. (COM9), connection type(Serial).

Other settings are shown below. Click Open after setting.

Press enter key several times after Open. We can enter micropython language at putty terminal.


Breathing light

After that we can realize blink in the same method as that of esp32 and ameba. There is a led light installed on esp8266 board, and is no need of external connection of led light. Method of finishing breathing light is also the same. I will save the trouble of introduction here.



IO port reading on esp32 platform


IO port reading program

Code: [Select]
  from machineimport Pin
  import time
  button =Pin(34,Pin.IN)
  while True:
   print(button.value())
   time.sleep(1)


Enter the read program of IO port to terminal for running. IO34 pin is connected to nothing, so what it read is low level, output 0. When we connect IO34 pin to 3.3V pin, what it read is high level, output 1.


Reference: ESP8266 micropython- Tutorial 2: Micropython GPIO

spycatcher2k

Please use your own website/blog etc. to post this type of material. All you are doing is consuming bandwidth and space.
-=-
http://www.uk-pcb.co.uk - UK Based PCB Fab & Assembly Company
Design & Assembly work undertaken - Arduino repairs & testing - PM for details. Arduino & C# PC programming.

Go Up