The Basics
- Statements are grouped together by curly brackets { }, not by indentation (as in Python).
- You can put newlines and spaces where you like, but your code will be easier to read if you indent it (like Python).
- Everything between // and the end of the line, or between /* and */ is a comment.
- All variables must be declared, defining their type. They have no meaning outside the smallest enclosing { }. Declarations must be the first things after {.
- All statements (including declarations) must be terminated by a semicolon.
- Lines beginning with # are definitions of constants or directives to include a file from somewhere else containing stuff you'll be needing.
Declarations
int a, b, c; // Declare 3 integers
float x; // Declare a floating point variable (needn't be a whole number)
boolean love_marmite; // Takes the values true or false
char c; // this variable holds a single character
int blindmouse[3]; // declares blindmouse[0], blindmouse[1] and blindmouse[2]
Statements
See the Arduino Reference (under Help in the Arduino IDE) for a list of operators.
Assignment
x = (a + b) / c;
Conditional
if ( a == 0 ) then { ….}
if (x >= 0 && x < 10} then { …. } else { …. }
Loop
while ( sum < max ) do { …. }
for (i=0; i<10; i++) { ….} // The same as i = 0; while (i < 10) { ….; i = i+1; }
break; // Exit immediately from the smallest surrounding loop
continue; // Go back to the top of the smallest surrounding loop and start the next time round.
Functions
- A function has a type, but if it just does a job and doesn't return anything the type is void.
- We have to declare the type of the parameters (length and breadth), to which are assigned the values given in the function call.
- See the Arduino Reference for standard functions you can use.
float area(float length, float breadth) {
return length * breadth;
}
roomsize = area(6, 9);