Book Image

Python Programming for Arduino

Book Image

Python Programming for Arduino

Overview of this book

Table of Contents (18 chapters)
Python Programming for Arduino
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Introduction to Arduino programming


The Arduino platform was introduced to simplify electronic hardware prototyping for everyone. For this reason, Arduino programming was intended to be easy to learn by nonprogrammers such as designers, artists, and students. The Arduino language is implemented in C/C++, while the fundamentals of the sketch and program structures are derived from an open source programming language called Processing and an open source electronic prototyping language called Wiring.

Comments

Arduino follows a commenting format that is adopted from C and it is similar to higher-level languages; however, it is different from the Python comment format that we learned earlier in this chapter. There are various methods of commenting, which are as follows:

  • Block comment: This is done by covering the commented text between /* and */:

    /* This is a comment.
    *  Arduino will ignore any text till it finds until the ending comment syntax, which is,
    */
  • Single-line or inline comment: This is done by using // before the line:

    // This syntax only applies to one line.
    // You have to use it again for each next line of comment.
    int pin = 13;     //Selected pin 13

Usually, a block comment at the beginning of the sketch is mostly used to describe the program as a whole. Single-line comments are used to describe specific functions or to-do notes, such as the following one:

//TODO: explain variables next.

Variables

Like any other high-level language, a variable is used to store data with three components: a name, a value, and a type. For example, consider the following statement:

int pin = 10;

Here, pin is the variable name that is defined with the type int and holds the value 10. Later in the code, all occurrences of the pin variable will retrieve data from the declaration that we just made here. You can use any combination of alpha-numeric characters to select the variable name as long as the first character is not a number.

Constants

In the Arduino language, constants are predefined variables that are used to simplify the program:

  • HIGH, LOW: While working with digital pins on the Arduino board, only two distinct voltage stages are possible at these pins. If a pin is being used to obtain an input, any measure above 3V is considered a HIGH state. If you are using a pin for output, then the HIGH state will set the pin voltage to 5V. The opposite voltage levels are considered as LOW states.

  • false, true: These are used to represent logical true and false levels. false is defined as 0 and true is mostly defined as 1.

  • INPUT, OUTPUT: These constants are used to define the roles of the Arduino pins. If you set the mode of an Arduino pin as INPUT, the Arduino program will prepare the pin to read sensors. Similarly, the OUTPUT setting prepares the pins to provide a sufficient amount of current to the connected sensors.

We will utilize these constants later in the book and we will also explain them with example code.

Data types

The declaration of each custom variable requires the user to specify the data type that is associated with the variable. The Arduino language uses a standard set of data types that are used in the C language. A list of these data types and their descriptions are as follows:

  • void: This is used in the function declaration to indicate that the function is not going to return any value:

    void setup() {
    // actions
    }
  • boolean: Variables defined with the data type boolean can only hold one of two values, true or false:

    boolean ledState = false;
  • byte: This is used to store an 8-bit unsigned number, which is basically any number from 0 to 255:

    byte b = 0xFF;
  • int: This is short for integers. It stores 16-bit (Arduino Uno) or 32-bit (Arduino Due) numbers and it is one of the primary number storage data types for the Arduino language. Although int will be used to declare numbers throughout the book, the Arduino language also has long and short number data types for special cases:

    int varInt = 2147483647;
    long varLong = varInt;
    short varShort = -32768;
  • float: This data type is used for numbers with decimal points. These are also known as floating-point numbers. float is one of the more widely used data types along with int to represent numbers in the Arduino language:

    float varFloat = 1.111;
  • char: This data type stores a character value and occupies 1 byte of memory. When providing a value to char data types, character literals are declared with single quotes:

    char myCharacater = 'P';
  • array: An array stores a collection of variables that is accessible by an index number. If you are familiar with arrays in C/C++, it will be easier for you to get started, as the Arduino language uses the same C/C++ arrays. The following are some of the methods to initialize an array:

    int myIntArray[] = {1, 2, 3, 4, 5};
    int tempValues[5] = { 32, 55, 72, 75};
    char msgArray[10] = "hello!";

    An array can be accessed using an index number (where the index starts from number 0):

    myIntArray[0] == 1
    msgArray[2] == 'e'

