It’s clear that Python is the most popular programming language of 2019. The rise of Python has been especially prominent in the embedded field. It seems that everyone is talking about it.

As a high-level programming language, It allows you to focus on the core functionality of the application by taking care of common programming tasks.

The simple syntax rules of Python further makes it easier for you to keep the code base readable and application maintainable.

Zerynth opens IoT and embedded development to the huge community of Python programmers. It allows the developers to develop IoT projects using the popular 32-bit microcontrollers.

With 100+ supported libraries, Developers save a huge amount of time while using Zerynth, These libraries let the developer focus on the core of the project,  rather than handling low-level details.

In this article, we will be looking at the basics of Python, from both perspectives – the embedded development and the traditional perspective.

Python’s open source structure and simple syntax are just some of the things that recommend it for embedded and IoT projects. Unlike C, Python is not so error-prone, and it’s easily readable.

If you’ve been using it for embedded projects in the past, you’ll know what we are talking about. If you haven’t, start this tutorial and learn why everyone is talking about Python in the embedded.

Basics of Python

Let’s start with the Basics of Python Programming Language

To get started working with Python 3, you’ll need to have access to the Python interpreter. There are several common ways to accomplish this. Check this guide for installing Python for Windows, Linux and Mac OS

Your First Python Program

Often, a program called “Hello, World!” is used to introduce a new programming language to beginners. A “Hello, World!” is a simple program that outputs “Hello, World!”.

Python is one of the easiest languages to learn, and creating “Hello, World!” program is as simple as writing:

Copy to Clipboard

The “print” function basically prints the given string on the output console

Variables

Copy to Clipboard

Here, “num1” is a variable. You can store a value in a variable. Here, 3 is stored in this variable. Similarly, 5 is stored in “num2” variable.

The variables num1 and num2 are added using the ‘+’ operator. The result of the addition is then stored in another variable “sum”.

The print() function prints the output to the screen. In our case, it prints 8 on the screen.

Note that any line starting with ‘#’ is a comment. Comments are used in programming to describe the purpose of the code. This helps you as well as other programmers to understand the intent of the code. Comments are completely ignored by compilers and interpreters.

Python Operators

Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the operator operates on is called the operand.

For example:

Copy to Clipboard

Here, ‘+’ is the operator that performs addition. 2 and 3 are the operands and 5 is the output of the operation.

For example:

Copy to Clipboard

Comparison operators

Comparison operators are used to compare values. It either returns True or False according to the condition.

For example:

Copy to Clipboard

Logical operators

Logical operators are the and, or, not operators.

Bitwise operators

Bitwise operators act on operands as if they were a string of binary digits. It operates bit by bit, hence the name.

For example, 2 is 10 in binary and 7 is 111.

In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

Bitwise operations might be hard to understand, depending on your knowledge of binary system, logic gates operations.
What’s great is that these operations operate in the same manner no matter the programming language you are using.

Strings

Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes (‘…’) or double quotes (“…”) with the same result. \ can be used to escape quotes:

Copy to Clipboard

What are if…else statement in Python?

Decision making is required when we want to execute code only if a certain condition is satisfied.

The if…elif…else statement is used in Python for decision making.

Copy to Clipboard

Here, the program evaluates the test expression and will execute statement(s) only if the text expression is True.

If the text expression is False, the statement(s) is not executed.

In Python, the body of the ‘if ‘ statement is indicated by the indentation. The body starts with an indentation and the first unindented line marks the end.

Python interprets non-zero values as True. None and 0 (zero) are interpreted as False.

As an example:

Copy to Clipboard

When you run the program, the output will be:

Copy to Clipboard

In the above example, ‘num > 0’ is the test expression.

The body of  ‘if’ is executed only if this evaluates to True.

When variable num is equal to 3, test expression is true and statements inside the body of ‘if ‘ are executed.

If variable num is equal to -1, test expression is false and statements inside the body of ‘if’ are skipped.

The print() statement falls outside of the if block (unindented). Hence, it is executed regardless of the test expression.

Python if…elif…else Statement

Copy to Clipboard

The ‘elif’ is short for else if. It allows us to check for multiple expressions. If the condition for ‘if’ is False, it checks the condition of the next ‘elif’ block and so on.

If all the conditions are False, body of else is executed. Only one block among the several if…elif…else blocks is executed according to the condition. The if block can have only one else block. But it can have multiple elif blocks.

