Basic - Python commands

In this educational activity we want to teach the students all the python commands needed for implementing the data acquisition software. This with reference to the specific commands of the programmable logic unit MINDSTORM EV3.

Preparing For This Tutorial:

Time constraints:

Exercise

Read what is written and run all the boxed programs.

Theory

Part 1

Print to screen

In python the print command is

#!/usr/bin/env python3

print("Hello World! ")

The instruction receives a string (identified as the sequence of characters enclosed in quotation marks) and prints that on the screen. The string can also be given to the command as follows:

#!/usr/bin/env python3

text = "Hello World!"

print(text)

To write the text on more than one line, you can use the \emph{return} character \n

#!/usr/bin/env python3

text = "Hallo \\n World! "

print(text)

We can also make some simple computer calculations

#!/usr/bin/env python3

a = 2

b = 3

print("a + b = ",a+b)

print("a \* b = ",a*b)

print("a raised to b = ",a**b)

Exercise Write a program that prints the sum of two numbers and then elevates it to the cube.

Handle strings

It is useful in Python to be able to perform operations with string objects, with particular reference to the sum operation

#!/usr/bin/env python3

text = "Hello World! " + "I’m happy!"

print(text)

The sum can only occur between two string objects. If you want to add a number type object to a string type, you must first transform the number into a string.

#!/usr/bin/env python3

a = 2

text = "There are " + str(a) + " apples on the table."

print(text)

Exercise Write a program that prints your name and age.

Print to file

To print lines of text in a file it is necessary to follow the following procedure:

1.Create an object of type file opened in ”write” mode. The instruction is open and the parameter that says the file is opened in write mode is ”w”.

2.Write a line of text (if you want to wrap then you must indicate to write the return character).

3.Close the file.

#!/usr/bin/env python3

FileText = "This is written into the file\n"

ScreenText = "This is written on the screen"

print(ScreenText)

out_file = open("MyFile.txt","w")

out_file.writelines(FileText)

out_file.close()

This program writes the file called MyFile.txt in the same folder as the program file. Run the program, find the file, open it and check that exactly what you expected is written inside.

Exercise Write a program that prints the name and age of three people in a table.

Import a library

Each programming language has its own libraries written to provide the user with a ready-made package of functions. An important library is that of mathematics in order to perform complex operations such as the square root.

#!/usr/bin/env python3

import math

a = 36

b = math.sqrt(a)

print("The square root of " + str(a) +" is " + str(b) )

Exercise Write a program that illustrates the calculation of the Pythagorean theorem.

Create a function

Often in a program the same sequence of instructions is executed many times in an always identical way, except for the initial value of some parameters. To avoid having to rewrite the entire sequence of operations, it is possible to define a function. In the following example we define the function Pit which calculates the hypotenuse of a right triangle knowing the measurements of the two sides.

#!/usr/bin/env python3

import math

def Pit(a,b):

  return math.sqrt(a**2+b**2)

  d=Pit(3,4)

print("Se i cateti valgono 3 e 4,")

print("l’ipotenusa vale: "+str(d))

print("If the cathets are 5 e 12,")

print("the hypotenuse is: "+str(Pit(5,12)))

However, it is not necessary for a function to return any value to the program as a result, such as the function StampaPit implemented below

#!/usr/bin/env python3

import math

def Pit(a,b):

  return math.sqrt(a**2+b**2)

def StampaPit(a,b):

  print("If the cathets are "+str(a)+" e "+str(b)+",")

  print("the hypotenuse is: "+str(Pit(a,b)))

StampaPit(3,4)

StampaPit(5,12)

StampaPit(8,15)

Exercise Write a program in which there is a function that, given a pair of numbers, returns their sum. Use this function within the program.

It is also possible to import a single function from a particular library with the following syntax:

#!/usr/bin/env python3

from math import sqrt

print("I print the square root of 36: it is "+str(sqrt(36)))

2.6 Request for data

You may need to ask the user to enter some data. The instruction that tells the software to ask the user for a value is input(”text”). This function receives as a parameter the string to be printed on the screen when it is requested to enter the data. This function returns what the user typed on the keyboard, treating it as a string variable.

#!/usr/bin/env python3

name = input("Tell me your name.")

print("Your name is "+name)

If the required values are numeric, they must be explicitly converted into numbers before being used.

#!/usr/bin/env python3

import math

def Pit(a,b):

  return math.sqrt(a**2+b**2)

def StampaPit(a,b):

  print("If the cathets are "+str(a)+" and "+str(b)+",")

  print("the hypotenuse is: "+str(Pit(a,b)))

  a = input("Enter the value of the first cathet ")

  b = input("Enter the value of the second cathet: ")

StampaPit(float(a),float(b))

Manage time

To manage the time inside a software it is necessary to import the relative library. At this point many useful functions will be available.

#!/usr/bin/env python3

import time

print("L’istante attuale \`e: ")

