0

members

Easy Basics Project 75a MicroPython programming basics

of Acoptex.com (Not selected)

Basics: Project 075a

Project name: MicroPython programming basics

Tags: MicroPython, programming basics

General

We will learn MicroPython programming basics in this project.

Programming in MicroPython is very similar to programming in Python - all of the language features of Python are also existing in MicroPython but there are some xceptions. Due to microcontrollers and embedded systems are more limited than our PCs, MicroPython are not comming with the full standard library by default.

If you know how to program in Python, programming in MicroPython is the same but you need to bear in mind that MicroPython is used for constrained devices. So, keep your code as simple as possible.

This project explains the basics of Python programming language syntax:

  1. Mathematical operators
  2. Relational operators
  3. Data types
  4. print() function
  5. Conditional statements
  6. While and for loops
  7. User defined functions
  8. Classes and objects
  9. Modules

In this project we are using uPyCraft IDE as a development environment.

Read about Installing uPyCraft IDE to program ESP32 Development board and ESP8266 ESP-12EESP32 development board - Uploading MicroPython firmwareESP8266 ESP-12E module - Uploading MicroPython firmwareESP32 Development board and ESP8266 ESP-12E module - MicroPython

1.Mathematical Operators

Micropython can perform mathematical operations. The following tlist shows the mathematical operators supported:

Operator Mathematical Operation

+ Addition

Subtraction

* Multiplication

/ Division

// Division, discarding the decimal point

% Remainder after division

See examples below:

You can perform other mathematical operations if you import the math module, like trigonometric functions, logarithm, exponentiation and so on.

2.Relational Operators

You can make comparisons using relational operators. These compare the values on either sides and show the relation between them.

Operator Description

== Equal to

!= Not equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

See the examples below:

3. Data Types

Variables can store several types of values, not just whole numbers. That’s where data types come in. A data type is a classification of a value that tells what operations can be done with the value and how it should be stored.

The following list shows the data types we are using moreoften in our projects:

Data type Description

int (Int) Integer (whole number)

float (Float) Number with a decimal point

str (String) Set of characters between quotation marks

bool (Boolean) True or False

Let’s make variables with different data types:

The first value assigned to c, is an integer, which is a whole number.

The a variable contains a float value, which is a number with a decimal.

The third value, 'Hello World!', is a string, which is a series of characters. A string must be put inside single ('Hello World!') or double quotation ("Hello World!") marks.

Finally, d is a Boolean, which is a type that can only take either True or False.

There is a function to check the data type of a variable: the type() function. This function accepts as argument the variable you want to check the data type: type(variable)

For example, after declaring the variables in the previous example a, b, c, and d, you can check its data type. For example, if you type type(a) it will return  

This will tell that a is the float. When you check other variables:

4. print() Function

The print() function prints the message between parentheses into the Shell. This is specially useful in our projects to debug the code and keep track of a process.

5. Comments