Conversions

Conversion functions are used to convert any data type value into the provided data types. The Arduino language implements the following conversion functions that can be utilized during programming:

  • char(): This converts the value of any data type to the character data type

  • byte(): This converts the value of any data type to the byte data type

  • int(): This converts the value of any data type to the integer data type

  • float(): This converts the value of any data type to the floating-point number data type

As a demonstration of using these functions, check out the following example:

int myInt = 10;
float myfloat = float(myInt);

Implementation of the preceding code will create a floating-point variable, myFloat, with value 10.0 using the integer value initialized by the myInt variable.

Functions and statements

Functions, also called subroutines or procedures, are a piece of code implemented to do specific tasks. The Arduino language has some predefined functions and the user can also write custom functions to implement certain program logic. These custom functions can then be called from any part of the sketch to perform a specific task. Functions help programmers to simplify debugging, to reduce chances for error, and to organize coding concepts:

void blinkLED(){
// action A;
// action B;
}

The Arduino language has a set of library functions to simplify the programming experience. Although not all of these library functions are required by an Arduino sketch, setup() and loop() are mandatory functions and they are required to successfully compile the sketch.

The setup() function

When Arduino runs a sketch, it first looks for the setup() function. The setup() function is used to execute important programming subroutines before the rest of the program, such as declaring constants, setting up pins, initializing serial communication, or initializing external libraries. When Arduino runs the program, it executes the setup() functions only once. If you check out the Blink sketch that we used in the previous section, you can see the initialization of the setup() function, as displayed in the following code snippet:

void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
}

As you can see in our example, we used the pinMode() function to assign the role of the LED pin in the setup() function.

The loop() function

Once Arduino has executed the setup() function, it starts iterating the loop() function continuously. While setup() contains the initialization parameters, loop() contains the logical parameters of your program:

void loop() {
  digitalWrite(led, HIGH);
  delay(1000);
  digitalWrite(led, LOW);
  delay(1000);
}

As you can see in the preceding code snippet from the Blink sketch, the loop() function executes the main code that blinks the LED and repeats the process iteratively.

The pinMode() function

The pinMode() function is used to set the behavior of Arduino. As we saw in the setup() function of the Blink sketch, the pinMode() function configures the LED pin for OUTPUT:

pinMode(led, OUTPUT)

Here, the led variable is assigned to digital pin 13, whose mode will be changed by the pinMode() function.

Working with pins

Once you are done configuring the pins that will be used by your program, you also need help in reading the input from these pins or for sending signals to them. Arduino provides a few specific functions to handle these scenarios:

  • digitalWrite(): This was developed for digital I/O pins. This function sets the pin to HIGH (5V) or LOW (0V), which are already configured as OUTPUT using pinMode(). For example, the following line of code sets digital pin 13 to HIGH:

    digitalWrite(13, HIGH);
  • digitalRead(): Similar to digitalWrite(), this function helps you to read the state of a digital pin that is configured as INPUT:

    value = digitalRead(13);
  • analogRead(): This function reads the value from a specific analog pin. The value is linearly mapped between the integer value of 0 and 1023 to represent the voltage from 0V to 5V:

    value = analogRead(0);
  • analogWrite(): This function is used to provide analog output results at a digital pin. The technique is called PWM, and this will be explained in Chapter 4, Diving into Python-Arduino Prototyping. It is still important to note that this function is not designed for all digital pins, but it is only for pins that are designated as PWM pins.

Statements

If you are familiar with any other object-oriented programming language, you must have used statements extensively for your programs. The Arduino language uses traditional C/C++ statements such as if/else, while, switch/case, and for to control the flow of your program. Instead of diving deep into these statements right now, they are described later in the book with practical examples.