print(time.strftime("%d/%m/%Y - %H:%M:%S"))

StartingTime = time.time()

input("How old are you?")

NowIs = time.time()

ElapsedTime = NowIs-StartingTime

print("It took you "+str(ElapsedTime)+" seconds to respond")

Exercise Write a program that asks you three questions by writing to you the moment you answered each question and how much time has passed between the first and last answer.

Array

It is often convenient to use objects called array that are made up of a sequence of indexed objects. It is possible to directly access each of the objects in the list through its index.

#!/usr/bin/env python3

MyArray = [5,10,15,25,40,65]

print(MyArray[1])

print(MyArray[3])

MyArray[3] = MyArray[3]+6

print(MyArray[3])

The *While* loop

The while loop implements the repetition of a certain sequence of instructions as long as a certain condition is respected.

#!/usr/bin/env python3

a = 0

while a<7:

  print("a = "+str(a))

  a=a+1

Exercise Write a program that calculates the sum of the first 100 integers using the while loop.

The *for* loop

The for loop implements the repetition of a certain sequence of instructions as long as a certain counter takes all the values from an initial to a final value. The initial and final values correspond to those of an array. In the following program the array myRange contains all the numbers from 0 to 7

#!/usr/bin/env python3

myRange = range(0,8)

print("in my array there are the following elements: ")

print(*myRange)

text = ":"

for count in myRange:

  text = text + str(count) + ":"

print(text)

Exercise Write a program that calculates the sum of the first 100 integers using the for loop.

if..elif..else

The command if..elif..else allows you to make a choice based on a particular condition. Let’s start with the following program.

#!/usr/bin/env python3

a = int(input("Write your age: "))

if a >= 18:

  print("You are of age!")

else

  print("You are an underage person.")

If we needed to concatenate more than one condition we can write

#!/usr/bin/env python3

a = int(input("Write your age: "))

if a >= 18:

  print("You are of age!")

elif a<6:

  print("You’re not going to school yet")

else:

  print("Hello underage student.")

Exercise Write a program that tells you if you are a boy or a girl after asking your name.

Summarizing

Now try writing a program that uses what you learned to solve this problem: find the solution to the equation 2−x = x

with an approximation less than 0.001, knowing that the solution sought is in the range [0 : 1] and write it on the screen. Once the solution has been found, write the equation and its solution on a file. Repeat the whole thing five times.

Part 2

Commands to know

1. Contact sensor

To start with, you need to create the sensor object. We already have everything we need in the library.

#!/usr/bin/env python3

import time

from ev3dev2.sensor.lego import TouchSensor

touch_sensor = TouchSensor()

while not touch_sensor.is_pressed:

  print("Press the sensor")

  time.sleep(2)

print("Good boy! you pressed the sensor")

2. Color sensor

To start with, you need to create the sensor object. We already have everything we need in the library. Since the sensor can work by measuring the color or the reflected brightness, it will be necessary to set which of the two modes must be selected

#!/usr/bin/env python3

import time

from ev3dev2.sensor.lego import ColorSensor

color_sensor = ColorSensor()

color_sensor.mode=’COL-COLOR’ # Put the color sensor into COL-COLOR mode.

colors = [’unknown’,’black’,’blue’,’green’,’yellow’,’red’,’white’,’brown’] for count in range(0,10):

    text = "measuring colors "

    index = color_sensor.value()

    text = text + colors[index]

    print(text)

time.sleep(5)

Reflected brightness sensor

To start with, you need to create the sensor object. We already have everything we need in the library

#!/usr/bin/env python3

from ev3dev2.sensor.lego import ColorSensor

color_sensor = ColorSensor()

lum = color_sensor.reflected_light_intensity

print("The reflected light intensity is "+str(lum))

Exercise write a program that writes the measured reflected brightness 10 times, when the contact sensor is pressed.

Temperature sensor

To start with you need to create the sensor object; you need to import the INPUT 2 channel of the programmable unit, import the sensor object and then create it by assigning it to the input 2 port. Next we set the sensor to work in degrees centigrade. At this point it is possible to read the sensor value

#!/usr/bin/env python3

from ev3dev2.sensor import INPUT_2

from ev3dev2.sensor.lego import Sensor

temperature_sensor = Sensor(INPUT_2)

temperature_sensor.mode = "NXT-TEMP-C"

T = temperature_sensor.value()

print("temperature is: "+str(T))

Acoustic module

The programmable unit is capable of emitting sounds and musical notes, as well as synthesizing the voice.

#!/usr/bin/env python3

from ev3dev2.sound import Sound

sound = Sound()

text = input("Write something I can read.")

sound.speak(text)

Summarizing

Write a program that every time we press the contact sensor button, the color sensor reads the color, says it out loud, writes it on the screen, and records on a file on disk, in an appropriate table, the color read and the time interval during which the button was pressed.

Next Section - Application of ultrasonic sensor