Comments in Python start with the hash character (#) and continue to the end of the line. A comment is useful to add "notes" in your program or to tell anyone who reads the program what the script does. This doesn’t add any functionality to your program.

6. Conditional Statements

You will normally need to perform different actions depending on whether a certain condition is True or False to write useful programs. We are talking about conditional statements. They have the following structure:

expr is a Boolean expression and it can be either True or False. If it is True, the statement right after it is executed. The statement  should be indented so that Python knows what statement belongs to each expression.

The elif statement stands for else if and runs only if the first if condition is not True. The else statement only runs if none of the other expressions are True.

There is no limit to the number of elif statements in a program. It’s also not necessary to include an else clause, but if there is one, it must come at the end.

In the Arduino IDE, we use {} curly brackets to define code blocks. With MicroPython, we use indentation. Additionally, you need to use a colon : after each expression. Contrary to the Arduino IDE, the expression doesn’t need to be inside parentheses.

Please note that Python’s standard indentation is 4 spaces. MicroPython indentation should be only 2 spaces to fit more code into the microcontroller memory.

7. While and For loops

Loops allow you to execute a block of code multiple times for as long as a condition is met. There are two kinds of loops: while and for loops. For example, you can print all numbers from 1 to 10 with a while loop:

The code that belongs to the while loop, indicated by the indentation, is executed as long as the value in the number variable is less than or equal to (<=) 10. In every loop, the current number is printed and then 1 is added to it.

You can also print numbers from 1 to 10 using a for loop, like this:

The for loop is executed as long as the value in the number variable is within the range of 1 and 11. The range() function automatically assigns the next value to the number variable, until 1 below the final number you specify.

You should use a for loop when you want to repeat a block of code a certain number of times. Use a while loop when you want to repeat code until a certain condition is no longer met. In some situations, you can use either one, oftentimes one is more suitable than the other.

Similar to the conditional statements, the for and while Boolean expressions should have a colon : right after them, and the expressions to be executed should be indented.

7. User-defined Functions

To define a new function, you use the word def followed by the name you want to give the function and a set of parentheses (and arguments inside, if necessary). After the parentheses you add a colon : and then tell the function what instructions to perform. The statements should be indented with 2 spaces (in MicroPython). For example:

This function converts the temperature in Celsius to Fahrenheit, for example:

The celsius_to_fahrenheit() function accepts as argument a temperature in Celsius (temp_celsius). Then, it does the calculation to convert the temperature. Finally, it returns the temperature in Fahrenheit (temp_fahrenheit).

Please note that functions don’t necessarily need to return something. They could just perform some work without the need to return anything.

8. Classes and Objects

Python is an Object-Oriented Programming (OOP) language. There are two important concepts you need to understand about OOP: classes and objects.

A class is a blueprint for objects. It defines a set of attributes (data and functions) that characterize an object. The functions inside of a class are called methods. Classes are defined by the keyword class followed by the name of the class. For example:

class Car:

  (...)

Please note that by convention, classes’ names in Python should be CapWords. However, you can give whatever name you want.

An object is an instance of a class. It’s simply a collection of data and methods into a single entity. Through the object, you can use all functionalities of its class. Let’s check together a simple example.

If we would like to define several cars in a Python program using the same attributes, we can think of the term car as a class. We may want to define a car using attributes like name, age, country and so on.

So, we can create a class called Car. Our class will have the following attributes: make, model, transmission, age and color. You can add as many attributes as you want. We will also create a function (method) that prints a description of the car based on its attributes.

As you can see, we define a new class by using the keyword class, followed by the name we want to give to the class.

Inside the Car class, we define several variables to hold values. By default the make, the model, the transmission, the color are empty strings, and the age is 0. Then, we also define a function (method) that prints all the variables values into the Shell.

All functions inside a class should have the self parameter as argument and other arguments, if needed.

The self parameter refers to the object itself. It is used to access variables that belong to the class. For example, to access the make variable inside the class, we should use self.make.

Now that we’ve create a class, we can create as many Car objects as we want by using that class. The Car object will have a make, model, transmission, age and color. We will also be able to print its description using the description() method.

For example, to create a new Car object called car1:

>>> car1 = Car()

Set the object’s properties

To set the make, model, transmission, age and color of the car1 object. You can do it as follows:

>>> car1.make = "Alpha Romeo"

>>> car1.model = "Giulia"

>>> car1.transmission = "Manual"

>>> car1.age = 5

>>> car1.color = "Silver"

Calling methods

Later in your code you can use the created description() method on any Car object. To call the description() method on the car1 object:

>>> car1.description()

This should print the following:

Alpha Romeo Giulia Manual is 5 years old and she is Silver.

You should now understand that you can create as many objects as you want using the same class and you are able to use the available methods with all the objects of that class.

The constructor method

Instead of having to define a class, and then set the object’s properties, which can be time consuming, you can use the constructor method inside your class.

The constructor method is used to initiate data as soon as an object of a class is instantiated. The constructor method is also known as __init__ method.  Using the __init__ method, the Car() class looks as follows:

Then, to instantiate a Car object with the same attributes we’ve defined earlier, we just need to do the following:

>>> car1 = Car("Alpha Romeo","Giulia","Manual",5,"Silver")

If you call the description() on the car1 object, you’ll get the same result:

>>> car1.description()

Alpha Romeo Giulia Manual is 5 years old and she is Silver.

9. Modules

A module is a file that contains a set of classes and functions you can use in your code – you can also call it library. To access the classes and functions inside that code, you just need to import that module into your code.

You can create your own modules, or use already created modules from the standard Python library. When it comes to MicroPython, it only comes with a small subset of the standard Python library, but it does come with a set of modules to control GPIOs, make networks connections and much more.

Importing modules/libraries is as simple as using:

import module_name

For example, to import the machine library that contains classes to control GPIOs, type the following:

import machine

In most programs you won’t need all the classes from one module. You may just want to import a single class. For example, to import only the Pin class from the machine module:

from machine import Pin

Assigning Values to Variables

In Python you don’t need to declare what type each variable is. If you’re used to program your boards using Arduino IDE, you know that you need to declare the type of a variable when creating a new variable. 

Variables are simply a storage placeholder for values: number or text. To assign a value to a variable you use the equal sign (=), with the variable name on the left and the value on the right.

For example, to create a variable to hold the GPIO number where a Servo is connected to, you can simply type the following: Servo_pin = 23

In the Arduino IDE, you would have: const int Servo_pin = 23;

As you can see, Python is much simpler than programming in Arduino IDE (Using C language).

Note: the names you give variables can’t have spaces and are case sensitive, so Servo_pin is different from SERVO_PIN or servo_pin.

Summary

We have learnt MicroPython programming basics in this project.

The main differences between your Arduino sketches and programs in MicroPython:

  • You don’t use semicolon ; at the end of a statement
  • After Boolean expressions in conditional statements and loops, you use a colon :
  • To define code blocks use indentation instead of curly brackets {}
  • When creating a variable, you don’t need to define which data type it is – you don’t need to declare a variable
  • Indentation in MicroPython is 2 spaces


Other projects of Acoptex.com
Easy CBASIC Lesson 9 Compiling and debugging in Visual Studio of Acoptex.com in Csharp 10-04-2019
Easy Basics: Project 081d ESP8266 ESP-12E module and Nextion HMI display of Acoptex.com in ESP8266 ESP-12 24-03-2019

« Go back to category
Is this project fake? Report it!   
Recommend to a friend
Published at 07-10-2018
Viewed: 280 times