You are on page 1of 20

Arduino

IDE
Arduino IDE
• The Arduino Integrated Development Environment - or Arduino Software (IDE) -
contains a text editor for writing code, a message area, a text console, a toolbar with
buttons for common functions and a series of menus. It connects to the Arduino
hardware to upload programs and communicate with them.
• Decision making structures require
that the programmer specify one or
more conditions to be evaluated or
tested by the program. It should be
along with a statement or
statements to be executed if the
condition is determined to be true,
and optionally, other statements
to be executed if the condition
is determined to be false.
Form 1

A. If Statement if (expression)

   statement;

It takes an Form 2 

expression in if (expression) {

parenthesis and a    Block of statements;

statement or block of }

statements. If /* Global variable definition */

the expression is true int A = 5 ;

then the statement


int B = 9 ;

Example:
or block of
statements gets Void setup () {
executed otherwise
these statements are }

skipped.
Void loop () {

   /* check the boolean condition */


if (expression) {

   Block of statements;

B. If else Statement else {

   Block of statements;

An if statement can }

be followed by an
optional else Example:

statement, which /* Global variable definition */

executes when the int A = 5 ;

expression is false. int B = 9 ;

Void setup () {

Void loop () {
switch (variable) {

   case label:

   // statements

   break;

C. Switch Statement }

Similar to the if case label: {

statements, switch...case    // statements

 controls the flow of    break;


programs by allowing }
the programmers to
specify different codes default: {
that should be executed    // statements
in various conditions.    break;

Example: 
expression1 ? expression2 : expression3

D. Conditional         
 operator

The conditional operator


? : is the only ternary
operator in C. /* Find max(a, b): */

max = ( a > b ) ? a : b;

/* Convert small letter to capital: */

/* (no parentheses are actually necessary) */

c = ( c >= 'a' && c <= 'z' ) ? ( c - 32 ) : c;


Loop Statement
• A program loop is a series of statements that executes for a specified
number of repetitions or until specified conditions are met. Use the WHILE
clause to indicate that the loop should execute repeatedly as long as the WHILE
expression evaluates to true (1).
• A. while
A while loop will loop
continuously, and infinitely, Syntax
until the expression inside the
parenthesis, () becomes false. while (condition) {

Something must change the   // statement(s)


tested variable, or the while
loop will never exit. }

This could be in your code, Example Code


such as an incremented
variable, or an var = 0;

external condition, such as while (var < 200) {


testing a sensor.
  // do something repetitive 200 times

  var++;

}
Syntax
B. do...while do {

  // statement block
The do… while loop works
in the same manner as } while (condition);

the while loop, with the Example Code


exception that the condition is
tested at the end of the loop, int x = 0;
so the do loop will always run do {
at least once.
  delay(50);          // wait for sensors to stabilize

  x = readSensors();  // check the sensors

} while (x < 100);


Syntax
C. for for (initialization; condition; increment) {
  // statement(s);
}
The for statement is used
to repeat a block of
statements enclosed in curly
Example Code
braces. An increment counter is // Dim an LED using a PWM pin
usually used to increment int PWMpin = 10;  // LED in series with 470 ohm
and terminate the resistor on pin 10
loop. The for statement is
useful for any repetitive void setup() {
operation, and is often used   // no setup needed
in combination with arrays }
to operate on collections
of data/pins. void loop() {
  for (int i = 0; i <= 255; i++) {
    analogWrite(PWMpin, i);
    delay(10);
  }
}
Functions
The Arduino hardware and software was designed for artists, designers, hobbyists,
hackers, newbies, and anyone interested in creating interactive objects or
environments. Arduino can interact with buttons, LEDs, motors, speakers, GPS units,
cameras, the internet, and even your smart-phone or your TV!
• (1) & (2) Power (USB / Barrel Jack) Every Arduino board needs a way to be
connected to a power source. The Arduino UNO can be powered from a USB cable
coming from your computer or a wall power supply (like this) that is terminated in
a barrel jack. In the picture above the USB connection is labeled (1) and the barrel
jack is labeled (2).

• GND (3): Short for ‘Ground’. There are several GND pins on the Arduino, any of
which can be used to ground your circuit.

• 5V (4) & 3.3V (5): As you might guess, the 5V pin supplies 5 volts of power, and
the 3.3V pin supplies 3.3 volts of power. Most of the simple components used with
the Arduino run happily off of 5 or 3.3 volts.

• Analog (6): The area of pins under the ‘Analog In’ label (A0 through A5 on the
UNO) are Analog In pins. These pins can read the signal from an analog sensor
(like a temperature sensor ) and convert it into a digital value that we can read.

• Digital (7): Across from the analog pins are the digital pins (0 through 13 on the
UNO). These pins can be used for both digital input (like telling if a button is
pushed) and digital output (like powering an LED).

• PWM (8): You may have noticed the tilde (~) next to some of the digital pins (3, 5,
6, 9, 10, and 11 on the UNO). These pins act as normal digital pins, but can also
be used for something called Pulse-Width Modulation (PWM). We have a tutorial
on PWM, but for now, think of these pins as being able to simulate analog output
(like fading an LED in and out).

• AREF (9): Stands for Analog Reference. Most of the time you can leave this pin
alone. It is sometimes used to set an external reference voltage (between 0 and 5
Volts) as the upper limit for the analog input pins.
(10) Reset Button
Just like the original Nintendo, the Arduino has a reset button (10). Pushing it will temporarily connect the reset
pin to ground and restart any code that is loaded on the Arduino. This can be very useful if your code doesn’t
repeat, but you want to test it multiple times. Unlike the original Nintendo however, blowing on the Arduino
doesn't usually fix any problems.

(11) Power LED Indicator


Just beneath and to the right of the word “UNO” on your circuit board, there’s a tiny LED next to the word
‘ON’ (11). This LED should light up whenever you plug your Arduino into a power source. If this light doesn’t turn
on, there’s a good chance something is wrong. Time to re-check your circuit!

(12) TX RX LEDs
TX is short for transmit, RX is short for receive. These markings appear quite a bit in electronics to indicate the
pins responsible for serial communication. In our case, there are two places on the Arduino UNO where TX and RX
appear -- once by digital pins 0 and 1, and a second time next to the TX and RX indicator LEDs  (12). These LEDs
will give us some nice visual indications whenever our Arduino is receiving or transmitting data (like when we’re
loading a new program onto the board).

(13) Main IC
The black thing with all the metal legs is an IC, or Integrated Circuit  (13). Think of it as the brains of our Arduino.
The main IC on the Arduino is slightly different from board type to board type, but is usually from the ATmega line
of IC’s from the ATMEL company. This can be important, as you may need to know the IC type (along with your
board type) before loading up a new program from the Arduino software. This information can usually be found in
writing on the top side of the IC. If you want to know more about the difference between various IC's, reading the
datasheets is often a good idea.

(14) Voltage Regulator


The voltage regulator (14) is not actually something you can (or should) interact with on the Arduino. But it is
potentially useful to know that it is there and what it’s for. The voltage regulator does exactly what it says -- it
controls the amount of voltage that is let into the Arduino board. Think of it as a kind of gatekeeper; it will turn
away an extra voltage that might harm the circuit. Of course, it has its limits, so don’t hook up your Arduino to
anything greater than 20 volts.
Strings
Text strings can be represented in two ways. you can use the String data type, which is part of the core
as of version 0019, or you can make a string out of an array of type char and null-terminate it. This
page described the latter method. For more details on the String object, which gives you more functionality at
the cost of more memory, see the string object page.

Possibilities for declaring strings

• Declare an array of chars without initializing it as in Str1

• Declare an array of chars (with one extra char) and the compiler will add the required null character, as in Str2

• Explicitly add the null character, Str3

• Initialize with a string constant in quotation marks; the compiler will size the array to fit the string constant and
a terminating null character, Str4

• Initialize the array with an explicit size and string constant, Str5

• Initialize the array, leaving extra space for a larger string, Str6
Null termination

Generally, strings are terminated with a null character (ASCII code 0). This allows functions (like Serial.print()) to tell where the end
of a string is. Otherwise, they would continue reading subsequent bytes of memory that aren’t actually part of the string.

This means that your string needs to have space for one more character than the text you want it to contain. That is why Str2 and Str5 need
to be eight characters, even though "arduino" is only seven - the last position is automatically filled with a null character. Str4 will be
automatically sized to eight characters, one for the extra null. In Str3, we’ve explicitly included the null character (written '\0') ourselves.

Note that it’s possible to have a string without a final null character (e.g. if you had specified the length of Str2 as seven instead of eight).
This will break most functions that use strings, so you shouldn’t do it intentionally. If you notice something behaving strangely
(operating on characters not in the string), however, this could be the problem.

Arrays of strings

It is often convenient, when working with large amounts of text, such as a project with an LCD display, to setup an array of strings.
Because strings themselves are arrays, this is actually an example of a two-dimensional array.
In the code below, the asterisk after the datatype char “char*” indicates that this is an array of “pointers”. All array names are actually
pointers, so this is required to make an array of arrays. Pointers are one of the more esoteric parts of C++ for beginners to understand, but
it isn’t necessary to understand pointers in detail to use them effectively here.

Single quotes or double quotes?

Strings are always defined inside double quotes ("Abc") and characters are always defined inside single quotes('A').
Strings

Syntax

char Str1[15];
char Str2[8] = {'a', 'r', 'd', 'u', 'i', 'n', 'o'};
char Str3[8] = {'a', 'r', 'd', 'u', 'i', 'n', 'o', '\0'};
char Str4[] = "arduino";
char Str5[8] = "arduino";
char Str6[15] = "arduino";

Example Code

char *myStrings[] = {"This is string 1", "This is string 2", "This is string 3",
                     "This is string 4", "This is string 5", "This is string 6"
                    };

void setup() {
  Serial.begin(9600);
}

void loop() {
  for (int i = 0; i < 6; i++) {
    Serial.println(myStrings[i]);
    delay(500);
  }
}
Arrays
Creating (Declaring) an Array

All of the methods below are valid ways to create (declare) an array.

 int myInts[6];

  int myPins[] = {2, 4, 8, 3, 6};

  int mySensVals[5] = {2, 4, -8, 3, 2};

  char message[6] = "hello";

You can declare an array without initializing it as in myInts.


In myPins we declare an array without explicitly choosing a size. The compiler counts the elements and creates an array of the appropriate size.
Finally you can both initialize and size your array, as in mySensVals. Note that when declaring an array of type char, one more element than your
initialization is required, to hold the required null character.
Arrays

Accessing an Array
Arrays are zero indexed, that is, referring to the array initialization above, the first element of the array is at index 0, hence

mySensVals[0] == 2, mySensVals[1] == 4, and so forth.

It also means that in an array with ten elements, index nine is the last element. Hence:

int myArray[10]={9, 3, 2, 4, 3, 2, 7, 8, 9, 11};

// myArray[9]    contains 11

// myArray[10]   is invalid and contains random information (other memory address)

For this reason you should be careful in accessing arrays. Accessing past the end of an array (using an index number greater than your declared array size - 1) is
reading from memory that is in use for other purposes. Reading from these locations is probably not going to do much except yield invalid data. Writing to
random memory locations is definitely a bad idea and can often lead to unhappy results such as crashes or program malfunction. This can also be a difficult
bug to track down.

Unlike BASIC or JAVA, the C++ compiler does no checking to see if array access is within legal bounds of the array size that you have declared.
Arrays

To assign a value to an array:

mySensVals[0] = 10;

To retrieve a value from an array:

x = mySensVals[4];

Arrays and FOR Loops

Arrays are often manipulated inside for loops, where the loop counter is used as the index for each array element. For
example, to print the elements of an array over the serial port, you could do something like this:

for (byte i = 0; i < 5; i = i + 1) {

  Serial.println(myPins[i]);

You might also like