Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 16 Next »

Note : If you are an absolute beginner to programming, it is a good idea to use the code+blocks programming option in Tinkercad, and copy over the generated C++ code to Arduino IDE.

Comments

  • Comments are for you – the programmer or any other human who might read your code
  • Comments are not run on the Arduino board
C++Blocks
/*
   multi-line
   comment
*/
// single line comment





Statements

  • Statements are compiled into an ‘executable’ of 1s and 0s, which are run on the Arduino.
  • Statements end with a ;
C++Blocks
c = a+b; // c is assigned the sum of a, b



Variables

  • Variables are containers to store intermediate data
  • In C language, a variable needs to have a type, which specifies the nature and the size of data it holds
  • Some of the standard data types are
  • int : 16-bit integers in the range -32,768 to 32,767
  • unsigned int : 16-bit positive integers (incl 0), 0 to 65535
  • char : 8-bit integers from -128 to 127. Characters such as ‘0’, ‘A’, ‘a’ etc. are represented using ASCII (48, 65, 97 respectively - read up more!). BYTE is the same as unsigned char
  • float : for floating point numbers such as 2.25, -5.875 (32-bits)
  • Types can also be user defined (through classes)
  • Variables can be declared with or without initialization
C++Blocks
int a; // declaration

int a = 0; // declaration and initialization

Note: Creating a variable in Blocks declares it and initializes it to 0

A variable appearing on the left-hand side of an assignment statement assigns a value to it.

C++Blocks
a = 10; // assigning 10 to a

A variable value is used when it appears in a comparison or on the right-hand side of an expression/assignment.

C++Blocks
(a == 1) // checking if a is equal to 1

The comparison above returns a 'true' or 'false', which is usually used for selection or iteration. Read up more about comparison operators!

Important : In C++, '==' is a comparison operator, '=' is the assignment operator. Using one instead of the other will not cause a syntax error, but will cause incorrect program functionality.

C++Blocks
b = a + 10; // variable b is assigned the value of variable a plus 10.

Selection

  • A program that executes all the statements in a sequence is probably not very interesting.
  • Sometimes, a part of a program must be executed based on a certain condition (selection).
  • Given below is an example of an if-else statement. The {} is optional if there is only one line being executed conditionally for if or else.
C++Blocks
if(a>0){
    c = a+b;
//executed when a>0
}
 
else{
    c = a-b;
//executed when a<0 or a==0
}

To Do : Read up about switch-case

Iteration

  • Sometimes, a part of a program must be executed repeatedly until a certain condition is satisfied (iteration / loop)
  • Given below is an example for an while loop.
C++Blocks
while(a>0){
    a = a-b;
/* executed over and over until a<0 or a==0 */
}

To Do : Read up about for loop, do-while loop

Functions

  • A function is a segment of code which can be invoked from different parts of the program in a parameterized manner
  • A function involves 3 aspects
  • Declaration (typically done in header files with extension .h)
int add(int,int)
  • Definition (typically done by the library vendor)
int add(int x, int y){ // x, y are function 'parameters'
                        //of the function 'add’
  return x+y;
}
  • Usage (usually, we need to do only this)
{
  … //other statements
 
    c = add(a,b);
 
/* causes add() to be called with a, b passed as arguments.
    The value returned is assigned to c */
 
  … //other statements
}

Note : Blocks do not allow you to declare or define functions explicitly. However, some built-in functions such as digitalWrite() can be called using appropriate blocks, as shown below.

C++Blocks
{
  digitalWrite(11, HIGH);
}

Setup() and loop() functions

  • Setup and loop are functions called automatically (unlike all other functions needs to be called explicitly)
  • setup() is called once, when you release the reset button / plug in your Arduino / upload a new code onto the board
  • loop() is called repeatedly; anything inside the loop() gets executed over and over as long as the system remains powered on

Note : When using blocks, any setup code required is automatically inserted into setup(). The main program logic which implemented using blocks goes into loop().

Good Coding Styles / Practices

Good code is code which is readable, comprehensible, and extensible. If you can't read/comprehend, you can't debug the code, you can't improve the code, you can't collaborate in a team. Hence the importance of following good coding styles/practices.

  • Write detailed comments. This will be very useful later for you yourself or other people who read your code.
  • Use descriptive variable names for variable etc. rather than short, generic names like i, j, k. This will help your code more readable and comprehensible.
  • Indent your code properly. Indent with tabs, not with spaces. This also makes your code easier to read.
  • Use constants/variables for values that appear at multiple places rather than hard-coding values.
Poor Coding Style
void setup(){
    //setup code
}
void loop()
       {                // Poor position for opening brace.
    int j = 100;        // Non-descriptive variable name
  analogWrite(5, j);    /*  Indented with spaces, and not aligned with the previous line.
                            Hard-coded values.
                            No comment to indicate what the line does.*/
                }       // Poor position for closing brace.
Good Coding Style
const int leftMotor = 5; // pin 5 used to control left motor of the robot
void setup(){
    //setup code
}
void loop(){
    int leftMotorSpeed = 100;
    analogWrite(leftMotor, leftMotorSpeed); // to write the analog value 100 to pin 5.
}
  • No labels