What is for loop in Python?

The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal.

Copy to Clipboard

Here, “val” is the variable that takes the value of the item inside the sequence on each iteration.

Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.

For example:

Copy to Clipboard

When you run the program, the output will be:

Copy to Clipboard

while Statements

The while statement is in Python similar to C and other most used languages.

The basic example is:

Copy to Clipboard

This code will print 1, 2, 3….. until the execution is killed.

break and continue Statements, and else Clauses on Loops

The break statement, like in C, breaks out of the smallest enclosing for or while loop.

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. This is exemplified by the following loop, which searches for prime numbers:

Copy to Clipboard

Yes, this is the correct code. Look closely: the else clause belongs to the for loop, not the if statement.

The output is:

Copy to Clipboard

When used with a loop, the else clause has more in common with the else clause of a try statement than it does that of if statements: a try statement else clause runs when no exception occurs, and a loop else clause runs when no break occurs. For more on the try statement and exceptions, see tut-handling.

The continue statement, also borrowed from C, continues with the next iteration of the loop.

Functions in Python

In Python, a function is a group of related statements that perform a specific task.

Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable.

Furthermore, it avoids repetition and makes code reusable.

Copy to Clipboard

Above shown is a function definition which consists of following components.:

  • Keyword ‘def’ marks the start of function header.
  • A function name to uniquely identify it. Function naming follows the same rules of writing identifiers in Python.
  • Parameters (arguments) through which we pass values to a function. They are optional.
  • A colon (:) to mark the end of function header.
  • Optional documentation string (comments) to describe what the function does.
  • One or more valid Python statements that make up the function body. Statements must have the same indentation level (usually 4 spaces).
  • An optional return statement to return a value from the function.

How to call a function in Python?

Once we have defined a function, we can call it from another function, program or even the Python prompt. To call a function we simply type the function name with appropriate parameters.

Copy to Clipboard

Default Argument Values

The most useful form is to specify a default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow. For example:

Copy to Clipboard

This function can be called in several ways:

  • giving only the mandatory argument: ask_ok(‘Do you really want to quit?’)
  • giving one of the optional arguments: ask_ok(‘OK to overwrite the file?’, 2)
  • or even giving all arguments: ask_ok(‘OK to overwrite the file?’, 2, ‘Come on, only yes or no!’)

Basics of Zerynth

Basically every example we saw before can be replicated also with Zerynth.

To get started with Zerynth, check this great installation guide. In addition, the Getting Started Guide will show you how you can run your first examples on Zerynth Studio.

For more information about each function and module mentioned below, check the documentation of Zerynth.

Your First Zerynth Program

We are going to start our examples with the simplest one we can make: A “Hello, World!” example!

This is also the simplest example to start with embedded development.

In Zerynth Studio:

Copy to Clipboard

The example starts with importing the streams library; That library is used for communication between the board and the PC serially.

Then in the infinite loop, the device prints “Hello Zerynth!” every second.

Sleep function is used as a delay for 1 second. Note that in Zerynth the sleep() function suspends the current thread for time expressed in time_units BUT all the other threads are free to continue their execution!

Blinking a LED

Then we will have a look at an example that involves bit handling. We are going to blink a LED for a given time then switch it off.

Copy to Clipboard

Reading a digital pin

In the last example, we had the microcontroller drive an output signal on a pin. In this one, we’ll see how we can we drive input signals to the microcontrollers.

Copy to Clipboard

Serial Communication

In this example, we will have a deeper look at the serial communication between the microcontroller and the PC, Through our Streams library

Copy to Clipboard

WiFi Connection

Now, We’ll have a look at an example that uses Wifi connection.

This is a simple wifi driver initialization and connection to a wifi network.

Copy to Clipboard

MQTT Example

Finally, we will have a look at a full example, that connects your device to the internet and send data to the cloud using MQTT.

Copy to Clipboard

Download Zerynth Studio

If you haven’t downloaded Zerynth Studio yet, now is a perfect time. It’s free to download and available for Windows, Linux, and Mac OS.

Share This Story, Choose Your Platform!

About the Author: Luigi F. Cerfeda

Luigi is a biomedical engineer, and is currently Sales Director at Zerynth. Being one of the first members on the team, he has held various roles in the company as he has a deep knowledge of the IoT market and Industry 4.0.

Follow Zerynth on

Latest Posts