View Course Path

Arduino programming and syntax : A definitive guide for beginners

Once you have set up your Arduino IDE, it is time to begin writing the code. Coding for the Arduino platform is effortless. There are a ton of libraries to make things easier. The syntax is fairly simple too. In this post, we will cover almost all the essential language elements of an Arduino sketch (program). After this, you should be able to read, write and undertake any Arduino coding project.

Contents

What is an Arduino program?

The Arduino program is usually written in the Arduino IDE. The program is a set of instructions in embedded C. It has some special header files as zip files that are available online to provide specialised functions. An Arduino program is known as a sketch.

The Arduino code should contain two functions as void setup() and void loop(). These two are the main elements of any Arduino code. They are known as functions. We will take a closer look at them soon.

All declarations are made in void setup(). The name contains the word ‘setup’ which should give away its purpose. The actual commands to be performed and the computing process are coded within the void loop() function. The ‘loop’ signifies that the sketch will run infinitely.

Arduino IDE

What language is used for writing an Arduino program?

Embedded C is used to write the Arduino programs. It is used for applications that very near to the hardware. That directly communicates with the hardware. It is very similar to C and C++. But it has some built-in functions other than normal functions used in ordinary C.

What is a sketch?

The Arduino program is called a sketch. It contains the instructions to be performed by the Arduino board, which are written in Embedded C.

What are the general syntax elements in Arduino programming?

The general syntax for writing the Arduino program is almost similar to that of ordinary C and C++. Those who are familiar with basic C and C++ can do it easily. If you would like a quick recap of your C knowledge, we have a free C programming course for beginners that you can check out.

The general syntax includes the following elements:

#define

What comes to your mind when you try to think of this commands purpose? Probably something to do with introducing an element right? That’s true.

#define is used to assign a variable to the constant that has to be used in the program. It doesn’t need any memory space. During compile time the compiler can replace the variables by the constant. Generally, the constants are defined by using the ‘const’ keyword in place of #define. You shouldn’t use a semicolon after #define or equal to sign after #define; else it will show a cryptic error.

Syntax: #define variable constant

Parameters: variable is the name, that has to be assigned to the value. Constant is the value that is used in the program.

Example

#define a 3  //correct

#define a 3; //Error

#define a=3 //Error

In this case, the compiler will replace the variable a by 3.

#include<>

Clearly, this tells the program to include something. The question is, what? Well, you can use this command to include additional library files into your sketch for adding some additional functionalities.

It is one of the best features of the Arduino IDE. There are several libraries available online. They are specially written for Arduino’s purpose. Each library gives you some additional access to the sensors and modules.

Akin to the #define command, there is no semicolon needed at the end of the #include statement. Otherwise, it will show a cryptic error.

Syntax: #include<library file>

Parameters: The library file is the additional header to be added. Here’s how you can include a library file in your Arduino IDE.

Example

This example includes the SoftwareSerial library so that its functions may be used to control a GPS.

#include <SoftwareSerial.h> //library file

static const int RX = 4, TX = 3;

static const uint32_t GPSBaud = 9600;

// The serial connection to the GPS device

SoftwareSerial ss(RX, TX);

void setup()

{

Serial.begin(115200);

ss.begin(GPSBaud);

}

void loop()

{

while (ss.available() > 0){

Serial.write(ss.read());

}

}

All the commands like ss.read in the above sketch are courtesy of the library file we included in the beginning. Without that library file, it would become incredibly difficult to implement GPS functionality.

Block comments /* */

You can use it to write comments in the sketch. Comments are the lines that are used to notify the programmer of that particular code snippet. It is not exported to the processor, so it doesn’t take any memory space in the microcontroller’s memory. It is only to help you understand the code. Writing good comments is a key part of writing clean, readable code.

The starting of the comment block is marked by /*, and the ending is marked by */.

Example

/*Blink turns on an LED on for on second, 
then off for one second, repeatedly*/

Comment //

Block comments can have multiple lines. When you wish to have a single line comment you can use // and then write the comment. Similar to/**/, these comment lines are also ignored by the compiler. It doesn’t take any space in the microcontroller’s memory. Moreover, it helps you to understand how the program works.

