Lesson 4. Programming basics of Arduino in C.

Basic Arduino lessons

This lesson provides the minimum knowledge necessary for programming Arduino systems in C language. You can only view it and use it as reference information in the future. Those who have programmed on C in other systems can skip the article.

Previous lesson     List of lessons     Next lesson

I repeat that this is the minimum information. Description of pointers, classes, string variables, etc. will be given in subsequent lessons. If something turns out to be incomprehensible, do not worry. In the following lessons there will be many examples and explanations.

 

Structure of the Arduino program.

The structure of the Arduino program is simple enough and in the minimal version consists of two parts setup() and loop().

void setup() {

// the code is executed once when the program is started

}

void loop() {

// the main code is executed in a loop

}

The setup() function is executed once, when the power is turned on or the controller is reset. Usually, initial settings of variables, registers, occur in it. The function must be present in the program, even if it does not contain anything.

After setup() finishes, control passes to the loop() function. She performs commands in an infinite loop written in her body (between braces). Actually these commands and perform all the algorithmic actions of the controller.

 

Initial syntax of the C language.

; semicolon. Expressions can contain as many arbitrary spaces, line breaks. The end of the expression is indicated by the semicolon character.

z = x + y;
z =    x
+ y  ;

{} The braces define a function block or expressions. For example, in the setup() and loop() functions.

/* ... */ comment block, be sure to close.

/* is a comment block */

// single-line comment, do not close, it works until the end of the line.

// this is one line of the comment

 

Variables and data types.

A variable is a memory cell in which information is stored. The program uses variables to store the intermediate calculation data. Data can be used for calculations of different formats, of different digits, so the variables in C have the following types.

Data type Bits Number range
boolean 8 true, false
char 8 -128 … 127
unsigned char 8 0 … 255
byte 8 0 … 255
int 16 -32768 … 32767
unsigned int 16 0 … 65535
word 16 0 … 65535
long 32 -2147483648 … 2147483647
unsigned long 32 0 … 4294967295
short 16 -32768 … 32767
float 32 -3.4028235+38 … 3.4028235+38
double 32 -3.4028235+38 … 3.4028235+38

Data types are selected based on the required accuracy of calculations, data formats, and so on. It is not necessary, for example, for a counter counting up to 100, to choose the type long. It will work, but the operation will take more data and program memory, it will take more time.

 

Declaration of variables.

Specifies the data type, and then the variable name.

int x; // declare a variable with the name x of type int
float widthBox; // declare a variable named widthBox of type float

All variables must be declared before they are used.

A variable can be declared in any part of the program, but it determines which blocks of the program can use it. Variables have scope.

  • Variables declared at the beginning of the program, prior to the void setup() function, are considered global and are available anywhere in the program.
  • Local variables are declared inside functions or blocks such as the for loop, and can only be used in declared blocks. There are several possible variables with the same name, but different visibility areas.

int mode; // variable available to all functions

void setup() {
// empty block, initial settings are not required
}

void loop() {

long count; // the variable count is only available in the loop() function

for (int i = 0; i <15;) // variable i is available only within the loop
  {
     i ++;
  }
}

When declaring a variable, you can set its initial value (initialize).

int x = 0; // declare a variable x with initial value 0
char d = 'a'; // declare a variable d with the initial value equal to the code of the symbol "a"

In arithmetic operations with different types of data, data types are automatically converted. But it is better to always use an explicit transformation.

int x; // variable int
char y; // char variable
int z; // variable int

z = x + (int) y; // the variable y is explicitly converted to int

 

Arithmetic operations.

= assignment
+ addition
- subtraction
* multiplication
/ division
% remainder of the division

 

Relational operations.

== equal to
!= not equal
< less
> more
<= less or equal
>= more or equal

 

Logical operations.

&& logical AND
|| logical OR
!! logical NOT

 

Pointer operations.

* indirect addressing
& get the address of a variable

 

Bitwise operations.

& AND
|| OR
^ EXCLUSIVE OR
~ INVERSION
<< SHIFT LEFT
>> SHIFT RIGHT

 

Mixed assignment operations.

++ + 1 to the variable
-- - 1 from the variable
+= addition
-= subtraction
*= multiplication
/= division
%= remainder of division
&= bit AND
|= bit OR

 

Selection options, program management.

IF statement checks the condition in parentheses and executes the subsequent expression or block in curly brackets if the condition is true.

if (x == 7)   // if x = 7 then z = 1
z = 1;

if (x> 7)   // if x> 7, then the block z = 0, y = 9 is executed
  {z = 0; y = 9; }

 

IF ... ELSE allows to choose between two options.

