loading

Step 1: Brief Introduction of MicroPython

Damien George is a computer engineer who works every day in the Python language 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 non-computer-specialized people use it as a first language. Unfortunately, it cannot achieve some very basic control. Therefore, it is inconspicuous in the field of hardware.

In order to break the limit, Damien spent six months to build Micro Python. 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, esp32, rtl8195a, nrf51822 and so on.

With Micro Python, users can access and control the basics of hardware completely through Python scripting language, such as controlling LED bulb, LCD displayer, reading voltage, controlling motor, entering SD card, network, Bluetooth, and reading sensor etc.

Step 2: Goal of the Article

After reading the article, you can have a preliminary understanding of micropython, which is mainly related to variable data type and basic syntax. To prevent being boring, we will use examples in the following to explain in-depth syntax content in details. It is recommended to manually enter the code for actual operation to deepen understanding.

Step 3: 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:

Step 4:

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 (**).

Step 5:

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, esp8266, 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.

Step 6:

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.

Step 8: 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:

Step 9:

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:

Step 10:

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:

Step 11:

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.

Function

In microPython, we need to use def statement to define a function, writing function name, parentheses, parameters in parentheses and colon: one by one, and then compiling the function in indented block. Use return statement to return the return value of function. Let’s take the computations of absolute value of my abs and summation of add functions as an example.

>>>def my_abs(x)

: . . . if x>=0

: . . . return x

. . . else

: . . . return -x

. . .

>>>my_abs(5)

5

>>>my_abs(-6)

6

After completion of function defining, we need to press return for two times to return to prompt>>> again:

>>>def add(a,b)

: . . . retrun a+b

. . .

>>>add(4,2)

6

Original article reference: http://www.arduino.cn/thread-42220-1-1.html

About This Instructable

71views

1favorite

License:

More by JFJAVENUE:How to Make a Rechargeable Mini Lightning Cloud Make Your Own Arduino Weather Station! How to Make Your Own Personalized Power Bank (3D Printing) 
Add instructable to: