Here is the CheatSheet for the Arduino programming language, with the different instructions and statements available in the language.
Program Structure
Basic Structure
// Structure of a basic program
void setup() {
// Initializations, executed once at startup
}
void loop() {
// Main code, executed in a loop
}
Comments
// Line comments
/*
Block of comments
*/
Functions
void myFunction() {
// Function code
}
// Call a function
myFunction();
Inputs and Outputs
Change Mode
pinMode(pinLED, OUTPUT); // Set pinLED as output
// Predefined constants
HIGH, LOW, INPUT, OUTPUT, INPUT_PULLUP
Digital
// Reading
int value = digitalRead(pin);
// Writing
digitalWrite(pin, value);
Analog (PWM)
// Reading
int value = analogRead(pin);
// Writing
analogWrite(pin, value);
Time Control
Predefined Functions
// Predefined variables
millis(), delay(), delayMicroseconds()
Blink without delay
unsigned long currentMillis = millis(); // Get the current time in milliseconds
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis; // Update the previous time
// .. do whatever you want
}
Communication
Serial (UART)
Serial.begin(9600); // Start communication
Serial.print("Hello"); // Send data
Serial.println(" World"); // Send with newline
while (Serial.available()) { // Read data
char data = Serial.read();
}
I2C
#include <Wire.h>
void setup() {
Wire.begin(); // Start I2C communication
}
void loop() {
Wire.beginTransmission(8); // I2C device address
Wire.write("Hello"); // Send data
Wire.endTransmission(); // End transmission
}
SPI
#include <SPI.h>
void setup() {
SPI.begin(); // Start SPI communication
}
void loop() {
digitalWrite(SS, LOW); // Enable device
SPI.transfer(0x0A); // Send data
digitalWrite(SS, HIGH); // Disable device
}
Operators and Comparators
Comparators
//x equal to y
x == y
//x not equal to y
x != y
//x less than y
x < y
//x greater than y
x > y
//x less than or equal to y
x <= y
//x greater than or equal to y
x >= y
Arithmetic Operators
//assignment operator
a = b
//addition
a + b
//subtraction
a - b
//multiplication
a * b
//division
a / b
//modulus
a % b
Bitwise Operators
//binary and
a & b
//binary or
a | b
//binary xor
a ^ b
//binary not
a ~ b
//left shift
a << b
//right shift
a >> b
Compound Operators
//increment
a++
//decrement
a--
//compound addition
a += b
//compound subtraction
a -= b
//compound multiplication
a *= b
//compound division
a /= b
//compound and
a &= b
//compound or
a |= b
Boolean Operators
//not
!a
//and
a && b
//or
a || b
Access Operators
//indirection operation
*variable
//address operation
&variable
Variable Declaration and Type Conversion
Void
//empty type (only for functions)
void
Booleans
//boolean, false or true
boolean = false;
Integers
//integer, 16 bits, from -32,768 to 32,767
int var = 100;
//integer, 16 bits, from 0 to 65535 (except on Due, where it is 32 bits)
unsigned int var = 100;
//integer, 16 bits, from 0 to 65535
short var = 100;
//integer, 32 bits, from -2,147,483,648 to 2,147,483,647
long var = 100000L;
//integer, 32 bits, from 0 to 4,294,967,295
unsigned long var = 100000L;
Floating Point
//floating point, 32 bits, from -3.4028235E+38 to 3.4028235E+38. Precision 6 digits
float var = 1.117;
//identical to float, except on Arduino Due where it is 64-bit floating point
double var = 1.117;
Bytes
//8 bits, from 0 to 255
byte var = B10010;
//16 bits, unsigned, from 0 to 65535
word var = 10000;
Characters
//8 bits, from -128 to 127
char var = 'A';
//8 bits, from 0 to 255
unsigned char var = 240;
Variable Conversion
//converts to char
char(variable);
//converts to byte
byte(variable);
//converts to int
int(variable);
//converts to word
word(variable);
//converts to long
long(variable);
//converts to float
float(variable);
Variable Qualifiers
//STATIC
//Variables visible only inside a function,
//and whose value is maintained between calls to it.
static int variable;
//CONST
//Variables whose value cannot be redefined after initialization
const float pi = 3.14;
//VOLATILE
//Variables in which the compiler is told not to store in the registers
//of the microprocessor, but rather forces updates in memory. This
//is done when there is a possibility that the value of the variable is
//modified by another process running concurrently with the current one
//(for example when using threads or interrupts)
volatile int variable = LOW;
Arrays
Creating Arrays
//declare vector
int myArray[5];
//initialize vector
int myArray[] = {2, 4, 8, 3, 6};
//declare and initialize vector
int myArray[5] = {2, 4, -8, 3, 2};
Manipulating Arrays
//assign value to array element
myArray[0] = 10;
//get value of array element
x = myArray[4];
Text Strings
Texts as Character Arrays
char string1[15];
char string2[8] = {'a', 'r', 'd', 'u', 'i', 'n', 'o'};
char string3[8] = {'a', 'r', 'd', 'u', 'i', 'n', 'o', '\0'};
char string4[ ] = "text";
char string5[8] = "text";
char string6[15] = "text";
//array of strings
char* stringArray[]={"String 1", "String 2", "String 3",
"String 4", "String 5", "String 6"};
Texts as String Objects
// string literal
String txtMsg = "Hello";
// converting a char to String
String txtMsg = String('a');
// converting a literal to String
String txtMsg = String("Text");
// concatenating two literals to String
String txtMsg = String("text1" + "text2");
Conditionals
Shortened Conditional
condition ? true : false;
IF Conditional
if (variable < 10)
{
// action A
}
if (variable < 10)
{
// action A
}
else
{
// action B
}
if (variable < 10)
{
// action A
}
else if (variable >= 100)
{
// action B
}
else
{
// action C
}
SWITCH / CASE OF Conditional
switch (variable) {
case 1:
// action A
break;
case 2:
// action B
break;
default:
// default case (optional)
}
Loops
FOR Loop
for (int i=0; i <= 100; i++){
// action
}
WHILE Loop
variable = 0;
while(variable < 100){
// action
variable++;
}
DO WHILE Loop
do
{
//action
variable++;
} while (variable < 100);
Mathematical Functions
Range Functions
//returns minimum between a and b
min(a,b);
//returns maximum between a and b
max(a,b);
//returns absolute value of a
abs(a);
//returns x restricted to (a,b)
constrain(x, a, b);
//interpolates linearly y between x1,y1 x2,y2
map(x, x1, x2, y1, y2);
Exponentiation
//returns a^b (both float type)
pow(a,b);
//returns the square root of a
sqrt(a);
Random Numbers
//initializes the seed of the pseudo-random number generator
randomSeed(seed);
//returns a random number between a and b (both long type)
random(a, b);
Trigonometry
//returns the sine of a (a float type and in radians)
sin(a);
//returns the cosine of a (a float type and in radians)
cos(a);
//returns the tangent of a (a float type and in radians)
tan(a);
Bit and Byte Functions
//returns the least significant byte of a word or variable.
lowByte(variable);
//returns the most significant byte of a word
//(or the second least significant byte in larger variables)
highByte(variable);
//returns the nth bit of a variable x
//(with bit 0 being the least significant)
bitRead(x, n);
//writes the nth bit of variable x with value b
//(with bit 0 being the least significant)
bitWrite(x, n,b );
//sets the nth bit of variable x to 1
bitSet(x, n);
//sets the nth bit of variable x to 0
bitClear(x, n);
//gets the value of the nth bit (same as 2^n)
bit(n);
Text Functions
//returns the character at position 3 (same as txtMsg[3];)
txtMsg.charAt(3);
//replaces the character at position 3 with "A" (same as txtMsg[3]="A";)
txtMsg.setCharAt("A", 3);
//concatenates text 1 and text 2 (same as text1=text1+text2;)
text1.concat("text2");
//returns the length of the string
txtMsg.length();
//returns the string converted to lowercase
txtMsg.toLowerCase();
//returns the string converted to uppercase
txtMsg.toUpperCase();
//removes spaces and incorrect characters
txtMsg.trim();
//returns the text string as an integer
txtMsg.toInt();
Comparison
//compares two strings. Returns 1 if text1 is greater than text2,
//0 if they are equal, and -1 otherwise
text1.compareTo(text2);
//compares if two strings are equal (same as text1==text2)
text1.equals(text2);
//compares if two strings are equal, ignoring case
text1.equalsIgnoreCase(text2);
Substrings
//returns a substring from position 3 to 10
txtMsg.substring(3, 10);
//checks if the string starts with "text", with offset 3
txtMsg.startsWith("text", 3);
//checks if the string ends with "text"
txtMsg.endsWith("text");
Search and Replace
//returns the index of the first occurrence of 'A',
//starting from the offset position
txtMsg.indexOf('A', offset);
//returns the index of the last occurrence of 'A'
//before the offset position
txtMsg.lastIndexOf('A', offset);
//replaces occurrences of "text1" with "text2"
txtMsg.replace("text1", "text2");
User Functions
Global Variables
int option=1;
int change(){
option=4;
}
void setup(){
Serial.begin(9600);
}
void loop(){
change();
Serial.print(option); //shows 4
delay(10000);
}
Passing Parameters by Value
int change(var){
var=4;
}
void setup(){
Serial.begin(9600);
}
void loop(){
int option=1;
change(option);
Serial.print(option); //shows 1
delay(10000);
}
Passing Parameters by Reference
int change(int &var){
var=4;
}
void setup(){
Serial.begin(9600);
}
void loop(){
int option=1;
change(option);
Serial.print(option); //shows 4
delay(10000);
}
Passing Parameters by Pointer
int change(int* var){
*var=4;
}
void setup(){
Serial.begin(9600);
}
void loop(){
int option=1;
change(&option);
Serial.print(option); //shows 4
delay(10000);
}
Returning Values
int change(){
int var=4;
return var;
}
void setup(){
Serial.begin(9600);
}
void loop(){
int option=1;
option=change();
Serial.print(option); //shows 4
delay(10000);
}
Advanced Data Types (Enum / Struct / Typedef)
Enumerations
//declaration
enum myEnumeration {
option1,
option2,
option3
};
//example of usage
myEnumeration variable = option2;
if (variable==option2){
//action
}
Structures
//declaration
struct myStructure
{
int field1;
int field2;
char field3;
};
//example of usage
struct myStructure variable;
variable.field1=10;
Definition of User Data Types
//declarations
typedef int newtype;
typedef enum myEnumeration newtype;
typedef struct myStructure newtype;
//example of usage
newtype variable;
Classes
Example of Class Usage
class MyRobot;
//definition of example class
class MyRobot
{
public:
void greet(); //displays "Hello"
void incCont(); //increments counter
int getCont(); //returns counter
void sayCont(); //displays counter value
void setCont(int); //initializes counter to a value
private:
int cont=0; //private counter variable
};
//displays "Hello"
void MyRobot::greet(){
Serial.println("Hello");
}
void MyRobot::incCont(){
this->cont++;
}
//returns counter
int MyRobot::getCont(){
return this->cont;
}
//displays counter value
void MyRobot::sayCont(){
Serial.println(this->cont);
}
//initializes counter to a value
void MyRobot::setCont(int _cont){
this->cont=_cont;
}
MyRobot robot;
void setup(){
Serial.println("Starting");
Serial.begin(9600);
robot.greet(); //shows hello
}
void loop(){
robot.incCont(); //increments the counter
robot.sayCont(); //displays the value
delay(1000);
}
EEPROM
// EEPROM (non-volatile memory)
EEPROM.write(address, value); // Write
byte val = EEPROM.read(address); // Read
Useful Libraries
#include <Wire.h> // I2C Communication
#include <SPI.h> // SPI Communication
#include <Servo.h> // Servo Motor Control
#include <Stepper.h> // Stepper Motor Control
#include <LiquidCrystal.h> // LCD Screen Control
#include <WiFi.h> // WiFi Connection
#include <Ethernet.h> // Ethernet Connection
#include <SoftwareSerial.h> // Software Serial Communication
#include <SD.h> // Reading and writing to SD cards