Syntax: //

Example

#define a=3

digitalWrite(a,1); //Turn the LED on

curly braces {}

Curly braces or brackets are an important part of C and C++ programming languages. An open curly brace { must be followed by a closing curly brace }. It is said to be balanced. The Arduino IDE has a convenient feature as the braces are automatically balanced while creating an open brace. It is highlighted when it is not balanced.

Unbalanced braces tend to cryptic error. The code within the braces is said to be a block that may be a function.

Example

Void getdata(datatype argument){

//code

}

Loops

while(condition){

//code

}

Conditional statements

if(condition){

//code

}

Semicolons ;

Used at the end of a statement. If you forget to put a semicolon at any statement other than #define and #include, you will be notified by the compiler error.

Example

int a=3;

What is the general structure of a sketch?

A sketch in the Arduino IDE has two main parts in its structure: these are setup() and loop().

void setup()

The setup() function should be the first one that is called when a sketch starts to run or compile. This function block is used to initialize the pin-modes, variables and also the baud rate. It will only run once when the Arduino is powered or tends to reset.

Example Code

#define a=3

/*Blink turns on an LED on for on second, then off for one second, repeatedly*/

void setup()

{

pinMode(a,OUTPUT); //this is a command that sets the nature of an Arduino pin as an output. More on this later.

}

void loop(){

//code

}

void loop()

It is the block that contains the code which has the instruction that has to be performed infinitely by the microcontroller from when the Arduino board is powered on till when it’s powered off.

Example Code

#define a=3

/*Blink turns on an LED on for on second, then off for one second, repeatedly*/

void setup()

{

pinMode(a,OUTPUT); //Declaring the pinmode

}

Void loop()

{

digitalWrite(a,0);// Turn LED off

delay(1000);

digitalWrite(a,1); // Turn LED on

delay(1000); //Delay 10seconds

}

What are the different types of variables in an Arduino program?

There are about 18 datatypes in the Arduino programming language. However, we will introduce only the most commonly used ones here. The rest will be introduced whenever the need arises throughout this free Arduino course.

What is int?

Integers are the data type that can store numbers. In Arduino Uno, an int can store a 16- byte value that is 2-byte. Here, int has the range of -32,768 to 32,767. That is -2^15 to 2^15. In some boards like Arduino Due, an int can store a 32-bit value that is 4- byte.

int can also store negative numbers using complement math. That the most significant bit represents a sign. A type called unsigned int can store only positive numbers.

Syntax: int variable = value;

Example

int count=0; // initializing an integer with the name "count" and giving it a value of 0.

Void setup(){

Serial.begin(9600);

}

Void loop(){

Count++;

Serial.println(count);

Delay(1000)

}

What is char?

It helps to store a character. The char data type has at least an 8-bit size.

Eg. ‘A’

Characters are also stored as numbers. These standard numbers that are allocated for all characters are called ASCII numbers. For example, the ASCII value of ‘B’ is 66.

Syntax

Char variable= character

Example

char a = ‘A’;

char b=’;’;

What is float?

It helps to store decimal numbers. Floating-point numbers are used to approximate the analog and continuous values due to their greater resolution when compared to integers. Range of float data type is from     -3.4028235E+38 to 3.4028235E+38. It has 32-bit storage.

Syntax

float variable=value;

Example

float a, b=12.22;

int x=1, y;

y=x/2 //y has 0 because int can’t store fractions and decimals

a=(float)x/2; //z has 0.5 now

What is bool?

It can store only two values, true or false. It occupies one byte.

Syntax: bool a=true/false;

Example

bool a=true;

while(a){

Serial.println(“Yes”); //prints yes infinetly

}

What is the local variable?

Local variables are variables with local scope. We can use it only within the code block where we declare it.

What is a global variable?

Global variables are variables with global scope. It means we can use it anywhere in the sketch.

What are the different arithmetic functions that can be performed in an Arduino?

We can perform all the basic mathematical operations in the Arduino programming language.

What is multiplication operation?

Operator: *

It can multiply the two numbers.

Syntax: value1 *value2;

Example

int a=5;

int b=5,c;

c= a*b; // c has 25

What is the remainder operation?

Operator: %

It helps us to find the remainder when one integer is divided by another integer. It works only for int datatype, not for float datatype

Syntax: remainder=dividend % divisor;

Example

int a[10];

void setup(){

pinMode(0, INPUT);

}

void loop(){

a[i]=digitalRead(0);

i=(i+1)%10;

}

What is the division operation?

Operator: /

It can divide two numbers.

Syntax: quotient=divider/divisor;

Example

int a=5;

int b=5,c;

c= a/b; // c has 1

What is the addition operation?

Operator: +

It can add the two numbers with the same data type.

Syntax: value1 + value2;

Example

int a=5;

int b=5,c;

c= a+b; // c has 10

What is the subtraction operation?

Operator:

It can subtract the two numbers with the same data type.

Syntax: value1 – value2;

Example

int a=5;

int b=5,c;

c= a - b; // c has 0

What is the assignment operation?

Operator: =

It can assign the numbers on the right side to the variable on the left side of the operator.

Syntax: variable = value2;

Example

int a=5;

int b=analogRead(3) //b has the sensor reading

What are the different comparison functions in an Arduino program?

These functions help to compare two numbers in an Arduino program.

What is equal to operation?

Operator: ==

It checks whether the two numbers on the left and right sides are the same or not and returns ‘true’ or ‘false’.

Syntax: value1 == value2;

Example

int a=1;

int b=1,count=0;

if(a==b) //true

count++; //count increases

What is not equal to operation?

Operator: !=

It checks whether the two numbers on the left and right sides are not the same or not. And returns true or false.

Syntax: value1 != value2;

Example

int a=1;

int b=2,count=0;

if(a!=b) //true

count++; //count increases

What is less than operation?

Operator: <

It checks whether the numbers on the left are less than the numbers on the right side and returns true or false.

Syntax: value1 < value2;

Example

int a=1;

int b=2,count=0;

if(a<b) //true

count++; //count increases

What is less than or equal to operation?

Operator: <=

It checks whether the numbers on the left is less than or equal to the numbers on the right side or not and returns true or no.

Syntax: value1 <= value2;

Example

int a=1;

int b=2,count=0;

if(a<=b) //true

count++; //count increases

int a=2;

int b=2,count=0;

if(a<=b) //true

count++; //count increases

What is greater than operation?

Operator:>

It checks whether the numbers on the left is greater than the number on the right side and returns true or false.

Syntax: value1 > value2;

Example

int a=2;

int b=1,count=0;

if(a>b) //true

count++; //count increases

What is greater than equal to operation?

Operator: >=

It checks whether the numbers on the left is greater than or equal to the number on the right side and returns true or false.

Syntax: value1 >= value2;

Example

int a=2;

int b=1,count=0;

if(a<=b) //true

count++; //count increases

int a=2;

int b=2,count=0;

if(a==b) //true

count++; //count increases

What is pin mode declaration?

Function: pin mode(Pin, mode)

We use the pinMode command to define the function of pins on the Arduino board. It helps to declare the PIN and the mode on which the pin is performed. It initializes the pins of the Arduino board which are to be used as input pins or output pins.

Arguments:

Pin- The PIN may be a digital or analog pin of the Arduino board where the hardware is connected.

Mode – There are two modes as INPUT mode and OUTPUT mode. The input mode helps you to get the data. The output mode helps you to perform a function on that pin.

We usually use this function is the void setup() block.

Returns

None

Example:

void setup() {
pinMode(13, OUTPUT);
}

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

Digital pins control

These digital I/O pins are used to perform operations in terms of 0’s and 1’s. And these pins can deliver 3.3V in Arduino Uno. There are 13 digital I/O pins present in the Arduino Uno board. There are two main functions at our disposal:

digitalRead(Pin)

You can use it to get the digital input from the devices such as sensors and Arduino shields in the form of 0’s and 1’s.

Argument:

Pin – The pin that connects with the sensor.

Returns

0 or 1.

Example

int Pin = 8; // Initializing Arduino Pin
int Reading;

void setup() {
  pinMode(Pin, INPUT); // Declaring Arduino Pin as an Input
}

void loop() {
  Reading = digitalRead(Pin); // Reading status of Arduino digital Pin
  
  if(Reading == HIGH)
  {
    Serial.println("HIGH");
  }

  if(Reading == LOW)
  {
    Serial.println("LOW");
  }
 
}

//code from:theengineeringprojects.com

digitalWrite(Pin, Mode)

It is useful in giving digital output to devices such as modules, shields, LED, motor and other electronic devices. In the form of 0’s and 1’s. That pin can give up to 3.3V when the output is 1.

Argument:

Pin – The pin that connects with the sensor.

Mode- 0 or 1, which means LOW/HIGH.

Returns

None.

Example

const int p = 2 ;
void setup()
{
pinMode(pwm,OUTPUT) ;
}
void loop()
{
digitalWrite(p,HIGH) ;//writes a HIGH status to pin p
delay(50) ;
digitalWrite(p,LOW) ;
delay(50) ;
digitalWrite(p,HIGH) ;
delay(50) ;
digitalWrite(p,LOW) ;
delay(50) ;
}

Analog pins control

There are five analog I/O pins present in the Arduino Uno board. It can send and receive analog signals. It is useful in PWM control and also helps to get accurate readings of the sensor.

AnlogRead(Pin)

You can use it to get the analog input from the devices such as sensors and shields in the form of 0’s and 1’s.

Argument:

Pin – The pin that connects with the sensor.

Returns

Analog readings

Example

const int pwm = 2 ; 
const int adc = 0 ; 
void setup()
{
pinMode(pwm,OUTPUT) ; 
}
void loop()
{
int adc = analogRead(0) ;  //reads analog data from ADC
adc = map(adc, 0, 1023, 0, 255); 
analogWrite(pwm,adc) ; 
}

AnalogWrite(Pin, Value)

You can use this function to give the analog output to the devices such as modules, shields, LED, motor and other electronic devices. It also helps in PWM control.

Argument:

Pin – The pin that connects with the sensor.

Value – Duty cycle that ranges between 0 and 255.

Returns

None

Example

const int pwm = 2 ; 
void setup()
{
pinMode(pwm,OUTPUT) ; 
}
void loop()
{
analogWrite(pwm,25) ; //writes output 25 on pin 2
delay(50) ; 
analogWrite(pwm,50) ; 
delay(50) ; 
analogWrite(pwm,100) ; 
delay(50) ; 
analogWrite(pwm,225) ; 
delay(50) ; 
}

What are branch or redirect statements?

What is the break statement?

Syntax: break

You can use this statement to break the loop when the given condition satisfies. That means it comes out of the loop.

Example:

int a;

while(True){

a=digitalRead(3); //a stores the digital input at pin 3

if(a==1){ // check whether the digital input is 1

break; //breaks when the digital input is 1.

}

}

What is the return statement?

Syntax: return value

It returns the value to the variable. Usually, functions use this return statement.

The value may any of the data types. But it needs to be specified at the function declaration.

Example:

int value(int a){

if(a>50){

return a-50;

}

else{

return a;

}

}

Void loop(){

int a;

a=value(analogRead(3)); // pass the analog reading at pin 3 to the function.

Serial.println(a); /* prints original value-50 if the original value exceeds 50 otherwise no                 change occur in original value*/

}

What is the continue statement?

Syntax: continue

It skips the statements that are below to it when the given condition satisfies.

Example:

for(int i=0;i<100;i++){

if(i%2==0){ //checks whether i is even or not.

continue; //skip the below statements if i is an even number

}

analogWrite(3,i) //Controls the PWM at pin 3 according to i

delay(50);

}

What is the goto statement?

Syntax: goto

Transfers the pointer to the labeled point.

Example:

int a;

While(1){

if(analogRead(3)>250){

goto action; /*pass the program flow to the action when the analog reading is greater than 250 */

}

}
action:

digitalWrite(3,HIGH);

What are the control statements?

Control statements allow you to add a condition to a loop. If you want to control the number of times a loop executes with some parameters, then control statements are the right tools for you.

What is ‘for’ statement?

Syntax: for(Starting condition; stoping condition; incrementing/decrementing condition){}

Arguments: There are three arguments inside the for statement.

First, you need to initialize the variable. And you can assign the starting number to that variable.

The second is the stopping condition. The statement runs the code until the variable satisfies this condition.

Next, third is the changing condition that states how to increment or decrement the variable for upcoming iterations.

We have covered the working of the for loop in-depth here. The conditional loops in the Arduino programming language are similar to the ones we saw in our course on C programming.

Example:

for(int i=0;i<100;i=i*i){ /* i is initialised as 0, it stops when I reaches 100 and the I is incremented by i*I */

digitalWrite(3,HIGH);

delay(100);

digitalWrite(3,LOW);

delay(100);

}

What is the while statement?

Syntax: while(stoping condition){ incrementing/decrementing statement}

Arguments: It is the stopping condition.

The while block must contain the incrementing/decrementing statement within it. And also you need to initialize the variable before calling the while statement.

We have covered the working of the while loop in-depth here.

Example:

int a=0

while(a<100){ // runs untill a reaches 100

digitalWrite(3,HIGH);

delay(100);

digitalWrite(3,LOW);

delay(100);

a=a+5; //a increments by 5

}

What is the do-while statement?

Syntax: do{

}while(stoping condition)

Arguments: while statement contains the stoping condition.

The advantage of the do-while statement is that it will run the code within it at-least once even if the condition is not satisfied.

They do block must contain the incrementing/decrementing statement within it. And also you need to initialize the variable before calling the do-while statement.

We have covered the working of the do-while loop in-depth here.

Example:

int a;

do{

digitalWrite(3,HIGH);

delay(100);

digitalWrite(3,LOW);

delay(100);

}while(if(digitalRead(1))); // runs untill the D1 pin gives input

What is the Serial begin function?

Syntax: Serial.begin(value)

Argument: value – baud rate

Baud rate is the rate of transfer of data. When we communicate with a device, we need to make sure that the transmission speed and receiving speed are the same on the two ends of the communication. The baud rate gives the rate of data transfer. Inverse it, and you will get the number of bits being transmitted per second.

We can use different baud rates, they are 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200.

Example:

void setup(){

pinMode(1, INPUT);

Serial.begin(9600);

}

What is the Serial print function?

It prints the data as a human-understandable ASCII text.

Syntax: Serial.print(Data, Format)

Arguments:

Data

Format- It is not necessary, but it helps you to print the data in a specified format such as binary, octal, decimal.

Example:

Serial.print(68) //prints 68

Serial.print(1.5555) //prints 1.55

Serial.print(“Naveen”) //prints “Naveen”

Serial.print(78, OCT) //prints “116”

Serial.print(“abc”) ;Serial.print(“def”); //prints “abcdef”

What is the Serial print ln function?

It prints the data as a human-understandable ASCII text. That return ‘\r’ and ‘\n’ so that the next statement prints in the new line.

Syntax: Serial.println(Data, Format)

Arguments:

Data

Format- It is not necessary, but it helps you to print the data in a specified format such as binary, octal, decimal.

Example:

Serial.println(68) //prints 68

Serial.println(1.5555) //prints 1.55

Serial.println(“Naveen”) //prints “Naveen”

Serial.println(78, OCT) //prints “116”

Serial.print(“abc”) ;Serial.print(“def”);

/*prints “abc”

         “def” */

What is the Serial parse Int function?

It looks for the next valid integer if the current input is not an integer.

Syntax:

Serial.parseInt()

Serial.parseInt(lookahead)

Serial.parseInt(lookahead, ignore)

Arguments:

lookahead: Look ahead for the integer

SKIP_ALL (default one): It ignores all characters other than digits or minus sign ‘-‘.

SKIP_NONE: It doesn’t skip anything.

SKIP_WHITESPACE: It skips tabs, spaces.

Returns

It returns the next valid integer.

Example

#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
char valA;
int valB;

void setup()
{
Serial.begin(9600);
lcd.begin(16,2);
}

void loop()
{
  if (Serial.available()>0)
  {      
    valA=Serial.parseInt();
    lcd.write(valA);
    valB=Serial.read();
    lcd.write(valB);
  }
}

What is the Serial parse Float function?

It returns the first valid integer from the serial buffer.

Syntax:

Serial.parseInt()

Serial.parseInt(lookahead)

Serial.parseInt(lookahead, ignore)

Arguments:

lookahead: Look ahead for the integer

SKIP_ALL (default one): It ignores all characters other than digits or minus sign ‘-‘.

SKIP_NONE: It doesn’t skip anything.

SKIP_WHITESPACE: It skips tabs, spaces.

Returns

It returns the next valid float.

Example

void setup() {
  Serial.begin(9600);
  for (int i = 0; i < FILTERSAMPLES; i++) {
    filterSamples[i] = 0;
  }

  Serial.println("Remove all weight from the scale, then type ok and press enter.");
  while (!Serial.find("ok"));
  zeroOffset = readADC(0); 
  Serial.println();
  Serial.println("Place egg on the scale and type its weight in grams, then press enter.");
  grams = Serial.parseFloat();
  while (grams <= 0) {
    grams = Serial.parseFloat();
  }

What is String()?

It creates a string class. That is, a sequence of characters. There are many types to construct strings from different datatypes that format them as a sequence of characters. It returns an instance of string class

  • Within double quotes: a string of characters (e.g. “Naveen”)
  • Within single quotes: a single character (e.g. ‘N’)
  • It can be another instance of a String object.
  • Converts to a long integer with the specified base
  • Afloat or double with specified decimal places

Syntax

string(Val)

string(Val,base)

string(Val, decimal places)

Example

string a=string(13);

Gives the string “13”

string a=string(13, HEX);

Gives “D”, that is a hexadecimal representation of 13. You can prefer binary too by replacing HEX by BIN.

What is an Array?

An array is a collection of homogenous variables. They are accessed by using an index number like a[0], a[1]. Arrays are zero-indexed. The first element of the array is always at index 0, and the size of the array is total number-1.

Using loops, you can manipulate arrays.

Syntax: You can create an array by following methods,

int a[6];

int a[]={1,2,3,4,5,6};

Where a[2] contains 3

char a[6]= “Naveen”;

Example:

int a[5]={0,1,2,3};

It has only four elements, but the size is five, so a[4] provides garbage value. And a[6] has an invalid address.

You can assign a value to an array index as,

a[0] = 1;

And also, you can get the value by,

b=a[0];

Then, you can also print and access the elements of the array by using a loop.

for(int i=0;i<5;i++){

Serial.println(a[i]);

}

We have covered the working of arrays in C in-depth here.

What is a Function?

Other than built-in functions, you can also write your functions. Using this, we can divide the large program into basic building blocks.

It contains a set of programming statements with curly braces as {}. It provides reusability.

User-defined functions are classified into four types, they are

  • Function with no arguments that returns no value.
  • Then, the function with no arguments that returns a value.
  • Function with arguments that returns no value.
  • And the function with arguments that returns a value.

Advantages:

  • Using functions will avoid rewriting same code again and again
  • You can call it called many times
  • It helps to understand the code easily

We have covered the working of the functions in C in-depth here.

Conclusion

There’s a lot more that you can do with an Arduino, and we will cover the next stage of programming an Arduino at a later stage in this Arduino course. However, what we have seen in this post should be more than enough to get you up and running with most projects. If there is any query that you have, we are always happy to help. Let us know in the comments, and we’ll get back to you. Feel free to bookmark this page for all future reference.

2 thoughts on “Arduino programming and syntax : A definitive guide for beginners

  1. i love your work easy to understand I give you AA++ for your work .
    im 60 year olde ime just sarting to worke on pc and Arduino

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.