if (x> 6) // if x> 6, then the block z = 0, y = 10 is executed
  {
   z = 0;
   y = 10;
  }
else // otherwise this block is executed
  {
   z = 20;
   y = 30;
  }

 

ELSE IF - allows multiple choice

if (x> 6) // if x> 6, then the block z = 0, y = 10 is executed
  {
    z = 0;
    y = 10;
  }

else if (x> 30) // if x> 30, this block is executed
  {
  }

else // otherwise this block is executed
  {
   z = 20;
   y = 30;
  }

 

SWITCH CASE - multiple choice. Allows you to compare a variable (in the example it's x) with several constants (in examples 6 and 12) and execute a block in which the variable is equal to a constant.

switch (x) {

  case 6:
    // code is executed if x = 6
    break;

  case 12:
    // code is executed if x = 12
    break;

  default:
    // code is executed if none of the previous values ​​match
    break;
}

 

FOR loop. The construction allows you to organize loops with a given number of iterations. The syntax is:

for (action before the start of the cycle;
         continuation condition;
        action at the end of each iteration) {

// body code of the loop

}

An example of a cycle of 100 iterations.

for (i = 0; i <100; i ++) // initial value 0, finite 99, step 1
{
     sum = sum + I;
}

 

WHILE cycle. The operator allows you to organize loops with a construction:

while (expression)
  {
   // body code of the loop
  }

The loop is executed until the expression in parentheses is true. Example of a cycle for 20 iterations.

x = 0;
while (x <20)
  {
   // body code of the loop
   x ++;
  }

 

DO WHILE - a loop with an exit condition.

do
  {
   // body code of the loop
  } while (expression);

The loop is executed while the expression is true.

 

BREAK is an exit statement from the loop. Used to interrupt the execution of for, while, do while loops.

x = 0;
while (x <100)
  {
   if (z> 30) break; // if z> 30, then exit the loop
   // body code of the loop
   x ++;
  }

 

GOTO is an unconditional jump operator.

goto mark1; // go to mark1
..................
mark1:

 

CONTINUE - skip operators to the end of the loop body.

x = 0;
while (x <100)
  {
   // body code of the loop
   if (z> 30) continue; // if z> 30, then return to the beginning of the loop body
   // body code of the loop
   x ++;
  }

 

Arrays.

An array is a memory area where several variables are sequentially stored.

Declares an array as follows.

int ages [15]; // an array of 15 variables of type int
float weight [10]; // an array of 10 float variables

When declaring, arrays can be initialized:

int ages [5] = {16, 23, 27, 42, 48};

Refer to array variables as follows:

x = ages [3]; // x is assigned a value from the 3 element of the array
ages [4] = 35; // 4 array element is set to 35

The numbering of array elements is always from zero.

 

Functions.

Functions allow to perform the same actions with different data. The function has:

  • the name by which it is called;
  • arguments - the data that the function uses to calculate;
  • the data type returned by the function.

A custom function is described outside the setup() and loop() functions.

void setup () {
  // the code is executed once when the program is started
}

void loop () {
  // the main code is executed in a loop
}

// declare a custom function named functionName
type functionName (type argument1, type argument1, ..., type argument)
  {
   // the body of the function
   return ();
  }

An example of a function that calculates the sum of the squares of two arguments.

int sumQwadr (int x, int y)
  {
  return (x * x + y * y);
  }

The function call is:

d = 3; b = 2;
z = sumQwadr (d, b); // in z is the sum of the squares of the variables d and b

Functions are built-in, user-defined, plug-in.

Very briefly, but this data should be enough to start writing programs in C for Arduino systems.

The last thing I want to tell you in this lesson is how to design programs in C. I think if you read this lesson for the first time, you should skip this section and return to it later when you have what to make out.

 

Recommendations for the design of programs in the language C.

The main purpose of external design programs is to improve the readability of programs, reduce the number of formal errors. Therefore, to achieve this purpose, you can safely violate all the recommendations.

Names in C.

Names representing data types must be written in a mixed register. The first letter of the name must be uppercase.

Signal, TimeCount

Variables should be written with names in a mixed register, the first letter lowercase.

signal, timeCount

Constants must be written in uppercase. As a separator, the bottom underscore.

MAX_TEMP, RED

Methods and functions should be called verbs written in a mixed register, the first letter in lowercase.

getTime, setTime

On the remaining formalities in the following lessons, as necessary.

In the next lesson, write the first program, learn how to read data from digital ports and control their state.

Previous lesson     List of lessons     Next lesson

Leave a Reply

Your email address will not be published. Required fields are marked *