Arduino Tutorials

I have been learning how to use an Arduino Uno with the Elegoo Uno R3 Most Complete Starter Kit and following Paul McWhorters new Arduino Tutorials on YouTube as a primary source.

If you are purchasing the Elegoo Kit, please do so from Paul's video description to support his work. The datasheet for each component in the kit is available here. Note, rename the downloaded zip file something short otherwise the path will be too long to extract:

For physical hardware you will also need to install the Arduino IDE and drivers:

While following along with these I have been putting physical circuits together using hardware however I have also been putting emulated circuits together using TinkerCad.

These are a collection of my notes and Tinkercad emulations while taking the course.

I also completed Abdul Bari Udemy C++ Course to familiarise myself with the C++ programming language before diving into the tutorials.

Another useful Udemy course is Dr Peter Dalmaris Arduino Step by Step getting started.

Table of contents

  1. Tutorial 01: The Arduino Blink Test Sketch
    1. Tutorial 02 and 03: Arduino and Breadboard
      1. LED
        1. Resistor
        2. Tutorial 04: Variables and Functions in Arduino Sketches
          1. Tutorial 05: Numbering Systems and DataTypes used in Computer Science
            1. Decimal Characters 0,1,2,3,4,5,6,7,8,9
              1. Binary Characters 0,1
                1. Hexadecimal Characters 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F
                  1. byte and kilobyte
                    1. char
                      1. string
                        1. float
                        2. Tutorial 06: Arduino and LED Binary Counter
                          1. Tutorial 07 and 08: Arduino digitalWrite, analogWrite and ~Pulse Width Modulation
                            1. Tutorial 09: Arduino and Ohms Law
                              1. Tutorial 10: Arduino analogRead
                                1. Tutorial 11: Arduino Serial port class
                                  1. Tutorial 12: Arduino and Potentiometer
                                    1. Tutorial 13: Code Blocks
                                      1. functions
                                        1. if, else
                                          1. switch case
                                          2. Tutorial 14: Arduino Dimmable LED Project
                                            1. Tutorial 15-16: For Loops
                                              1. Tutorial 17: While Loops
                                                1. Tutorial 18: Reading Numbers from the Serial Monitor
                                                  1. Tutorial 19: Reading Strings from the Serial Monitor
                                                    1. Tutorial 20: Arduino and RBG LED
                                                      1. Tutorial 21: Arduino and RBG LED Color Mixing
                                                        1. Tutorial 22-23: Arduino and an Active Buzzer (Piezo)
                                                          1. Tutorial 24: Arduino and a Passive Buzzer (Piezo)
                                                            1. Tutorial 25-26: Arduino and PhotoResistor
                                                              1. Tutorial 27: Arduino and Pushbuttons and Pull Up or Pull Down Resistors
                                                                1. Tutorial 28: Arduino and Push Button Toggle Switch
                                                                  1. Tutorial 29: Using Push Buttons to Create a Dimmable LED
                                                                    1. Tutorial 30-31: Arduino and Servo
                                                                      1. Tutorial 32-33: Joysticks
                                                                        1. Tutorial 34: Arduino AnalogWrite of INPUT Pins
                                                                          1. Tutorial 35: Arduino and Stepper Motor
                                                                            1. Tutorial 36: Tilt Switch
                                                                              1. Tutorial 37: Arduino, L293D Motor Driver and DC Motor
                                                                                1. Tutorial 38: Using a Tilt Switch to Cut Off a DC Motor
                                                                                  1. Tutorial 39: Using a Joystick to Control a DC Motor
                                                                                    1. Tutorial 40: Controlling DC Motor Speed and Direction with Push Buttons
                                                                                      1. Tutorial 41: Binary and Hexadecimal Revisited
                                                                                        1. Tutorial 42-47: Arduino and a 74HC595 Parallel Shift Register
                                                                                          1. Tutorial 48-49: Arduino and LCD Display
                                                                                            1. Tutorial 50-52: DHT11 Temperature and Humidity Sensor
                                                                                              1. Tutorial 53-55: Arduino and HC-SR04 Ultrasonic Sensor
                                                                                                1. Tutorial 56-57: The Arduino Serial Monitor

                                                                                                  The Arduino has a test LED which is internally attached to Pin 13 and ground.

                                                                                                  We can test communication with the Arduino with an Arduino sketch. The Arduino sketch has a setup function which we run once for example to configure pins and a loop function which runs repeatedly:

                                                                                                  void setup()
                                                                                                  {
                                                                                                    // put your setup code here, to run once:
                                                                                                    pinMode(13, OUTPUT);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    // put your main code here, to run repeatedly:
                                                                                                    digitalWrite(13, HIGH);
                                                                                                  }

                                                                                                  In this case we use the inbuilt function pinMode to configure pin 13 as an OUTPUT. An LED is an output device that converts electricity into light. Then we set the voltage to HIGH using the digitalWrite inbuilt function. When the voltage is HIGH, the pin will output 5 V (or just slightly less). This can be seen by attaching a multimeter to the Arduino:

                                                                                                  When the voltage is instead set to LOW the reading on the multimeter is instead 0 V:

                                                                                                  void setup()
                                                                                                  {
                                                                                                    // put your setup code here, to run once:
                                                                                                    pinMode(13, OUTPUT);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    // put your main code here, to run repeatedly:
                                                                                                    digitalWrite(13, LOW);
                                                                                                  }

                                                                                                  We can now blink the LED on and off using a delay time of 1000 ms = 1 s within the loop:

                                                                                                  void setup()
                                                                                                  {
                                                                                                    // put your setup code here, to run once:
                                                                                                    pinMode(13, OUTPUT);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    // put your main code here, to run repeatedly:
                                                                                                    digitalWrite(13, HIGH);
                                                                                                    delay(1000); 
                                                                                                    digitalWrite(13, LOW);
                                                                                                    delay(1000); 
                                                                                                  }

                                                                                                  This is emulated using Tinkercad here:

                                                                                                  Tutorial 02 and 03: Arduino and Breadboard

                                                                                                  The breadboard looks like the following. There are four sections:

                                                                                                  Starting from the bottom section. A + rail and a – rail are indicated. All the pins in these rails are horizontally connected:

                                                                                                  A 5V and a GND Rail can be made by wiring up the + Rail to the 5 V pin of the Arduino and – Rail to the GND pin of the Arduino respectively:

                                                                                                  Next there is the bottom middle section with columns (1, 2, 3, …). Each column has 5 rows pins (a,b,c,d and e) which are internally connected. However each column is separate:

                                                                                                  The upper middle section once again has columns (1, 2, 3, …). This time each column has 5 rows pins (f,g,h,i and j) which are internally connected. Once again each column is separate. In addition the column above the middle divide is not connected to the column below the middle divide. i.e. (a,b,c,d,e) are not connected to (f,g,h,i,j).

                                                                                                  Finally in the top section another + rail and a – rail are indicated. All the pins in these rails are horizontally connected:

                                                                                                  Connecting a wire (or component) between 2 pins in separate columns will connect the two columns internally. For example 2 parallel rows:

                                                                                                  Or adjacent columns:

                                                                                                  LED

                                                                                                  LEDs are unipolar devices and only work when connected in the correct orientation.

                                                                                                  An LED has 2 legs. The longer Leg is the Anode and the shorter leg is the Cathode.

                                                                                                  The Anode should be connected to the positive side of the power supply and the shorter leg is the Cathode and should be connected to the negative side of the power supply. Lets illustrate this with a coin cell battery. Notice the LED only illuminates when the polarity is correct:

                                                                                                  Next we can connect an LED to the breadboard and then make a connection from the 5V pin of the Arduino to the Anode:

                                                                                                  And then the Cathode to one of the GND pins of the Arduino:

                                                                                                  This will complete the circuit however too high a current will run through the LED and the LED will burn out:

                                                                                                  Resistor

                                                                                                  To prevent this we must limit the current using a resistor. To understand this concept, conceptualise electricity as a series of positive particles which fall from the +5 V power supply to ground. In order to fall, a pathway between +5 V and ground must be made available. We can conceptualise a wire as a pipe between +5 V and the ground (left). In this diagram, the current can be visualised as the rate of particles falling i.e. 3. A resistor can be thought of as a constricted wire. A low value resistor (middle) will constrict the pipe slightly limiting the rate of particles (current) to 2. A higher value resistor will constrict the pipe more, limiting the rate of particles (current) to 1.

                                                                                                  To limit the current flowing through the LED to 15 mA we can use a 330 R resistor. Recall that:

                                                                                                  The current limiting resistor should be connected to the 5V power supply before the LED. Now the LED illuminates as expected:

                                                                                                  Recall that:

                                                                                                  And therefore as the value of resistor increases, the more restriction on the current. Resistors are labelled using coloured bands. For example a 10 R, 100 R, 220 R, 330 R, 1 K (1000 R), 2 K (2000 R), 5K1 (5100 R), 10 K (10000 R) 100 K (100000 R) and 1 M (1000000 R) resistor:

                                                                                                  However it is more routine to check their values using a multimeter with crocodile clips:

                                                                                                  Instead of using the 5 V pin on the Arduino (which is always 5 Volts), we can instead use a Digital Pin on the Arduino for example Pin 13 which we can control using the inbuilt digitalWrite function. We can assign the pin to LOW (0 V) or HIGH (5 V) respectively. We can control the LED using a sketch similar to the blink sketch before:

                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(13, OUTPUT);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    digitalWrite(13, HIGH);
                                                                                                    delay(500); 
                                                                                                    digitalWrite(13, LOW);
                                                                                                    delay(500); 
                                                                                                  }

                                                                                                  Tutorial 04: Variables and Functions in Arduino Sketches

                                                                                                  This tutorial uses the same circuit as above. However an Arduino sketch is used to create a Morse Code S.O.S where an S is presenting by 3 dots . . . and an O is represented by 3 – – -. The sketch below uses a duration of 50 ms for a dot, a duration of 500 ms for a dash and a period of 10000 ms to end the message:

                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(13, OUTPUT);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    //More Code
                                                                                                    // S: . . .
                                                                                                    // O: - - -
                                                                                                    // S: . . .
                                                                                                    
                                                                                                    // S . . .
                                                                                                    digitalWrite(13, HIGH);
                                                                                                    delay(50); 
                                                                                                    digitalWrite(13, LOW);
                                                                                                    delay(50);
                                                                                                    
                                                                                                    digitalWrite(13, HIGH);
                                                                                                    delay(50); 
                                                                                                    digitalWrite(13, LOW);
                                                                                                    delay(50);
                                                                                                    
                                                                                                    digitalWrite(13, HIGH);
                                                                                                    delay(50); 
                                                                                                    digitalWrite(13, LOW);
                                                                                                    delay(50); 
                                                                                                    
                                                                                                    // O: - - -
                                                                                                    digitalWrite(13, HIGH);
                                                                                                    delay(500); 
                                                                                                    digitalWrite(13, LOW);
                                                                                                    delay(500);
                                                                                                    
                                                                                                    digitalWrite(13, HIGH);
                                                                                                    delay(500); 
                                                                                                    digitalWrite(13, LOW);
                                                                                                    delay(500);
                                                                                                    
                                                                                                    digitalWrite(13, HIGH);
                                                                                                    delay(500); 
                                                                                                    digitalWrite(13, LOW);
                                                                                                    delay(500); 
                                                                                                    
                                                                                                    // S . . .
                                                                                                    digitalWrite(13, HIGH);
                                                                                                    delay(50); 
                                                                                                    digitalWrite(13, LOW);
                                                                                                    delay(50);
                                                                                                    
                                                                                                    digitalWrite(13, HIGH);
                                                                                                    delay(50); 
                                                                                                    digitalWrite(13, LOW);
                                                                                                    delay(50);
                                                                                                    
                                                                                                    digitalWrite(13, HIGH);
                                                                                                    delay(50); 
                                                                                                    digitalWrite(13, LOW);
                                                                                                    delay(50); 
                                                                                                    
                                                                                                    // End
                                                                                                    delay(10000);
                                                                                                  }

                                                                                                  The code above has numerous problems. First the dot is too short for our eyes to easily register the message. Secondly everything is hard coded as a number. The duration for the dot is used 12 times, the duration for the dash is used 6 times and the pin of the LED is used 19 times. It becomes tedious to change these when experimenting with our sketch and easy to forget one of the times to make the changes. To make our life easier we can instead assign these numbers to variables at the top of the Arduino sketch and then refer to these variables within the variable sketch:

                                                                                                  int redPin = 13;
                                                                                                  int dotT = 100;
                                                                                                  int dashT = 500;
                                                                                                  int endT = 10000;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(redPin, OUTPUT);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    //More Code
                                                                                                    // S: . . .
                                                                                                    // O: - - -
                                                                                                    // S: . . .
                                                                                                    
                                                                                                    // S . . .
                                                                                                    digitalWrite(redPin, HIGH);
                                                                                                    delay(dotT); 
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    delay(dotT);
                                                                                                    
                                                                                                    digitalWrite(redPin, HIGH);
                                                                                                    delay(dotT); 
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    delay(dotT);
                                                                                                    
                                                                                                    digitalWrite(redPin, HIGH);
                                                                                                    delay(dotT); 
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    delay(dotT); 
                                                                                                    
                                                                                                    // O: - - -
                                                                                                    digitalWrite(redPin, HIGH);
                                                                                                    delay(dashT); 
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    delay(dashT);
                                                                                                    
                                                                                                    digitalWrite(redPin, HIGH);
                                                                                                    delay(dashT); 
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    delay(dashT);
                                                                                                    
                                                                                                    digitalWrite(redPin, HIGH);
                                                                                                    delay(dashT); 
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    delay(dashT); 
                                                                                                    
                                                                                                    // S . . .
                                                                                                    digitalWrite(redPin, HIGH);
                                                                                                    delay(dotT); 
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    delay(dotT);
                                                                                                    
                                                                                                    digitalWrite(redPin, HIGH);
                                                                                                    delay(dotT); 
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    delay(dotT);
                                                                                                    
                                                                                                    digitalWrite(redPin, HIGH);
                                                                                                    delay(dotT); 
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    delay(dotT); 
                                                                                                    
                                                                                                    // End
                                                                                                    delay(endT);
                                                                                                  }

                                                                                                  There are still some issues. There is not a space between each character and a lot of repetition in the code… It is also very difficult to alter the message and we would need to look up the Morse code value for every letter and then hard code it.

                                                                                                  These issues can be addressed by creating our own functions. Functions have the form

                                                                                                  returnType functionName(input_arguments)
                                                                                                  {
                                                                                                      code block belonging to function
                                                                                                  }

                                                                                                  Some functions interact with the Arduino hardware and do not have a return type. When a function has no return type it must be declared as the type void. If functions do not have input arguments the parenthesis must still be included:

                                                                                                  void functionName()
                                                                                                  {
                                                                                                      code block belonging to function
                                                                                                  }

                                                                                                  Each statement in the code block must end in a semi-colon ;

                                                                                                  We can create the functions blankSpace, dash and dot. These functions call a series of statements using the inbuilt functions digitalWrite and delay respectively. These functions have input arguments which must be supplied:

                                                                                                  void blankSpace()
                                                                                                  {
                                                                                                    delay(spaceT);
                                                                                                  }
                                                                                                  
                                                                                                  void dash()
                                                                                                  {
                                                                                                    digitalWrite(redPin, HIGH);
                                                                                                    delay(dashT); 
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    delay(dashT);
                                                                                                  }
                                                                                                  
                                                                                                  void dot()
                                                                                                  {
                                                                                                    digitalWrite(redPin, HIGH);
                                                                                                    delay(dotT); 
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    delay(dotT);
                                                                                                  }
                                                                                                  
                                                                                                  void endSpace()
                                                                                                  {
                                                                                                    delay(endT);
                                                                                                  }

                                                                                                  Each letter consists of a sequence of dashes and dots followed by a blank space. We can create a function for each letter of the alphabet. These functions call a series of statements involving our dot, dash and blankSpace functions. As dot, dash and blankSpace are functions they must be called with parenthesis. These functions have no input arguments so there is nothing supplied between the parenthesis:

                                                                                                  void letterA()
                                                                                                  {
                                                                                                    // A: . -
                                                                                                    dot();
                                                                                                    dash();
                                                                                                    blankSpace();
                                                                                                  }
                                                                                                  
                                                                                                  void letterB()
                                                                                                  {
                                                                                                    // B: - . . .
                                                                                                    dash();
                                                                                                    dot();
                                                                                                    dot();
                                                                                                    dot();
                                                                                                    blankSpace();
                                                                                                  }
                                                                                                  
                                                                                                  void letterC()
                                                                                                  {
                                                                                                    // C: - . - .
                                                                                                    dash();
                                                                                                    dot();
                                                                                                    dash();
                                                                                                    dot();
                                                                                                    blankSpace();
                                                                                                  }
                                                                                                  
                                                                                                  void letterD()
                                                                                                  {
                                                                                                    // D: - . .
                                                                                                    dash();
                                                                                                    dot();
                                                                                                    dot();
                                                                                                    blankSpace();
                                                                                                  }
                                                                                                  
                                                                                                  void letterE()
                                                                                                  {
                                                                                                    // E: .
                                                                                                    dot();
                                                                                                    blankSpace();
                                                                                                  }
                                                                                                  
                                                                                                  void letterF()
                                                                                                  {
                                                                                                    // F: . . - .
                                                                                                    dot();
                                                                                                    dot();
                                                                                                    dash();
                                                                                                    dot();
                                                                                                    blankSpace();
                                                                                                  }
                                                                                                  
                                                                                                  void letterG()
                                                                                                  {
                                                                                                    // G: - - .
                                                                                                    dash();
                                                                                                    dash();
                                                                                                    dot();
                                                                                                    blankSpace();
                                                                                                  }
                                                                                                  
                                                                                                  void letterH()
                                                                                                  {
                                                                                                    // H: . . . .
                                                                                                    dot();
                                                                                                    dot();
                                                                                                    dot();
                                                                                                    dot();
                                                                                                    blankSpace();
                                                                                                  }
                                                                                                  
                                                                                                  void letterI()
                                                                                                  {
                                                                                                    // I: . .
                                                                                                    dot();
                                                                                                    dot();
                                                                                                    blankSpace();
                                                                                                  }
                                                                                                  
                                                                                                  void letterJ()
                                                                                                  {
                                                                                                    // J: . - - -
                                                                                                    dot();
                                                                                                    dash();
                                                                                                    dash();
                                                                                                    dash();
                                                                                                    blankSpace();
                                                                                                  }
                                                                                                  
                                                                                                  void letterK()
                                                                                                  {
                                                                                                    // K: - . -
                                                                                                    dash();
                                                                                                    dot();
                                                                                                    dash();
                                                                                                    blankSpace();
                                                                                                  }
                                                                                                  
                                                                                                  void letterL()
                                                                                                  {
                                                                                                    // L: . - . .
                                                                                                    dot();
                                                                                                    dash();
                                                                                                    dot();
                                                                                                    dot();
                                                                                                    blankSpace();
                                                                                                  }
                                                                                                  
                                                                                                  void letterM()
                                                                                                  {
                                                                                                    // M: - -
                                                                                                    dash();
                                                                                                    dash();
                                                                                                    blankSpace();
                                                                                                  }
                                                                                                  
                                                                                                  void letterN()
                                                                                                  {
                                                                                                    // N: - .
                                                                                                    dash();
                                                                                                    dot();
                                                                                                    blankSpace();
                                                                                                  }
                                                                                                  
                                                                                                  void letterO()
                                                                                                  {
                                                                                                    // O: - - -
                                                                                                    dash();
                                                                                                    dash();
                                                                                                    dash();
                                                                                                    blankSpace();
                                                                                                  }
                                                                                                  
                                                                                                  void letterP()
                                                                                                  {
                                                                                                    // P: . - - .
                                                                                                    dot();
                                                                                                    dash();
                                                                                                    dash();
                                                                                                    dot();
                                                                                                    blankSpace();
                                                                                                  }
                                                                                                  
                                                                                                  
                                                                                                  void letterQ()
                                                                                                  {
                                                                                                    // Q: - - . -
                                                                                                    dash();
                                                                                                    dash();
                                                                                                    dot();
                                                                                                    dash();
                                                                                                    blankSpace();
                                                                                                  }
                                                                                                  
                                                                                                  void letterR()
                                                                                                  {
                                                                                                    // R: . - .
                                                                                                    dot();
                                                                                                    dash();
                                                                                                    dot();
                                                                                                    blankSpace();
                                                                                                  }
                                                                                                  
                                                                                                  void letterS()
                                                                                                  {
                                                                                                    // S: . . .
                                                                                                    dot();
                                                                                                    dot();
                                                                                                    dot();
                                                                                                    blankSpace();
                                                                                                  }
                                                                                                  
                                                                                                  void letterT()
                                                                                                  {
                                                                                                    // T: -
                                                                                                    dash();
                                                                                                    blankSpace();
                                                                                                  }
                                                                                                  
                                                                                                  void letterU()
                                                                                                  {
                                                                                                    // U: . . -
                                                                                                    dot();
                                                                                                    dot();
                                                                                                    dash();
                                                                                                    blankSpace();
                                                                                                  }
                                                                                                  
                                                                                                  void letterV()
                                                                                                  {
                                                                                                    // V: . . . -
                                                                                                    dot();
                                                                                                    dot();
                                                                                                    dot();
                                                                                                    dash();
                                                                                                    blankSpace();
                                                                                                  }
                                                                                                  
                                                                                                  void letterW()
                                                                                                  {
                                                                                                    // W: . - -
                                                                                                    dot();
                                                                                                    dash();
                                                                                                    dash();
                                                                                                    blankSpace();
                                                                                                  }
                                                                                                  
                                                                                                  void letterX()
                                                                                                  {
                                                                                                    // X: - . . -
                                                                                                    dash();
                                                                                                    dot();
                                                                                                    dot();
                                                                                                    dash();
                                                                                                    blankSpace();
                                                                                                  }
                                                                                                  
                                                                                                  void letterY()
                                                                                                  {
                                                                                                    // Y: - . - -
                                                                                                    dash();
                                                                                                    dot();
                                                                                                    dash();
                                                                                                    dash();
                                                                                                    blankSpace();
                                                                                                  }
                                                                                                  
                                                                                                  void letterZ()
                                                                                                  {
                                                                                                    // Z: - - . .
                                                                                                    dash();
                                                                                                    dash();
                                                                                                    dot();
                                                                                                    dot();
                                                                                                    blankSpace();
                                                                                                  }
                                                                                                  

                                                                                                  Now the loop function with the message SOS can be readily modified:

                                                                                                  void loop()
                                                                                                  {
                                                                                                    //Morse Code
                                                                                                    letterS();
                                                                                                    letterO();
                                                                                                    letterS();
                                                                                                    endSpace();
                                                                                                  }

                                                                                                  For example to HELLO WORLD:

                                                                                                  void loop()
                                                                                                  {
                                                                                                    //Morse Code
                                                                                                    letterH();
                                                                                                    letterE();
                                                                                                    letterL();
                                                                                                    letterL();
                                                                                                    letterO();
                                                                                                    blankSpace();
                                                                                                    letterW();
                                                                                                    letterO();
                                                                                                    letterR();
                                                                                                    letterL();
                                                                                                    letterD();
                                                                                                    endSpace();
                                                                                                  }

                                                                                                  Tutorial 05: Numbering Systems and DataTypes used in Computer Science

                                                                                                  In a computer everything is stored as a binary number. There are a few fundamental datatypes which we need to be familar with:

                                                                                                  Decimal Characters 0,1,2,3,4,5,6,7,8,9

                                                                                                  To count numbers typically we use the characters 0,1,2,3,4,5,6,7,8,9 as we have "ten" fingers. If we count to a higher quantity we need to use another digit for example 10.

                                                                                                  In the Arduino IDE these are of the type int and are input using no prefix for example

                                                                                                  int myNum = 123

                                                                                                  Binary Characters 0,1

                                                                                                  Data in a computer is stored in a series of binary switches which have the values Off (0 or Low) or On (1 or High). To get to a higher quantity "three" we need to use another digit which gives 10.

                                                                                                  In the Arduino IDE these are of the type int and are input using the prefix 0b for example

                                                                                                  int myBin = 0b1111011

                                                                                                  Hexadecimal Characters 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F

                                                                                                  Another character system used is the Hexadecimal Character system which has 16 characters (using the characters in the binary number system plus 6 additional characters of the alphabet).

                                                                                                  In the Arduino IDE these are of the type int and are input using the prefix 0x for example:

                                                                                                  int myHex = 0x7B

                                                                                                  byte and kilobyte

                                                                                                  Because 16^1=2^4 a single Hexadecimal Digit can be used to represent 4 Binary Characters.

                                                                                                  Hexadecimal
                                                                                                  (1 Character)
                                                                                                  (16^1)
                                                                                                  Decimal
                                                                                                  (2 Characters)
                                                                                                  (10^2)
                                                                                                  Binary
                                                                                                  (4 Characters)
                                                                                                  (2^4)
                                                                                                  0000000
                                                                                                  1010001
                                                                                                  2020010
                                                                                                  3030011
                                                                                                  4040100
                                                                                                  5050101
                                                                                                  6060110
                                                                                                  7070111
                                                                                                  8081000
                                                                                                  9091001
                                                                                                  A101010
                                                                                                  B111011
                                                                                                  C121100
                                                                                                  D131101
                                                                                                  E141110
                                                                                                  F151111

                                                                                                  A byte is 256 numbers (0-255 in Decimal). These can be represented as two Hexadecimal digits (16^2) or eight Binary digits (2^8).

                                                                                                  1024 bytes are known as a kilobyte. A kilobyte is 10 Binary digits (2^10).

                                                                                                  The Arduino analogWrite typically uses a byte and the analogRead uses a kilobyte.

                                                                                                  char

                                                                                                  A byte, 256 values can be used to represent all the commonly used characters (including hidden characters used for punctuation) in the English language for example:

                                                                                                  void setup()
                                                                                                  {
                                                                                                    Serial.begin(9600);
                                                                                                    for(int i=0; i<256; i++)
                                                                                                      {
                                                                                                        Serial.print("i: ");
                                                                                                        Serial.print(i);
                                                                                                        Serial.print(" character: ");
                                                                                                        Serial.println((char) i);
                                                                                                      }
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                  
                                                                                                  }

                                                                                                  In the Arduino IDE these are of the type char and are input enclosed in single quotations, for example:

                                                                                                  char myChar = 'A'

                                                                                                  string

                                                                                                  A string is a collection of characters. These are enclosed with double quotation marks:

                                                                                                  string myString = "Hello World"

                                                                                                  \ is used to insert an escape character. To include a quotation within a string for example we can use \' or \". We can insert a tab or a newline using \t or \n. To insert a \ for example in a file path we use two \\, the first \ indicates we are going to insert an escape character and the second \ indicates that \ is the escape character to be inserted.

                                                                                                  string filePath = "C:\\Windows"

                                                                                                  float

                                                                                                  So far we have only considered a physical representation of a full integer number. In real life many numbers have a decimal component. If we take length for example. We can look at a length comparable for us using a metre stick with markings indicating one thousands of a metre i.e. mm marking:

                                                                                                  The metric system is based around the decimal system which uses the ten characters 0,1,2,3,4,5,6,7,8,9. This measurement device can be used to measure something with similar dimensions to us but does not have the accuracy to measure something small like the radius of a Hydrogen atom and does not have the scope to measure something much larger like the radius of the sun.

                                                                                                  To cover both of these we need a measurement system that can scale very large and very small units. In the metric system for convenience units of every thousand away from the unit are typically represented with a prefix.

                                                                                                  valueDigit
                                                                                                  (with Respect to Unit)
                                                                                                  prefixsingle letter
                                                                                                  prefix
                                                                                                  1,000,000,000,000+12TeraT
                                                                                                  1,000,000,000+9GigaG
                                                                                                  1,000,000+6MegaM
                                                                                                  1,000+3Kilok
                                                                                                  10
                                                                                                  0 . 001-3Millim
                                                                                                  0 . 000 001-6Microµ
                                                                                                  0 . 000 000 001-9Nanon
                                                                                                  0 . 000 000 000 001-12Picop

                                                                                                  This gives:

                                                                                                  • 696.34 megametres – radius of the sun
                                                                                                  • 1.753 metres – height of a human
                                                                                                  • 120 picometres – radius of hydrogen atom

                                                                                                  In a computer or microcontroller we must store these numbers using a series of bytes i.e. binary switches. To use the precision from the -12 to the +12 decimal place would require 1000000000000000000000000 discrete decimal numbers and in binary representation would be more memory than available on our Arduino or even computer…

                                                                                                  In order to better utilise memory we instead encode such numbers using a limited 6-7 digits of precision. For example:

                                                                                                  float pi = 3.14;

                                                                                                  Tutorial 06: Arduino and LED Binary Counter

                                                                                                  To understand the numbering system in more detail we can use four LEDs to represent 4 binary switches. We can test this circuit by turning all four LEDs on:

                                                                                                  int pinLED1 = 10;
                                                                                                  int pinLED2 = 11;
                                                                                                  int pinLED3 = 12;
                                                                                                  int pinLED4 = 13;
                                                                                                  
                                                                                                  void setup(){
                                                                                                    pinMode(pinLED1, OUTPUT);
                                                                                                    pinMode(pinLED2, OUTPUT);
                                                                                                    pinMode(pinLED3, OUTPUT);
                                                                                                    pinMode(pinLED4, OUTPUT);
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                    digitalWrite(pinLED1, HIGH);
                                                                                                    digitalWrite(pinLED2, HIGH);
                                                                                                    digitalWrite(pinLED3, HIGH);
                                                                                                    digitalWrite(pinLED4, HIGH);
                                                                                                  }

                                                                                                  Next we want to update the Arduino sketch and change the LED state to count through the binary representation below:

                                                                                                  Hexadecimal
                                                                                                  (1 Character)
                                                                                                  (16^1)
                                                                                                  Decimal
                                                                                                  (2 Characters)
                                                                                                  (10^2)
                                                                                                  Binary
                                                                                                  (4 Characters)
                                                                                                  (2^4)
                                                                                                  0000000
                                                                                                  1010001
                                                                                                  2020010
                                                                                                  3030011
                                                                                                  4040100
                                                                                                  5050101
                                                                                                  6060110
                                                                                                  7070111
                                                                                                  8081000
                                                                                                  9091001
                                                                                                  A101010
                                                                                                  B111011
                                                                                                  C121100
                                                                                                  D131101
                                                                                                  E141110
                                                                                                  F151111

                                                                                                  We can hard code this:

                                                                                                  int pinLED1 = 10;
                                                                                                  int pinLED2 = 11;
                                                                                                  int pinLED3 = 12;
                                                                                                  int pinLED4 = 13;
                                                                                                  int dt = 1000;
                                                                                                  
                                                                                                  void setup(){
                                                                                                    pinMode(pinLED1, OUTPUT);
                                                                                                    pinMode(pinLED2, OUTPUT);
                                                                                                    pinMode(pinLED3, OUTPUT);
                                                                                                    pinMode(pinLED4, OUTPUT);
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                    
                                                                                                    // Zero 0x0 0b0000
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                   
                                                                                                    // One 0x1 0b0001
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, HIGH);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                    // Two 0x2 0b0010
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, HIGH);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                    // Three 0x3 0b0011
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, HIGH);
                                                                                                    digitalWrite(pinLED4, HIGH);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                    // Four 0x4 0b0100
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, HIGH);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                    // Five 0x5 0b0101
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, HIGH);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, HIGH);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                    // Six 0x6 0b0110
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, HIGH);
                                                                                                    digitalWrite(pinLED3, HIGH);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                      
                                                                                                    // Seven 0x7 0b0111
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, HIGH);
                                                                                                    digitalWrite(pinLED3, HIGH);
                                                                                                    digitalWrite(pinLED4, HIGH);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                      
                                                                                                    // Eight 0x8 0b1000
                                                                                                    digitalWrite(pinLED1, HIGH);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                    // Nine 0x9 0b1001
                                                                                                    digitalWrite(pinLED1, HIGH);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, HIGH);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                      
                                                                                                    // Ten 0xA 0b1010
                                                                                                    digitalWrite(pinLED1, HIGH);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, HIGH);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                     // Eleven 0xB 0b1011
                                                                                                    digitalWrite(pinLED1, HIGH);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, HIGH);
                                                                                                    digitalWrite(pinLED4, HIGH);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                    // Twelve 0xC 0b1100
                                                                                                    digitalWrite(pinLED1, HIGH);
                                                                                                    digitalWrite(pinLED2, HIGH);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                    // Thirteen 0xD 0b1101
                                                                                                    digitalWrite(pinLED1, HIGH);
                                                                                                    digitalWrite(pinLED2, HIGH);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, HIGH);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                  
                                                                                                    // Fourteen 0xE 0b1110
                                                                                                    digitalWrite(pinLED1, HIGH);
                                                                                                    digitalWrite(pinLED2, HIGH);
                                                                                                    digitalWrite(pinLED3, HIGH);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                    // Fifteen 0xF 0b1111
                                                                                                    digitalWrite(pinLED1, HIGH);
                                                                                                    digitalWrite(pinLED2, HIGH);
                                                                                                    digitalWrite(pinLED3, HIGH);
                                                                                                    digitalWrite(pinLED4, HIGH);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                    
                                                                                                  }

                                                                                                  However we notice a lot of repetition in our code. This can be simplified by using a function switchOffLEDs which is used to switch the LEDs off after each binary representation:

                                                                                                  void switchOffLEDs(){
                                                                                                    delay(dt);
                                                                                                    
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    
                                                                                                    delay(dt);
                                                                                                  }

                                                                                                  We can make this more functional yet by instead making a function for each combination and calling these functions in the loop function:

                                                                                                  int pinLED1 = 10;
                                                                                                  int pinLED2 = 11;
                                                                                                  int pinLED3 = 12;
                                                                                                  int pinLED4 = 13;
                                                                                                  int dt = 1000;
                                                                                                  
                                                                                                  void switchOffLEDs(){
                                                                                                    delay(dt);
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    delay(dt);
                                                                                                  }
                                                                                                  
                                                                                                  void setup(){
                                                                                                    pinMode(pinLED1, OUTPUT);
                                                                                                    pinMode(pinLED2, OUTPUT);
                                                                                                    pinMode(pinLED3, OUTPUT);
                                                                                                    pinMode(pinLED4, OUTPUT);
                                                                                                  }
                                                                                                  
                                                                                                  void binaryZero(){
                                                                                                    // Zero 0x0 0b0000
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    switchOffLEDs();
                                                                                                  }
                                                                                                  
                                                                                                  void binaryOne(){
                                                                                                    // One 0x1 0b0001
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, HIGH);
                                                                                                    switchOffLEDs();
                                                                                                  }
                                                                                                  
                                                                                                  void binaryTwo(){
                                                                                                    // Two 0x2 0b0010
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, HIGH);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    switchOffLEDs();
                                                                                                  }
                                                                                                  
                                                                                                  void binaryThree(){
                                                                                                    // Three 0x3 0b0011
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, HIGH);
                                                                                                    digitalWrite(pinLED4, HIGH);
                                                                                                    switchOffLEDs();
                                                                                                  }
                                                                                                  
                                                                                                  void binaryFour(){
                                                                                                    // Four 0x4 0b0100
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, HIGH);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    switchOffLEDs();
                                                                                                  }
                                                                                                  
                                                                                                  void binaryFive(){
                                                                                                    // Five 0x5 0b0101
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, HIGH);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, HIGH);
                                                                                                    switchOffLEDs();
                                                                                                  }
                                                                                                  
                                                                                                  void binarySix(){
                                                                                                    // Six 0x6 0b0110
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, HIGH);
                                                                                                    digitalWrite(pinLED3, HIGH);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    switchOffLEDs();
                                                                                                  }
                                                                                                  
                                                                                                  void binarySeven(){
                                                                                                     // Seven 0x7 0b0111
                                                                                                    digitalWrite(pinLED1, LOW);
                                                                                                    digitalWrite(pinLED2, HIGH);
                                                                                                    digitalWrite(pinLED3, HIGH);
                                                                                                    digitalWrite(pinLED4, HIGH);
                                                                                                    switchOffLEDs();
                                                                                                  }
                                                                                                  
                                                                                                  void binaryEight(){   
                                                                                                    // Eight 0x8 0b1000
                                                                                                    digitalWrite(pinLED1, HIGH);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    switchOffLEDs();
                                                                                                  }
                                                                                                  
                                                                                                  void binaryNine(){
                                                                                                    // Nine 0x9 0b1001
                                                                                                    digitalWrite(pinLED1, HIGH);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, HIGH);
                                                                                                    switchOffLEDs();
                                                                                                  }
                                                                                                  
                                                                                                  void binaryTen(){
                                                                                                    // Ten 0xA 0b1010
                                                                                                    digitalWrite(pinLED1, HIGH);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, HIGH);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    switchOffLEDs();
                                                                                                  }
                                                                                                  
                                                                                                  void binaryEleven(){
                                                                                                    // Eleven 0xB 0b1011
                                                                                                    digitalWrite(pinLED1, HIGH);
                                                                                                    digitalWrite(pinLED2, LOW);
                                                                                                    digitalWrite(pinLED3, HIGH);
                                                                                                    digitalWrite(pinLED4, HIGH);
                                                                                                    switchOffLEDs();
                                                                                                  }
                                                                                                  
                                                                                                  void binaryTwelve(){
                                                                                                    // Twelve 0xC 0b1100
                                                                                                    digitalWrite(pinLED1, HIGH);
                                                                                                    digitalWrite(pinLED2, HIGH);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    switchOffLEDs();
                                                                                                  }
                                                                                                  
                                                                                                  void binaryThirteen(){
                                                                                                    // Thirteen 0xD 0b1101
                                                                                                    digitalWrite(pinLED1, HIGH);
                                                                                                    digitalWrite(pinLED2, HIGH);
                                                                                                    digitalWrite(pinLED3, LOW);
                                                                                                    digitalWrite(pinLED4, HIGH);
                                                                                                    switchOffLEDs();
                                                                                                  }
                                                                                                  
                                                                                                  void binaryFourteen(){
                                                                                                    // Fourteen 0xE 0b1110
                                                                                                    digitalWrite(pinLED1, HIGH);
                                                                                                    digitalWrite(pinLED2, HIGH);
                                                                                                    digitalWrite(pinLED3, HIGH);
                                                                                                    digitalWrite(pinLED4, LOW);
                                                                                                    switchOffLEDs();
                                                                                                  }
                                                                                                  
                                                                                                  void binaryFifteen(){
                                                                                                    // Fifteen 0xF 0b1111
                                                                                                    digitalWrite(pinLED1, HIGH);
                                                                                                    digitalWrite(pinLED2, HIGH);
                                                                                                    digitalWrite(pinLED3, HIGH);
                                                                                                    digitalWrite(pinLED4, HIGH);
                                                                                                    switchOffLEDs();
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                    binaryZero();
                                                                                                    binaryOne();
                                                                                                    binaryTwo();
                                                                                                    binaryThree();
                                                                                                    binaryFour();  
                                                                                                    binaryFive();
                                                                                                    binarySix();
                                                                                                    binarySeven();
                                                                                                    binaryEight();
                                                                                                    binaryNine();
                                                                                                    binaryTen();
                                                                                                    binaryEleven();
                                                                                                    binaryTwelve();
                                                                                                    binaryThirteen();
                                                                                                    binaryFourteen();
                                                                                                    binaryFifteen();  
                                                                                                  }

                                                                                                  Tutorial 07 and 08: Arduino digitalWrite, analogWrite and ~Pulse Width Modulation

                                                                                                  We have already used the digitalWrite command to set the voltage in a GPIO pin to HIGH or LOW. This switched the LED On or Off. If we add a scope between the GPIO pin and ground we can measure the voltage and see a solid 5 V or 0 V respectively.

                                                                                                  digitalWrite(ledPIN, HIGH);
                                                                                                  digitalWrite(ledPIN, LOW);

                                                                                                  The Arduino pins marked with a ~ such as 3, 5, 6, 9, 10 and 11 also have the capability to use an analogWrite. We must specify the pin to perform the analogWrite on as well an 8 bit value. This is known as a byte and ranges from 0-255 as previously discussed:

                                                                                                  analogWrite(ledPIN, 255);
                                                                                                  analogWrite(ledPIN, 0);

                                                                                                  The upper and lower bound 255 and 0 are essentially equivalent to HIGH and LOW used in a digitalWrite:

                                                                                                  The Arduino doesn't use a true analog signal but rather uses pulse width modulation (pwm). In pwm a square digital trace is used to simulate an analog signal. This square wave switches quickly between 0 and 5 V over a millisecond time-scale. This can be seen looking at an intermediate value such as 128 which is in the middle. This electrical process is too fast for our eyes to register and thus the LED appears to be on but dimmed (half brightness). Although too fast for the eye the electrical process can be measured on an oscilloscope. The output is at 0 V half the time and 1 V the other half of the time over a period of 1 ms.

                                                                                                  analogWrite(ledPIN, 128);

                                                                                                  And if a smaller value is selected:

                                                                                                  analogWrite(ledPIN, 5);

                                                                                                  Tutorial 09: Arduino and Ohms Law

                                                                                                  If we create a circuit with two resistors r1=330 R and r2=100 R in series attached between 5 V and GND. This can be visualised as a flow of positive particles through a pipe with two restrictions. The higher the resistance, the smaller the diameter of the pipe:

                                                                                                  The total resistance in the circuit is the sum of the resistance values:

                                                                                                  Then the current which can be thought as the rate of flow of positive particles falling through the bottom of the pipe in the circuit is:

                                                                                                  The flow of current is across the circuit. And the Voltage across each resistor is:

                                                                                                  This can be roughly visualised as the proportion of time the positive electrical charges spend stuck in each constricted area or resistor of the pipe. A voltage divider across a series of resistors is commonly used for reading values between a sensor.

                                                                                                  Tutorial 10: Arduino analogRead

                                                                                                  The Arduino has 6 pins A0, A1, A2, A3, A4, A5 and A6 which are capable of reading the 5V voltage as a kilobyte value. Recall that a kilobyte is 10 Binary digits (2^10) and has decimal values from 0-1023.

                                                                                                  We need to assign an integer value for each pin as well as an integer variable to store the value in for example pinV1 and valV1 respectively. In the setup, this time we are going to configure each pin as an INPUT as we are reading a value into the Arduino. The analogRead function requires a pin as its input argument and this function returns a value of the type int. We can assign this output to our variable, in the case of an analogRead of pinV1 to our variable valV1. In order to read the values we will need to use our Arduino's serial port and we can print the values valV1, valV2 and valV3 using some basic formatting.

                                                                                                  int pinV1 = A0;
                                                                                                  int pinV2 = A1;
                                                                                                  int pinV3 = A2;
                                                                                                  
                                                                                                  int valV1;
                                                                                                  int valV2;
                                                                                                  int valV3;
                                                                                                  
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(pinV1, INPUT);
                                                                                                    pinMode(pinV2, INPUT);
                                                                                                    pinMode(pinV3, INPUT);
                                                                                                    
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    valV1 = analogRead(pinV1);
                                                                                                    valV2 = analogRead(pinV2);
                                                                                                    valV3 = analogRead(pinV3);
                                                                                                    
                                                                                                    Serial.print("valV1: ");
                                                                                                    Serial.print(valV1);
                                                                                                    Serial.print(" valV2: ");
                                                                                                    Serial.print(valV2);
                                                                                                    Serial.print(" valV3: ");
                                                                                                    Serial.println(valV3);
                                                                                                    
                                                                                                    delay(delayTime);
                                                                                                  }

                                                                                                  This gives:

                                                                                                  valV1: 1023 valV2: 238 valV3: 0

                                                                                                  The integer value 1023 corresponds to the float +5.0 V and the integer value 0 corresponds to the float 0.0 V or ground.

                                                                                                  Any other value can be calculated using the conversion factor:

                                                                                                  And:

                                                                                                  We can see that V1 is the voltage difference between 5 V and Ground i.e. 5.00 V. That V2 is the voltage difference across the resistor R2 and ground. i.e. equal to the value V2 across R2 in Tutorial 09 i.e. 1.16 V and that V3 is the voltage difference between ground and ground which is 0.00 V.

                                                                                                  To use a floating point number in C++ we must declare it as a float and specify a decimal point. For example:

                                                                                                  float valV1f = 5.;

                                                                                                  When making calculations in our Arduino sketch. We must cast the int value to a float and also specify 5 as 5. and 1023 as 1023. in order to carry out a float operation.

                                                                                                  float valV2f;
                                                                                                  valV2f = (float) valV2 * 5. / 1023.;

                                                                                                  This will give the value 1.16.

                                                                                                  Failure to do so will instead carry out integer operations on the right hand side of the second line and so the value 1 (with 0.16 being truncated) will be calculated and then assigned to the value valV2f on the left hand side of the equation:

                                                                                                  float valV2f;
                                                                                                  valV2f = valV2 * 5 / 1023;

                                                                                                  A sketch that reads the analogRead and converts them to their corresponding voltages is as follows:

                                                                                                  int pinV1 = A0;
                                                                                                  int pinV2 = A1;
                                                                                                  int pinV3 = A2;
                                                                                                  
                                                                                                  int valV1;
                                                                                                  int valV2;
                                                                                                  int valV3;
                                                                                                  
                                                                                                  float valV1f;
                                                                                                  float valV2f;
                                                                                                  float valV3f;
                                                                                                  
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(pinV1, INPUT);
                                                                                                    pinMode(pinV2, INPUT);
                                                                                                    pinMode(pinV3, INPUT);
                                                                                                    
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    valV1 = analogRead(pinV1);
                                                                                                    valV2 = analogRead(pinV2);
                                                                                                    valV3 = analogRead(pinV3);
                                                                                                    
                                                                                                    valV1f = (float) valV1 * 5. / 1023.;
                                                                                                    valV2f = (float) valV2 * 5. / 1023.;
                                                                                                    valV3f = (float) valV3 * 5. / 1023.;
                                                                                                    
                                                                                                    Serial.print("valV1: ");
                                                                                                    Serial.print(valV1);
                                                                                                    Serial.print(" valV2: ");
                                                                                                    Serial.print(valV2);
                                                                                                    Serial.print(" valV3: ");
                                                                                                    Serial.println(valV3);
                                                                                                  	
                                                                                                      
                                                                                                    Serial.print("valV1f: ");
                                                                                                    Serial.print(valV1f);
                                                                                                    Serial.print(" V valV2f: ");
                                                                                                    Serial.print(valV2f);
                                                                                                    Serial.print(" V valV3f: ");
                                                                                                    Serial.print(valV3f);
                                                                                                    Serial.println(" V");
                                                                                                    
                                                                                                    Serial.println();
                                                                                                    delay(delayTime);
                                                                                                  }

                                                                                                  This gives an example reading:

                                                                                                  valV1: 1023 valV2: 238 valV3: 0
                                                                                                  valV1f: 5.00 V valV2f: 1.16 V valV3f: 0.00 V

                                                                                                  The circuit and the sketch can be updated to read off pin12 instead of the 5 V pin. Notice that this has 3 INPUT pins and 1 OUTPUT pin:

                                                                                                  int vPin = 11;
                                                                                                  
                                                                                                  int pinV1 = A0;
                                                                                                  int pinV2 = A1;
                                                                                                  int pinV3 = A2;
                                                                                                  
                                                                                                  float valV1;
                                                                                                  float valV2;
                                                                                                  float valV3;
                                                                                                  
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(vPin, OUTPUT);
                                                                                                    
                                                                                                    pinMode(pinV1, INPUT);
                                                                                                    pinMode(pinV2, INPUT);
                                                                                                    pinMode(pinV3, INPUT);
                                                                                                    
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    for(int analogVal=0; analogVal<256; analogVal++){
                                                                                                      Serial.print("analogVal: ");
                                                                                                      Serial.println(analogVal);
                                                                                                      
                                                                                                      analogWrite(vPin, analogVal);
                                                                                                  
                                                                                                      valV1 = (float) analogRead(pinV1) * 5. / 1023.;
                                                                                                      valV2 = (float) analogRead(pinV2) * 5. / 1023.;
                                                                                                      valV3 = (float) analogRead(pinV3) * 5. / 1023.;
                                                                                                  
                                                                                                      Serial.print("valV1: ");
                                                                                                      Serial.print(valV1);
                                                                                                      Serial.print(" valV2: ");
                                                                                                      Serial.print(valV2);
                                                                                                      Serial.print(" valV3: ");
                                                                                                      Serial.println(valV3);
                                                                                                  
                                                                                                      Serial.println();
                                                                                                      delay(delayTime);
                                                                                                    }
                                                                                                  }

                                                                                                  Notice that the voltage output from the pin is slightly shy of 5.0 V so we get a reading back of 916 opposed to 1023 i.e. 4.48 V opposed to 5.0 V:

                                                                                                  valV1: 916 valV2: 213 valV3: 0
                                                                                                  valV1f: 4.48 V valV2f: 1.04 V valV3f: 0.00 V
                                                                                                  
                                                                                                  valV1: 0 valV2: 0 valV3: 0
                                                                                                  valV1f: 0.00 V valV2f: 0.00 V valV3f: 0.00 V

                                                                                                  This can also be done with an analogWrite and a for loop. The emulation in Tinkercad is however limited when it comes to using the analogWrite command:

                                                                                                  The important thing to note is that the analogWrite typically uses a byte scaling from 0-255 and the analogRead uses a kilobyte scaling from 0-1023. In this case our highest voltage was 4.48 V and not 5.00 V so our maximum endpoint value was 916.

                                                                                                  The x axis has the independent variable and the y axis has the dependent variable. In this case we are changing analogVal independently and measuring the value of valV1 respect to analogVal.

                                                                                                  We therefore expect a straight line from the origin:

                                                                                                  x: analogVal=0 y: valV1=0

                                                                                                  To an endpoint of:

                                                                                                  x: analogVal=255 y: valV1=916

                                                                                                  The gradient is therefore:

                                                                                                  And we can substitution one of the points and gradient into the equation of a straight line to get the intercept. If we choose the origin we can see that the constant is therefore 0:

                                                                                                  Thus we can compute the expect values in Excel using the formula:

                                                                                                  We can plot this out:

                                                                                                  Tutorial 11: Arduino Serial port class

                                                                                                  The Arduino IDE has a Serial port class. This Serial class contains a collection of functions that can be used to control the Serial Port. The main functions are:

                                                                                                  int baudrate = 9600;
                                                                                                  Serial.begin(baudrate);

                                                                                                  The baudrate is the speed of communication and the Serial Monitor must be configured to use the same baudrate for communication to work as expected. 9600 is the standard value used. No line ending should also be configured.

                                                                                                  string myString = "Hello World";
                                                                                                  Serial.print(myString);
                                                                                                  Hello World

                                                                                                  print will print a string to the Serial Monitor:

                                                                                                  string myString = "Hello World";
                                                                                                  Serial.println(myString);
                                                                                                  Hello World
                                                                                                  

                                                                                                  println (print line) will print a string to the Serial Monitor and end the statement with a new line. A new line can also be inserting into a string using the escape character /n and a tab can be inserted using the escape character \t respectively.

                                                                                                  Note the output for the following looks like:

                                                                                                  string myString = "Hello World";
                                                                                                  Serial.print(myString);
                                                                                                  Serial.println(myString);
                                                                                                  Serial.print(myString);
                                                                                                  Hello WorldHello World
                                                                                                  Hello World

                                                                                                  And any other command will continue printing where the ! is because the last statement used the function print and not println:

                                                                                                  Hello WorldHello World
                                                                                                  Hello World!

                                                                                                  The syntax for the print and println function can also print numbers:

                                                                                                  int myNum = 4;
                                                                                                  Serial.print(myNum);
                                                                                                  4
                                                                                                  float myNum = 4.123;
                                                                                                  Serial.print(myNum);
                                                                                                  4.12

                                                                                                  Note by default for the float only 2 decimal places display. There is an optional secondary input argument format which can be used to specify the number of decimal places:

                                                                                                  float myNum = 4.123;
                                                                                                  int format = 3;
                                                                                                  Serial.print(myNum, format);
                                                                                                  4.123

                                                                                                  Tutorial 12: Arduino and Potentiometer

                                                                                                  The Potentiometer can be visualised as a Resistor and if we examine the outer pins we will return a constant value 250 kΩ regardless of the position of the dial:

                                                                                                  If instead of looking at the outer pins, we look at the resistance reading between the 1st and 2nd pin an 2nd and also the resistance reading between the 2nd and 3rd pin. We see that the resistance of the first reading increases from 0 Ω as the dial rotates and the resistance of the second reading decreases from a maximum value of 250 kΩ. In all cases the sum of the two readings is always 250 kΩ.

                                                                                                  We can compare this directly to a voltage divider made from two resistors. In either case the 5V power supply connects to the red pin and the black pin connects to round in either case. The middle blue pin is the sense pin.

                                                                                                  When the slider on the potentiometer is 0. The left resistor R1 is 0 and the right resistor R2 is the maximum value 250 kΩ. The reading at the sense pin will therefore be 5.00 V.

                                                                                                  As the dial is rotated, to the right the resistance of the first resistor r1 increases and the resistance of r2 decreases. As a result the voltage measured on the voltmeter decreases.

                                                                                                  Instead of using a voltmeter, we can use an analog pin within the Arduino to read the 5 V signal as an integer of kilobyte scaling 0-1023.

                                                                                                  int potPin = A0;
                                                                                                  int potVal;
                                                                                                  float potVolt;
                                                                                                  int delayTime = 250;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(potPin, INPUT);
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                    potVal = analogRead(potPin);
                                                                                                    potVolt = (float) potVal*5./1023.;
                                                                                                    Serial.print("potVal: ");
                                                                                                    Serial.print(potVal);
                                                                                                    Serial.print(" potVol: ");
                                                                                                    Serial.println(potVolt);
                                                                                                    delay(delayTime);
                                                                                                  }

                                                                                                  Tutorial 13: Code Blocks

                                                                                                  functions

                                                                                                  So far we have looked at functions. These typically have the form of the return type followed by the function name, which is usually in camelCase. After the function name parenthesis are required. The parenthesis include input arguments although not all functions have input arguments. Next is the { } which are used to incorporate a code block. The code block consists of a series of statements all which end in a semi-colon ;

                                                                                                  void functionName(input_arg){
                                                                                                      statement 1;
                                                                                                      statement 2;
                                                                                                  }

                                                                                                  An Arduino sketch contains two functions by default. setup which is ran once and loop, which loops round continuously:

                                                                                                  void setup(){
                                                                                                  
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                  
                                                                                                  }

                                                                                                  We add our own statements to these functions and in this case all the statements that we add are calling other inbuilt functions:

                                                                                                  void setup(){
                                                                                                      pinMode(11, OUTPUT);
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                      digitalWrite(HIGH);
                                                                                                      delay(1000);
                                                                                                      digitalWrite(LOW);
                                                                                                  }

                                                                                                  We can instead create our own function as we did in Tutorial 04 when looking at using Morse Code:

                                                                                                  void dash()
                                                                                                  {
                                                                                                    digitalWrite(redPin, HIGH);
                                                                                                    delay(dashT); 
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    delay(dashT);
                                                                                                  }
                                                                                                  
                                                                                                  void dot()
                                                                                                  {
                                                                                                    digitalWrite(redPin, HIGH);
                                                                                                    delay(dotT); 
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    delay(dotT);
                                                                                                  }
                                                                                                  

                                                                                                  These functions have no return type or input arguments and are called using:

                                                                                                  dash();
                                                                                                  dot();

                                                                                                  We can instead create a function that has an input argument and returns a value. In this case we will double the number:

                                                                                                  int doubleNum(int inputNum){
                                                                                                      return 2*num1;
                                                                                                  }

                                                                                                  To call this function we need to create a variable for the input argument and a variable for the output argument:

                                                                                                  int startNum = 2;
                                                                                                  int endNum
                                                                                                  endNum = doubleNum(startNum);

                                                                                                  The int variable startNum belongs to the main program. The function is declared in the main program but functions have their own local scope and can only access variables supplied via its input arguments. In this case startNum is supplied to the function with the local name inputNum (indicated as the green arrow).

                                                                                                  The function can likewise only return a value from its local namespace using the return statement (indicated as the purple arrow).

                                                                                                  To run this in an Arduino sketch we need to define the variables and function. Then we need to call the function in the setup to run once or loop to run repeatedly. To display the value being created we need to use the Serial monitor:

                                                                                                  int startNum=2;
                                                                                                  int endNum;
                                                                                                  
                                                                                                  int doubleNum(int num1=1){
                                                                                                      return 2*num1;
                                                                                                  }
                                                                                                  
                                                                                                  void setup(){
                                                                                                    endNum = doubleNum(startNum);
                                                                                                    Serial.begin(9600);
                                                                                                    Serial.println(endNum);
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                  
                                                                                                  }

                                                                                                  This displays the value as expected:

                                                                                                  4

                                                                                                  if, else

                                                                                                  Sometimes we will only want to execute code if a condition has been satisfied. We can do this with an if statement. This time the parenthesis includes the condition:

                                                                                                  if(condition){
                                                                                                      statement 1;
                                                                                                      statement 2;
                                                                                                  }

                                                                                                  We may also want optionally want to do something else if this condition has not been met using an associated else statement. There is no parenthesis provided with the else statement as it is only carried out if the if statement condition is not satisfied:

                                                                                                  if(condition){
                                                                                                      statement 1;
                                                                                                      statement 2;
                                                                                                  }
                                                                                                  else{
                                                                                                      statement 1;
                                                                                                      statement 2;
                                                                                                  }

                                                                                                  There is also the optional else if statement. Note the code below shows a branched structure. The first condition is check and if satisfied the top code block runs and no other code blocks are examined. This means that if the conditions in the if and if else block are both true then only the if code block is executed. The else block is only executed if all the conditions in the branches above have not been satisfied:

                                                                                                  if(condition1){
                                                                                                      statement 1;
                                                                                                      statement 2;
                                                                                                  }
                                                                                                  else if(condition 2){
                                                                                                      statement 1;
                                                                                                      statement 2;
                                                                                                  }
                                                                                                  else{
                                                                                                      statement 1;
                                                                                                      statement 2;
                                                                                                  }

                                                                                                  The condition always equates to a binary bool expression which is either true or false. This is normally done by comparing two numbers. We have 6 comparison operators, less than, greater than, equal to (double equals, a single equals is assignment), not equal to, less than or equal to (includes the value at the boundary) and greater than or equal to (includes the value at the boundary):

                                                                                                  num1 < num2;
                                                                                                  num1 > num2;
                                                                                                  num1 == num2;
                                                                                                  num1 != num2;
                                                                                                  num1 <= num2;
                                                                                                  num1 >= num2;

                                                                                                  This concept can be explored using the integer analog reading from the middle pin of a potentiometer. When rotated and a value is high enough "Hello" is also printed. There is nothing additional printed times when this condition is not satisfied:

                                                                                                  int potPin = A0;
                                                                                                  int potVal;
                                                                                                  float potVolt;
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(potPin, INPUT);
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                    potVal = analogRead(potPin);
                                                                                                    Serial.print("potVal: ");
                                                                                                    Serial.println(potVal);
                                                                                                    if(potVal>500){
                                                                                                    	Serial.println("Hello");  
                                                                                                    }
                                                                                                    delay(delayTime);
                                                                                                  }

                                                                                                  We can include an else statement using:

                                                                                                  int potPin = A0;
                                                                                                  int potVal;
                                                                                                  float potVolt;
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(potPin, INPUT);
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                    potVal = analogRead(potPin);
                                                                                                    Serial.print("potVal: ");
                                                                                                    Serial.println(potVal);
                                                                                                    if(potVal>500){
                                                                                                    	Serial.println("Hello");  
                                                                                                    }
                                                                                                    else{
                                                                                                      Serial.println("goodbye");
                                                                                                    }
                                                                                                    delay(delayTime);
                                                                                                  }

                                                                                                  And we can use a nested if else statement. Notice that when the potVal is over 600 it is also over 500 but the else if code block is not executed unless the if condition is not met i.e. "Hello" is only displayed for a potVal value between 501 and 600:

                                                                                                  int potPin = A0;
                                                                                                  int potVal;
                                                                                                  float potVolt;
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(potPin, INPUT);
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                    potVal = analogRead(potPin);
                                                                                                    Serial.print("potVal: ");
                                                                                                    Serial.println(potVal);
                                                                                                    if(potVal>600){
                                                                                                    	Serial.println("Hello World");  
                                                                                                    }
                                                                                                    else if(potVal>500){
                                                                                                    	Serial.println("Hello"); 
                                                                                                    }
                                                                                                    else{
                                                                                                      Serial.println("Goodbye");
                                                                                                    }
                                                                                                    delay(delayTime);
                                                                                                  }

                                                                                                  switch case

                                                                                                  Another related programming concept is switch case. Here a variable of type int or char is declared as a switch. A code block can be constructed for each unique case. In this case, let's just look at case 0, 511 and 1023:

                                                                                                  int potPin = A0;
                                                                                                  int potVal;
                                                                                                  float potVolt;
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(potPin, INPUT);
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                    potVal = analogRead(potPin);
                                                                                                    Serial.print("potVal: ");
                                                                                                    Serial.println(potVal);
                                                                                                  
                                                                                                    switch(potVal){
                                                                                                      case 0:
                                                                                                      	Serial.println("Hello");
                                                                                                      case 511:
                                                                                                      	Serial.println("Hello World");
                                                                                                      case 1023:
                                                                                                      	Serial.println("Goodbye");
                                                                                                    }
                                                                                                    
                                                                                                    delay(delayTime);
                                                                                                  }

                                                                                                  Notice that when potVal is 511 that case 0 is not satisfied and this code block is therefore ignored. Case 511 is satisfied and the associated code block is run as expected. Note however that any subsequent code block is also executed.

                                                                                                  To prevent this from happening we can end each code block with a break statement.

                                                                                                  int potPin = A0;
                                                                                                  int potVal;
                                                                                                  float potVolt;
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(potPin, INPUT);
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                    potVal = analogRead(potPin);
                                                                                                    Serial.print("potVal: ");
                                                                                                    Serial.println(potVal);
                                                                                                  
                                                                                                    switch(potVal){
                                                                                                    	case 0:
                                                                                                      	Serial.println("Hello");
                                                                                                      	break;
                                                                                                      case 511:
                                                                                                      	Serial.println("Hello World");
                                                                                                      	break;
                                                                                                      case 1023:
                                                                                                      	Serial.println("Goodbye");
                                                                                                      	break;
                                                                                                    }
                                                                                                    
                                                                                                    delay(delayTime);
                                                                                                  }

                                                                                                  Tutorial 14: Arduino Dimmable LED Project

                                                                                                  Let's have a look at using the Potentiometer as an intensity slider. First of all connecting the first pin to +5V and the last pin to ground. We can then set up the middle pin to A0 and use analogRead to read the value as we move the potentiometer slider.

                                                                                                  int potPin = A0;
                                                                                                  int potVal;
                                                                                                  int delayTime=1000;
                                                                                                  
                                                                                                  void setup(){
                                                                                                    pinMode(potPin, INPUT);
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                    potVal = analogRead(potPin);
                                                                                                    Serial.println(potVal);
                                                                                                    delay(delayTime);
                                                                                                  }

                                                                                                  As the slider moves clockwise, the value falls from the maximum value of 1023 to the minimum value of 0.

                                                                                                  This is round the wrong was so the +5V and ground cables will be switched:

                                                                                                  The potentiometer potVal ranges from 0-1023.

                                                                                                  Now let's hook up an LED with a current limiting resistor to a ~PWM pin which gives us our circuit:

                                                                                                  We can modify our sketch so the LED is on using a constant value:

                                                                                                  int potPin = A0;
                                                                                                  int potVal;
                                                                                                  int redPin = 6;
                                                                                                  int ledVal = 127;
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup(){
                                                                                                    pinMode(potPin, INPUT);
                                                                                                    pinMode(redPin, OUTPUT);
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                    potVal = analogRead(potPin);
                                                                                                    analogWrite(redPin, ledVal);
                                                                                                    Serial.println(potVal);
                                                                                                    delay(delayTime);
                                                                                                  }
                                                                                                  

                                                                                                  Possible values for ledVal are 0-255.

                                                                                                  The potentiometer potVal ranges from 0-1023.

                                                                                                  potVal is an independent variable (x-axis) and we want to set the value ledVal as a linear function of this i.e. ledVal is the dependent variable (y-axis). The equation of a straight line is:

                                                                                                  To find the gradient m, we require 2 points:

                                                                                                  And we can substitute one of the points into the equation of a straight line to get the intercept:

                                                                                                  As our straight line passes through the origin the intercept is thus 0 and therefore the equation is:

                                                                                                  We can calculate the expected ledVal with respect to potVal in Excel:

                                                                                                  And create a plot of this data:

                                                                                                  Now we can update our sketch to calculate ledVal using this formula:

                                                                                                  int potPin = A0;
                                                                                                  int potVal;
                                                                                                  int redPin = 6;
                                                                                                  float ledValf;
                                                                                                  int ledVal;
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup(){
                                                                                                    pinMode(potPin, INPUT);
                                                                                                    pinMode(redPin, OUTPUT);
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                    potVal = analogRead(potPin);
                                                                                                    ledValf = 255. / 1023. * (float) potVal;
                                                                                                    ledVal = (int) ledValf;
                                                                                                    analogWrite(redPin, ledVal);
                                                                                                    Serial.print("potVal: ");
                                                                                                    Serial.print(potVal);
                                                                                                    Serial.print(" ledVal: ");
                                                                                                    Serial.println(ledVal);
                                                                                                    delay(delayTime);
                                                                                                  }
                                                                                                  

                                                                                                  And the Potentiometer can be used to control the brightness of the LED as expected:

                                                                                                  Tutorial 15-16: For Loops

                                                                                                  Supposing we have a basic circuit which has a redLED and a yellowLED connected to pin 9 and 6 respectively. If we want to blink the yellowLED three times and the redLED two times:

                                                                                                  We can create a sketch to do so:

                                                                                                  int yellowPin = 6;
                                                                                                  int redPin = 9;
                                                                                                  int yellowTime = 500;
                                                                                                  int redTime = 500;
                                                                                                  
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(yellowPin, OUTPUT);
                                                                                                    pinMode(redPin, OUTPUT);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                  	digitalWrite(yellowPin, HIGH);
                                                                                                    	delay(yellowTime);
                                                                                                    	digitalWrite(yellowPin, LOW);
                                                                                                    	delay(yellowTime);
                                                                                                    
                                                                                                    	digitalWrite(yellowPin, HIGH);
                                                                                                    	delay(yellowTime);
                                                                                                    	digitalWrite(yellowPin, LOW);
                                                                                                    	delay(yellowTime);
                                                                                                    
                                                                                                    	digitalWrite(yellowPin, HIGH);
                                                                                                    	delay(yellowTime);
                                                                                                    	digitalWrite(yellowPin, LOW);
                                                                                                    	delay(yellowTime);
                                                                                                    
                                                                                                    	digitalWrite(redPin, HIGH);
                                                                                                    	delay(redTime);
                                                                                                    	digitalWrite(redPin, LOW);
                                                                                                    	delay(redTime);
                                                                                                    
                                                                                                    	digitalWrite(redPin, HIGH);
                                                                                                    	delay(redTime);
                                                                                                    	digitalWrite(redPin, LOW);
                                                                                                    	delay(redTime);
                                                                                                  }

                                                                                                  Notice the repetition in the code. The following is repeated three times:

                                                                                                  digitalWrite(yellowPin, HIGH);
                                                                                                  delay(yellowTime);
                                                                                                  digitalWrite(yellowPin, LOW);
                                                                                                  delay(yellowTime);

                                                                                                  And the following is repeated two times:

                                                                                                  digitalWrite(redPin, HIGH);
                                                                                                  delay(redTime);
                                                                                                  digitalWrite(redPin, LOW);
                                                                                                  delay(redTime);

                                                                                                  Repeating the code is fine for a small number of blinks but copying and pasting this code block to make the LED blink say for example 300 and 200 times would get very messy… It can be simplified using a for loop. The for loop has a similar code block structure to a function or a conditional if code block. In the case of a for loop, the parenthesis must contain, the initialisation statement which initialises a loop variable, the condition statement for a loop iteration to proceed and one expression to increment the loop variable from one loop iteration to the next.

                                                                                                  Notice that the initialisation statement and condition statement must each end in a semi-colon while the increment expression must not.

                                                                                                  for(initialisation statement; condition statement; increment expression){
                                                                                                      code block statement 1;
                                                                                                      code block statement 2;
                                                                                                  }

                                                                                                  An expression is also used for the condition in if.

                                                                                                  if(condition expression){
                                                                                                      code block statement 1;
                                                                                                      code block statement 2;
                                                                                                  }

                                                                                                  The nuance between an expression and a statement can create some confusion for beginners… In C++ an expression essentially becomes a statement that is carried out when appended by a semi-colon.

                                                                                                  The use of an expression in if for the condition highlights some ambiguity i.e. that the code block may or may not be executed dependant on the condition. In the case of a for loop, the loop variable is always going to be initialised and the condition to check whether or not the loop is likewise always going to execute and therefore these are statements. On the other hand the increment expression is only going to be executed when the loop condition is true.

                                                                                                  Let's initialise a loop variable idx of type int and value 0. Let's set the condition to run if idx is less than 3 and let's increment the loop variable by 1 for example:

                                                                                                  for(int idx=0; idx<3; idx=idx+1){
                                                                                                      digitalWrite(yellowPin, HIGH);
                                                                                                      delay(yellowTime);
                                                                                                      digitalWrite(yellowPin, LOW);
                                                                                                      delay(yellowTime);
                                                                                                  }

                                                                                                  idx=idx+1 can be written shorthand as idx+=1:

                                                                                                  for(int idx=0; idx<3; idx+=1){
                                                                                                      digitalWrite(yellowPin, HIGH);
                                                                                                      delay(yellowTime);
                                                                                                      digitalWrite(yellowPin, LOW);
                                                                                                      delay(yellowTime);
                                                                                                  }

                                                                                                  The increment operator can also be used. Normally the post-increment operator idx++:

                                                                                                  for(int idx=0; idx<3; idx++){
                                                                                                      digitalWrite(yellowPin, HIGH);
                                                                                                      delay(yellowTime);
                                                                                                      digitalWrite(yellowPin, LOW);
                                                                                                      delay(yellowTime);
                                                                                                  }

                                                                                                  We can update our sketch to use a for loop to blink the yellow and red LED 3 times and 2 times respectively:

                                                                                                  int yellowPin = 6;
                                                                                                  int redPin = 9;
                                                                                                  int yellowTime = 500;
                                                                                                  int redTime = 500;
                                                                                                  
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(yellowPin, OUTPUT);
                                                                                                    pinMode(redPin, OUTPUT);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    for(int idx=0; idx<3; idx++){
                                                                                                  	digitalWrite(yellowPin, HIGH);
                                                                                                    	delay(yellowTime);
                                                                                                    	digitalWrite(yellowPin, LOW);
                                                                                                    	delay(yellowTime);
                                                                                                    }
                                                                                                    
                                                                                                    for (int idx=0; idx<2; idx++){
                                                                                                    	digitalWrite(redPin, HIGH);
                                                                                                    	delay(redTime);
                                                                                                    	digitalWrite(redPin, LOW);
                                                                                                    	delay(redTime);
                                                                                                    }
                                                                                                  }

                                                                                                  We can use the Serial Monitor to examine changes in a loop variable and for convenience the for loop will be put in the setup function so it is only run once:

                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup(){
                                                                                                    Serial.begin(9600);  
                                                                                                  
                                                                                                    for(int idx=0; idx<3; idx++){
                                                                                                      Serial.print("idx: ");
                                                                                                      Serial.println(idx);
                                                                                                      delay(delayTime);
                                                                                                    }
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                  
                                                                                                  }

                                                                                                  The result is shown on the Serial Monitor. If the Tinkercad emulation is ran, you will visualise the output from the for loop proceeding including the 1000 ms delayTime.

                                                                                                  We can look at only the even numbers of idx by incrementing by 2 instead of 1:

                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup(){
                                                                                                    Serial.begin(9600);  
                                                                                                  
                                                                                                    for(int idx=0; idx<10; idx+=2){
                                                                                                      Serial.print("idx: ");
                                                                                                      Serial.println(idx);
                                                                                                      delay(delayTime);
                                                                                                    }
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                  
                                                                                                  }

                                                                                                  By default we are inclusive of the initialisation boundary and exclusive of the final boundary. If we want to instead be inclusive of the upper bound we can use less than or equal <= to opposed to less than < :

                                                                                                  int delayTime=1000;
                                                                                                  
                                                                                                  void setup(){
                                                                                                    Serial.begin(9600);  
                                                                                                  
                                                                                                    for(int idx=0; idx<=10; idx+=2){
                                                                                                      Serial.print("idx: ");
                                                                                                      Serial.println(idx);
                                                                                                      delay(delayTime);
                                                                                                    }
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                  
                                                                                                  }

                                                                                                  If we initialise idx to 1 instead of 0, this will give all the odd numbers instead:

                                                                                                  int delayTime=1000;
                                                                                                  
                                                                                                  void setup(){
                                                                                                    Serial.begin(9600);  
                                                                                                  
                                                                                                    for(int idx=1; idx<=10; idx+=2){
                                                                                                      Serial.print("idx: ");
                                                                                                      Serial.println(idx);
                                                                                                      delay(delayTime);
                                                                                                    }
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                  
                                                                                                  }

                                                                                                  It is also possible to create a for loop decrementing from the initialisation variable:It is also possible to create a for loop decrementing from the initialisation variable:

                                                                                                  It is also possible to create a for loop decrementing from the initialisation variable, to do this we use the greater than > instead of less than < conditional operator in the condition and decrement opposed to increment idx– or idx-=1 for a step decrement or idx-=2 for a 2 step decrement:

                                                                                                  int delayTime=1000;
                                                                                                  
                                                                                                  void setup(){
                                                                                                    Serial.begin(9600);  
                                                                                                  
                                                                                                    for(int idx=10; idx>0; idx-=2){
                                                                                                      Serial.print("idx: ");
                                                                                                      Serial.println(idx);
                                                                                                      delay(delayTime);
                                                                                                    }
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                  
                                                                                                  }

                                                                                                  Once again we are inclusive of the initialisation boundary and exclusive of the final boundary. To change this we can use greater than or equal to >= opposed to greater than > in our condition:

                                                                                                  int delayTime=1000;
                                                                                                  
                                                                                                  void setup(){
                                                                                                    Serial.begin(9600);  
                                                                                                  
                                                                                                    for(int idx=10; idx>=0; idx-=2){
                                                                                                      Serial.print("idx: ");
                                                                                                      Serial.println(idx);
                                                                                                      delay(delayTime);
                                                                                                    }
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                  
                                                                                                  }

                                                                                                  It is less common but possible to create two loop variables and check two conditions:

                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup(){
                                                                                                    Serial.begin(9600);  
                                                                                                  
                                                                                                    for(int idx=0, idy=7; idx<10 && idy<10 ; idx++ && idy++){
                                                                                                      Serial.print("idx: ");
                                                                                                      Serial.print(idx);
                                                                                                      Serial.print(" idy: ");
                                                                                                      Serial.println(idy);
                                                                                                      delay(delayTime);
                                                                                                    }
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                  
                                                                                                  }

                                                                                                  Note the expression idx++ && idy++ will carry out idx++ execute the code block and then carry out idy++.

                                                                                                  In the example above we used and && and therefore executed the code block in the for loop only when both conditions were true. We can instead use or || to run the code block in the for loop when either one of the conditions are true:

                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup(){
                                                                                                    Serial.begin(9600);  
                                                                                                  
                                                                                                    for(int idx=0, idy=7; idx<10 || idy<10 ; idx++ && idy++){
                                                                                                      Serial.print("idx: ");
                                                                                                      Serial.print(idx);
                                                                                                      Serial.print(" idy: ");
                                                                                                      Serial.println(idy);
                                                                                                      delay(delayTime);
                                                                                                    }
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                  
                                                                                                  }

                                                                                                  If the loop variable idx is used within the loop there is a slight nuance between idx++ (post-increment) and ++idx (pre-increment).

                                                                                                  If we use x += y++ when x=0 and y=1 then we take the original value of y=1. Then assign x to the original value of x + the original value of y i.e. x=0+1=1. Then we increment y giving y=2:

                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup(){
                                                                                                    Serial.begin(9600);  
                                                                                                  
                                                                                                    for(int idx=0, idy=1; idx<3 && idy<5 ; idx += idy++){
                                                                                                      Serial.print("idx: ");
                                                                                                      Serial.print(idx);
                                                                                                      Serial.print(" idy: ");
                                                                                                      Serial.println(idy);
                                                                                                      delay(delayTime);
                                                                                                    }
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                  
                                                                                                  }

                                                                                                  If we use x += ++y when x=0 and y=1 then we increment y=1 to y=2. Then assign x to the original value of x + the increment value of y i.e. x=0+2=2:

                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup(){
                                                                                                    Serial.begin(9600);  
                                                                                                  
                                                                                                    for(int idx=0, idy=1; idx<3 && idy<4 ; idx += ++idy){
                                                                                                      Serial.print("idx: ");
                                                                                                      Serial.print(idx);
                                                                                                      Serial.print(" idy: ");
                                                                                                      Serial.println(idy);
                                                                                                      delay(delayTime);
                                                                                                    }
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                  
                                                                                                  }

                                                                                                  Tutorial 17: While Loops

                                                                                                  So far we have seen a for loop of the form:

                                                                                                  for(initialisation statement; condition statement; increment expression){
                                                                                                      code block statement 1;
                                                                                                      code block statement 2;
                                                                                                  }

                                                                                                  This executes the code block for a desired number of times.

                                                                                                  We have also looked at conditional logic using an if branch of the form:

                                                                                                  if(condition expression){
                                                                                                      code block statement 1;
                                                                                                      code block statement 2;
                                                                                                  }

                                                                                                  And seen that this executes the code only once if the condition is satisfied.

                                                                                                  We also have the while loop which is similar to the if branch:

                                                                                                  while(condition expression){
                                                                                                      code block statement 1;
                                                                                                      code block statement 2;
                                                                                                  }

                                                                                                  This will execute the code block if the condition is satisfied and will repeatedly execute the code in the code block until the condition is not satisfied.

                                                                                                  If the condition is always true for example, involves a variable than never changes the loop may run forever:

                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup(){
                                                                                                    Serial.begin(9600);  
                                                                                                  
                                                                                                    while(true){
                                                                                                      Serial.println("Hello");
                                                                                                      delay(delayTime);
                                                                                                    }
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                  
                                                                                                  }

                                                                                                  Notice that the code is in the setup function but behaves as it is in the loop function. This is because the loop function is essentially executed as an infinite loop.

                                                                                                  A while loop can always be set up in place of a for loop. To do so we need to initialise a variable before the while loop. This variable will be included as part of the while loop condition expression and a statement within the while loop must be included which increments the expression. For example:

                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup(){
                                                                                                    Serial.begin(9600);  
                                                                                                  
                                                                                                    int idx=0;
                                                                                                    while(idx<3){
                                                                                                      Serial.print("idx: ");
                                                                                                      Serial.println(idx);
                                                                                                      delay(delayTime);
                                                                                                      idx++;
                                                                                                    }
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                  
                                                                                                  }

                                                                                                  The syntax of a for loop is usually cleaner and a for loop is preferred over a while loop when carrying out a loop for a known number of times.

                                                                                                  On the other hand when a loop involves a condition around external sensor data for example or an unknown amount of time when awaiting a response from a user, we may not know the precise number of iterations that the loop is going to be carried out. In such cases a for loop is insufficient and we must use a while loop to loop while the condition is true.

                                                                                                  Let's look at this using our Potentiometer circuit from earlier.

                                                                                                  In the void loop the variable potVal is assigned. This is used as part of the condition expression for our while loop:

                                                                                                  int potPin = A0;
                                                                                                  int potVal;
                                                                                                  float potVolt;
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(potPin, INPUT);
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                    potVal = analogRead(potPin);
                                                                                                    potVolt = (float) potVal*5./1023.;
                                                                                                    
                                                                                                    Serial.print("potVal: ");
                                                                                                    Serial.print(potVal);
                                                                                                    Serial.print(" potVol: ");
                                                                                                    Serial.println(potVolt);
                                                                                                    delay(delayTime);
                                                                                                    
                                                                                                    while(potVal>800){
                                                                                                      Serial.println("High potVal");
                                                                                                      delay(delayTime);
                                                                                                    }
                                                                                                    
                                                                                                    
                                                                                                  }

                                                                                                  Notice that when potVal is below a certain value, than the code block within the while loop is not executed:

                                                                                                  When the potentiometer is turned and potVal reaches a value of 800 we enter the while loop:

                                                                                                  Notice that there is no statement to reassign the value of potVal within thewhile loop and therefore when the potentiometer is moved, the value of potVal is not updated to reflect this change. For this reason we are stuck within an infinite while loop…

                                                                                                  To rectify this we can update the value of potVal within the for loop by reassigning it to a new reading from potPin:

                                                                                                  int potPin = A0;
                                                                                                  int potVal;
                                                                                                  float potVolt;
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(potPin, INPUT);
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                    potVal = analogRead(potPin);
                                                                                                    potVolt = (float) potVal*5./1023.;
                                                                                                    
                                                                                                    Serial.print("potVal: ");
                                                                                                    Serial.print(potVal);
                                                                                                    Serial.print(" potVol: ");
                                                                                                    Serial.println(potVolt);
                                                                                                    delay(delayTime);
                                                                                                    
                                                                                                    while(potVal>800){
                                                                                                    	Serial.println("High potVal");
                                                                                                      delay(delayTime);
                                                                                                      potVal = analogRead(potPin);
                                                                                                    }
                                                                                                    
                                                                                                    
                                                                                                  }

                                                                                                  Tutorial 18: Reading Numbers from the Serial Monitor

                                                                                                  In the Arduino IDE the Serial Monitor should be set to "No Line Ending" in order to read numbers and strings from the Serial Monitor. Tinkercad is correctly configured with these settings.

                                                                                                  Quite often we will want our Arduino sketch to:

                                                                                                  1. Ask the user for a number.
                                                                                                  2. wait for the user to input a number.
                                                                                                  3. parse the input number as an int or float.
                                                                                                  4. use that number within an Arduino for example change the intensity level of an LED.

                                                                                                  To ask for a number we use the Serial class function print or println for example:

                                                                                                  Serial.println("Input a number: ");

                                                                                                  To wait for the user to input a number, we can use a while loop. When waiting for an input the Serial monitor is not available for use in another program. We can therefore use the value of the Serial class available function as part of our while loop expression. This has a bool value of false when not available or a bool value of true when available:

                                                                                                  while(Serial.available()==false){
                                                                                                  
                                                                                                  }

                                                                                                  Because the output of this function is a bool, this can also be shortened down to "while the serial is not available" by use of the not ! operator:

                                                                                                  while(!Serial.available()){
                                                                                                  
                                                                                                  }

                                                                                                  For a bool true and 1 are equivalent and false and 0 are equivalent, so the following form may also be used:

                                                                                                  while(Serial.available()==0){
                                                                                                  
                                                                                                  }

                                                                                                  In all of the cases above the code block is empty as we don't want to specify any further instructions while waiting.

                                                                                                  While waiting the Serial monitor will look like the following, awaiting a response from the user in the dialog box. The Serial will not be available until the user hits Send.

                                                                                                  We must then parse the number to an int or a float. To save this as a variable, we must assign a variable name using the appropriate datatype before hand. For example for an int:

                                                                                                  int userNum;
                                                                                                  userNum = Serial.parseInt();

                                                                                                  And for a float:

                                                                                                  float userNum;
                                                                                                  userNum = Serial.parseFloat();

                                                                                                  Let's create an Arduino sketch which asks the user for a number in the Serial Monitor, stores it as userNum and then displays it within the Serial Monitor:

                                                                                                  int userNum;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    Serial.begin(9600);
                                                                                                      
                                                                                                    // ask
                                                                                                    Serial.println("Input a number: ");
                                                                                                    
                                                                                                    // wait
                                                                                                    while(Serial.available()==false){
                                                                                                      
                                                                                                    }
                                                                                                    
                                                                                                    // parse
                                                                                                    userNum = Serial.parseInt();
                                                                                                    
                                                                                                    // use number in sketch
                                                                                                    Serial.print("You entered: ");
                                                                                                    Serial.println(userNum);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                  
                                                                                                  }

                                                                                                  The user will be prompted to input a number. The while loop will hold the dialog box open:

                                                                                                  Until the user inputs a number and clicks Send:

                                                                                                  Then the number the user input is displayed:

                                                                                                  Because this is within the setup function, it is only run once. If we return to our circuit from Tutorial 15:

                                                                                                  Instead of blinking the yellowLED 3 times and the redLED 2 times. We can ask the user how many times they want to blink each LED:

                                                                                                  int yellowPin = 6;
                                                                                                  int redPin = 9;
                                                                                                  int yellowTime = 500;
                                                                                                  int redTime = 500;
                                                                                                  
                                                                                                  int yellowBlinks;
                                                                                                  int redBlinks;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    Serial.begin(9600);
                                                                                                    pinMode(yellowPin, OUTPUT);
                                                                                                    pinMode(redPin, OUTPUT);
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                   // ask 
                                                                                                   Serial.println("number of yellow LED blinks: ");
                                                                                                   
                                                                                                    // wait
                                                                                                   while(!Serial.available()){
                                                                                                      
                                                                                                   }
                                                                                                    
                                                                                                    // parse
                                                                                                    yellowBlinks = Serial.parseInt();
                                                                                                    
                                                                                                    // ask 
                                                                                                    Serial.println("number of red LED blinks: ");
                                                                                                  
                                                                                                    // wait
                                                                                                    while(!Serial.available()){
                                                                                                  
                                                                                                    }
                                                                                                    
                                                                                                    // parse
                                                                                                    redBlinks = Serial.parseInt();
                                                                                                    
                                                                                                    //
                                                                                                    Serial.print("You specified ");
                                                                                                    Serial.print(yellowBlinks);
                                                                                                    Serial.print(" yellow blinks and ");
                                                                                                    Serial.print(redBlinks);
                                                                                                    Serial.print(" red blinks.");
                                                                                                    
                                                                                                    for(int idx=0; idx<yellowBlinks; idx++){
                                                                                                      digitalWrite(yellowPin, HIGH);
                                                                                                      delay(yellowTime);
                                                                                                      digitalWrite(yellowPin, LOW);
                                                                                                      delay(yellowTime);
                                                                                                    }
                                                                                                    
                                                                                                    for (int idx=0; idx<redBlinks; idx++){
                                                                                                    	digitalWrite(redPin, HIGH);
                                                                                                    	delay(redTime);
                                                                                                    	digitalWrite(redPin, LOW);
                                                                                                    	delay(redTime);
                                                                                                    }
                                                                                                  }
                                                                                                  

                                                                                                  In tutorial 14, we created a dimmer switch using a potentiometer. We can modify this circuit to remove the potentiometer and instead ask the user for their desired light intensity:

                                                                                                  To do this we can modify the sketch to:

                                                                                                  int virtualPotVal;
                                                                                                  
                                                                                                  int redPin = 6;
                                                                                                  float ledValf;
                                                                                                  int ledVal;
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup(){
                                                                                                    pinMode(redPin, OUTPUT);
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop(){
                                                                                                    
                                                                                                    // ask
                                                                                                    Serial.println("Enter a virtualPotVal between 0-1023: ");
                                                                                                    
                                                                                                    // wait
                                                                                                    while(!Serial.available()){
                                                                                                    
                                                                                                    }
                                                                                                    
                                                                                                    // parse
                                                                                                    virtualPotVal = Serial.parseInt();
                                                                                                    
                                                                                                    // light LED
                                                                                                    ledValf = 255. / 1023. * (float) virtualPotVal;
                                                                                                    ledVal = (int) ledValf;
                                                                                                    Serial.print("virtualPotVal: ");
                                                                                                    Serial.print(virtualPotVal);
                                                                                                    Serial.print(" ledVal: ");
                                                                                                    Serial.println(ledVal);
                                                                                                    delay(delayTime);
                                                                                                    
                                                                                                    analogWrite(redPin, ledVal);
                                                                                                  }
                                                                                                  

                                                                                                  Tutorial 19: Reading Strings from the Serial Monitor

                                                                                                  In the Arduino IDE the Serial Monitor should be set to "No Line Ending" in order to read numbers and strings from the Serial Monitor. Tinkercad is correctly configured with these settings.

                                                                                                  To read a string from the Serial Monitor we can use the function readString which returns what the user inputs into the Serial monitor as a string:

                                                                                                  String yourName;
                                                                                                  yourName = Serial.readString();

                                                                                                  Recall to read from the Serial Monitor we must:

                                                                                                  • Ask the user for a string.
                                                                                                  • wait for the user to input a string.
                                                                                                  • read the string.
                                                                                                  • use the string within an Arduino for example to select an LED by color.

                                                                                                  Let's create a basic sketch which asks the user for their name and then greets the user:

                                                                                                  String yourName;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    Serial.begin(9600);
                                                                                                    
                                                                                                    // ask
                                                                                                    Serial.println("Input your name: ");
                                                                                                    
                                                                                                    // wait
                                                                                                    while(!Serial.available()){
                                                                                                      
                                                                                                    }
                                                                                                    
                                                                                                    // read string
                                                                                                    yourName = Serial.readString();
                                                                                                    
                                                                                                    // print user greeting
                                                                                                    Serial.print("Hello ");
                                                                                                    Serial.println(yourName);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                  
                                                                                                  }

                                                                                                  The Serial Monitor will show our message:

                                                                                                  It will wait until we type into the dialog box and press Send:

                                                                                                  The code will then display the greeting:

                                                                                                  As this was included in the setup function, it is only ran once. If it was in the loop function, we would go round again.

                                                                                                  Let's create a sketch that will ask the user to select a color of LED and the number of the times they want to blink the LED for. This sketch will have to read a string and parse an int:

                                                                                                  int redPin = 11;
                                                                                                  int greenPin = 10;
                                                                                                  int bluePin = 9;
                                                                                                  int yellowPin = 6;
                                                                                                  
                                                                                                  int delayTime = 500;
                                                                                                  
                                                                                                  String selectedLED;
                                                                                                  int activePin;
                                                                                                  int numberBlinks;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    Serial.begin(9600);
                                                                                                    pinMode(redPin, OUTPUT);
                                                                                                    pinMode(greenPin, OUTPUT);
                                                                                                    pinMode(bluePin, OUTPUT);
                                                                                                    pinMode(yellowPin, OUTPUT);
                                                                                                  }
                                                                                                  
                                                                                                  
                                                                                                  void loop() {
                                                                                                    // ask
                                                                                                    Serial.print("Select color of the LED from ");
                                                                                                    Serial.println("red, yellow, green or blue: ");
                                                                                                  
                                                                                                    // wait
                                                                                                    while (!Serial.available()) {
                                                                                                  
                                                                                                    }
                                                                                                  
                                                                                                    // read String
                                                                                                    selectedLED = Serial.readString();
                                                                                                  
                                                                                                    // ask
                                                                                                    Serial.println("number of LED blinks: ");
                                                                                                  
                                                                                                    // wait
                                                                                                    while (!Serial.available()) {
                                                                                                  
                                                                                                    }
                                                                                                  
                                                                                                    // parse
                                                                                                    numberBlinks = Serial.parseInt();
                                                                                                  
                                                                                                    if (selectedLED == "red") {
                                                                                                      activePin = redPin;
                                                                                                      // print statement and blink LED if valid color of LED
                                                                                                      Serial.print("You have selected the ");
                                                                                                      Serial.print(selectedLED);
                                                                                                      Serial.print(" LED and ");
                                                                                                      Serial.print(numberBlinks);
                                                                                                      Serial.println(" number of blinks.");
                                                                                                  
                                                                                                      for (int idx = 0; idx < numberBlinks; idx++) {
                                                                                                        digitalWrite(activePin, HIGH);
                                                                                                        delay(delayTime);
                                                                                                        digitalWrite(activePin, LOW);
                                                                                                        delay(delayTime);
                                                                                                      }
                                                                                                    }
                                                                                                    else if (selectedLED == "green") {
                                                                                                      activePin = redPin;
                                                                                                      // print statement and blink LED if valid color of LED
                                                                                                      Serial.print("You have selected the ");
                                                                                                      Serial.print(selectedLED);
                                                                                                      Serial.print(" LED and ");
                                                                                                      Serial.print(numberBlinks);
                                                                                                      Serial.println(" number of blinks.");
                                                                                                  
                                                                                                      for (int idx = 0; idx < numberBlinks; idx++) {
                                                                                                        digitalWrite(activePin, HIGH);
                                                                                                        delay(delayTime);
                                                                                                        digitalWrite(activePin, LOW);
                                                                                                        delay(delayTime);
                                                                                                      }
                                                                                                    }
                                                                                                    else if (selectedLED == "blue") {
                                                                                                      activePin = bluePin;
                                                                                                      // print statement and blink LED if valid color of LED
                                                                                                      Serial.print("You have selected the ");
                                                                                                      Serial.print(selectedLED);
                                                                                                      Serial.print(" LED and ");
                                                                                                      Serial.print(numberBlinks);
                                                                                                      Serial.println(" number of blinks.");
                                                                                                  
                                                                                                      for (int idx = 0; idx < numberBlinks; idx++) {
                                                                                                        digitalWrite(activePin, HIGH);
                                                                                                        delay(delayTime);
                                                                                                        digitalWrite(activePin, LOW);
                                                                                                        delay(delayTime);
                                                                                                      }
                                                                                                    }
                                                                                                    else if (selectedLED == "yellow") {
                                                                                                      activePin = yellowPin;
                                                                                                      // print statement and blink LED if valid color of LED
                                                                                                      Serial.print("You have selected the ");
                                                                                                      Serial.print(selectedLED);
                                                                                                      Serial.print(" LED and ");
                                                                                                      Serial.print(numberBlinks);
                                                                                                      Serial.println(" number of blinks.");
                                                                                                  
                                                                                                      for (int idx = 0; idx < numberBlinks; idx++) {
                                                                                                        digitalWrite(activePin, HIGH);
                                                                                                        delay(delayTime);
                                                                                                        digitalWrite(activePin, LOW);
                                                                                                        delay(delayTime);
                                                                                                      }
                                                                                                    }
                                                                                                    else {
                                                                                                      Serial.println("Invalid color choice.");
                                                                                                    }
                                                                                                  
                                                                                                  }
                                                                                                  

                                                                                                  Since we are carrying out the same block of code for each color of LED selected which includes multiple lines and a for loop. We can simplify the sketch by creating our own custom function:

                                                                                                  void blinkLED() {
                                                                                                    // print statement and blink LED if valid color of LED
                                                                                                    Serial.print("You have selected the ");
                                                                                                    Serial.print(selectedLED);
                                                                                                    Serial.print(" LED and ");
                                                                                                    Serial.print(numberBlinks);
                                                                                                    Serial.println(" number of blinks.");
                                                                                                  
                                                                                                    for (int idx = 0; idx < numberBlinks; idx++) {
                                                                                                      digitalWrite(activePin, HIGH);
                                                                                                      delay(delayTime);
                                                                                                      digitalWrite(activePin, LOW);
                                                                                                      delay(delayTime);
                                                                                                    }
                                                                                                  }

                                                                                                  We can call this for each LED:

                                                                                                  int redPin = 11;
                                                                                                  int greenPin = 10;
                                                                                                  int bluePin = 9;
                                                                                                  int yellowPin=6;
                                                                                                  
                                                                                                  int delayTime = 500;
                                                                                                  
                                                                                                  String selectedLED;
                                                                                                  int activePin;
                                                                                                  int numberBlinks;
                                                                                                  
                                                                                                  
                                                                                                  void blinkLED(){
                                                                                                   // print statement and blink LED if valid color of LED
                                                                                                   Serial.print("You have selected the ");
                                                                                                   Serial.print(selectedLED);
                                                                                                   Serial.print(" LED and ");
                                                                                                   Serial.print(numberBlinks); 
                                                                                                   Serial.println(" number of blinks."); 
                                                                                                    
                                                                                                   for (int idx=0; idx<numberBlinks; idx++){
                                                                                                     digitalWrite(activePin, HIGH);
                                                                                                     delay(delayTime);
                                                                                                     digitalWrite(activePin, LOW);
                                                                                                     delay(delayTime);
                                                                                                    }  
                                                                                                  }
                                                                                                  
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    Serial.begin(9600);
                                                                                                    pinMode(redPin, OUTPUT);
                                                                                                    pinMode(greenPin, OUTPUT);
                                                                                                    pinMode(bluePin, OUTPUT);
                                                                                                    pinMode(yellowPin, OUTPUT);
                                                                                                  }
                                                                                                  
                                                                                                  
                                                                                                  void loop(){
                                                                                                  // ask 
                                                                                                   Serial.print("Select color of the LED from ");
                                                                                                   Serial.println("red, yellow, green or blue: "); 
                                                                                                    
                                                                                                   // wait
                                                                                                   while(!Serial.available()){
                                                                                                      
                                                                                                   }
                                                                                                    
                                                                                                   // read String
                                                                                                   selectedLED = Serial.readString();
                                                                                                    
                                                                                                   // ask
                                                                                                   Serial.println("number of LED blinks: ");
                                                                                                     
                                                                                                   // wait
                                                                                                   while(!Serial.available()){
                                                                                                      
                                                                                                   } 
                                                                                                  
                                                                                                   // parse
                                                                                                   numberBlinks = Serial.parseInt();
                                                                                                   
                                                                                                   if(selectedLED=="red"){
                                                                                                     	activePin=redPin;
                                                                                                     	blinkLED();
                                                                                                   } 
                                                                                                   else if(selectedLED=="green"){
                                                                                                    	activePin=redPin;
                                                                                                     	blinkLED();
                                                                                                   } 
                                                                                                   else if(selectedLED=="blue"){
                                                                                                    	activePin=bluePin;
                                                                                                     	blinkLED();
                                                                                                   }
                                                                                                   else if(selectedLED=="yellow"){
                                                                                                    	activePin=yellowPin;
                                                                                                     	blinkLED();
                                                                                                   }
                                                                                                   else{
                                                                                                      Serial.println("Invalid color choice.");
                                                                                                    }
                                                                                                  
                                                                                                  }
                                                                                                  

                                                                                                  The Tinkercad emulation is available here:

                                                                                                  Tutorial 20: Arduino and RBG LED

                                                                                                  The RBG LED is essentially a combination of a Red, Blue and Green LEDs. This can be seen by testing the RGB LED with a coin cell battery.

                                                                                                  The four pins on the RGB LED are Red, Ground, Green and Blue.

                                                                                                  Because each of these are individual LEDs, they should all be wired up with a current limiting resistor. The circuit at the top of the breadboard is equivalent to the circuit at the bottom of the breadboard.

                                                                                                  Let's wire this up to our Arduino Uno and create a sketch. In this sketch we will blink the redLED for 1 second:

                                                                                                  int redPin = 11;
                                                                                                  int bluePin = 10;
                                                                                                  int greenPin = 9;
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(redPin, OUTPUT);
                                                                                                    pinMode(greenPin, OUTPUT);
                                                                                                    pinMode(bluePin, OUTPUT);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    // red LED On
                                                                                                    digitalWrite(redPin, HIGH);
                                                                                                    digitalWrite(bluePin, LOW);
                                                                                                    digitalWrite(greenPin, LOW);
                                                                                                    delay(delayTime);
                                                                                                    
                                                                                                    // all LED Off
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    delay(delayTime);
                                                                                                  }

                                                                                                  The code to wait, then turn off all the LEDs and then wait can be combined into a function called flashLED and works in the same manner as before:

                                                                                                  int redPin = 11;
                                                                                                  int bluePin = 10;
                                                                                                  int greenPin = 9;
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void flashLED(){
                                                                                                    delay(delayTime);
                                                                                                    
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    digitalWrite(bluePin, LOW);
                                                                                                    digitalWrite(greenPin, LOW);
                                                                                                    delay(delayTime);
                                                                                                  }
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(redPin, OUTPUT);
                                                                                                    pinMode(greenPin, OUTPUT);
                                                                                                    pinMode(bluePin, OUTPUT);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    // red LED On
                                                                                                    digitalWrite(redPin, HIGH);
                                                                                                    digitalWrite(bluePin, LOW);
                                                                                                    digitalWrite(greenPin, LOW);
                                                                                                    flashLED();
                                                                                                  }

                                                                                                  Now we can have a look at turning the other LEDs on:

                                                                                                  int redPin = 11;
                                                                                                  int bluePin = 10;
                                                                                                  int greenPin = 9;
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void flashLED(){
                                                                                                    delay(delayTime);
                                                                                                    
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    digitalWrite(bluePin, LOW);
                                                                                                    digitalWrite(greenPin, LOW);
                                                                                                    delay(delayTime);
                                                                                                  }
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(redPin, OUTPUT);
                                                                                                    pinMode(greenPin, OUTPUT);
                                                                                                    pinMode(bluePin, OUTPUT);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    // red LED On
                                                                                                    digitalWrite(redPin, HIGH);
                                                                                                    digitalWrite(bluePin, LOW);
                                                                                                    digitalWrite(greenPin, LOW);
                                                                                                    flashLED();
                                                                                                    
                                                                                                    // blue LED On
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    digitalWrite(bluePin, HIGH);
                                                                                                    digitalWrite(greenPin, LOW);
                                                                                                    flashLED();
                                                                                                    
                                                                                                    // green LED On
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    digitalWrite(bluePin, LOW);
                                                                                                    digitalWrite(greenPin, HIGH);
                                                                                                    flashLED();
                                                                                                  }

                                                                                                  And from the Tinkercad emulation we can see the redLED flash, then the blueLED flash and then the greenLED flash:

                                                                                                  Let's now instead turn on two LEDs on simultaneously, green and blue for example. Notice that when we do so, we get a new color cyan.

                                                                                                  int redPin = 11;
                                                                                                  int bluePin = 10;
                                                                                                  int greenPin = 9;
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void flashLED(){
                                                                                                    delay(delayTime);
                                                                                                    
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    digitalWrite(bluePin, LOW);
                                                                                                    digitalWrite(greenPin, LOW);
                                                                                                    delay(delayTime);
                                                                                                  }
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(redPin, OUTPUT);
                                                                                                    pinMode(greenPin, OUTPUT);
                                                                                                    pinMode(bluePin, OUTPUT);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    // green and Blue LEDs On
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    digitalWrite(bluePin, HIGH);
                                                                                                    digitalWrite(greenPin, HIGH);
                                                                                                  }

                                                                                                  The physical reason for this is our eyes have low (blue sensitive), medium (green sensitive) and high (red sensitive) wavelength sensors and our brain maps intensity ratios detected as these three sensors to a color:

                                                                                                  When two LEDs are on at full brightess we get the secondary colors:

                                                                                                  • red + blue = magenta
                                                                                                  • green + blue = cyan
                                                                                                  • red + green = yellow

                                                                                                  When the three LEDs are on at full brightness we get:

                                                                                                  • red + green + blue = white

                                                                                                  The absence of light is darkness i.e. black.

                                                                                                  This can be visualised in the figure below.

                                                                                                  Let's update our sketch to cycle through these colors.

                                                                                                  int redPin = 11;
                                                                                                  int bluePin = 10;
                                                                                                  int greenPin = 9;
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void flashLED(){
                                                                                                    delay(delayTime);
                                                                                                    
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    digitalWrite(bluePin, LOW);
                                                                                                    digitalWrite(greenPin, LOW);
                                                                                                    delay(delayTime);
                                                                                                  }
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(redPin, OUTPUT);
                                                                                                    pinMode(greenPin, OUTPUT);
                                                                                                    pinMode(bluePin, OUTPUT);
                                                                                                    
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    Serial.println("Primary colors. (1 LED on.):");
                                                                                                    
                                                                                                    digitalWrite(redPin, HIGH);
                                                                                                    digitalWrite(bluePin, LOW);
                                                                                                    digitalWrite(greenPin, LOW);
                                                                                                    Serial.println("red LED on.");
                                                                                                    flashLED();
                                                                                                    
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    digitalWrite(bluePin, HIGH);
                                                                                                    digitalWrite(greenPin, LOW);
                                                                                                    Serial.println("blue LED on.");
                                                                                                    flashLED();
                                                                                                  
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    digitalWrite(bluePin, LOW);
                                                                                                    digitalWrite(greenPin, HIGH);
                                                                                                    Serial.println("green LED on.");
                                                                                                    flashLED();
                                                                                                    
                                                                                                    Serial.println();
                                                                                                    Serial.println("Secondary colors. (2 LEDs on.):");
                                                                                                    
                                                                                                    digitalWrite(redPin, HIGH);
                                                                                                    digitalWrite(bluePin, HIGH);
                                                                                                    digitalWrite(greenPin, LOW);
                                                                                                    Serial.println("magenta: red and green LEDs on.");
                                                                                                    flashLED();
                                                                                                    
                                                                                                    digitalWrite(redPin, HIGH);
                                                                                                    digitalWrite(bluePin, LOW);
                                                                                                    digitalWrite(greenPin, HIGH);
                                                                                                    Serial.println("yellow: red and green LEDs on.");
                                                                                                    flashLED();
                                                                                                    
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    digitalWrite(bluePin, HIGH);
                                                                                                    digitalWrite(greenPin, HIGH);
                                                                                                    Serial.println("cyan: blue and green LEDs on.");
                                                                                                    flashLED();
                                                                                                    
                                                                                                    Serial.println();
                                                                                                    Serial.println("All leds on:");
                                                                                                    
                                                                                                    digitalWrite(redPin, HIGH);
                                                                                                    digitalWrite(bluePin, HIGH);
                                                                                                    digitalWrite(greenPin, HIGH);
                                                                                                    Serial.println("white: red, blue and green LEDs on.");
                                                                                                    flashLED();
                                                                                                    
                                                                                                    Serial.println();
                                                                                                    Serial.println("All leds off:");
                                                                                                    digitalWrite(redPin, LOW);
                                                                                                    digitalWrite(bluePin, LOW);
                                                                                                    digitalWrite(greenPin, LOW);
                                                                                                    Serial.println("black: absence of light i.e. no LEDs on.");
                                                                                                    flashLED();
                                                                                                    
                                                                                                    Serial.println();
                                                                                                  }

                                                                                                  Tutorial 21: Arduino and RBG LED Color Mixing

                                                                                                  We have seen earlier that the Arduino pins marked with a ~ such as 3, 5, 6, 9, 10 and 11 also have the capability to use an analogWrite. Recall that must specify the pin to perform the analogWrite on as well a byte that ranges from 0-255 as previously discussed. For the RBG LED, we need to use 3 pins, one for each LED. This gives 0-255 possible values for redLEDVal, 0-255 possible values for blueLEDVal and 0-255 possible values for greenLEDVal i.e. 16777216 possible combinations. You may have seen these represented as RGB values (note the order off the pinout in our emulated LED is RBG) in a color picker.

                                                                                                  This is a purple color used in Microsoft Word. Let us update our sketch to use analogWrite opposed to digitalWrite for each LED within the RBG LED and try to reproduce this color:

                                                                                                  int redPin = 11;
                                                                                                  int bluePin = 10;
                                                                                                  int greenPin = 9;
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void flashLED(int redVal=0, int blueVal=0, int greenVal=0){
                                                                                                      
                                                                                                    analogWrite(redPin, redVal);
                                                                                                    analogWrite(bluePin, blueVal);
                                                                                                    analogWrite(greenPin, greenVal);
                                                                                                    delay(delayTime);
                                                                                                    
                                                                                                    Serial.print("redVal: ");
                                                                                                    Serial.print(redVal);
                                                                                                    Serial.print(", blueVal: ");
                                                                                                    Serial.print(blueVal);
                                                                                                    Serial.print(", greenVal: ");
                                                                                                    Serial.println(greenVal);
                                                                                                    
                                                                                                    analogWrite(redPin, 0);
                                                                                                    analogWrite(bluePin, 0);
                                                                                                    analogWrite(greenPin, 0);
                                                                                                    delay(delayTime);
                                                                                                  
                                                                                                  }
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(redPin, OUTPUT);
                                                                                                    pinMode(bluePin, OUTPUT);
                                                                                                    pinMode(greenPin, OUTPUT);
                                                                                                    
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {  
                                                                                                    flashLED(102, 204, 0);
                                                                                                  }

                                                                                                  Note that the color produced from the emulation or from an actual circuit may differ slightly from the expected color. This is due to the RBG LEDs being to an extent uncalibrated. Essentially there is a variance in the brightness of each LED and some RBG LEDs may be stronger in the blue for example. Calibration is usually done by tweaking the exact resistor values of the LED. Likewise when a camera is used to take a picture from a bright object such as a LED, the color will appear different as cameras tend to automatically adjust their capture settings in order to achieve an image which appears more sharp.

                                                                                                  We can update the sketch to ask the user for a redVal, blueVal and greenVal and flash the LED with the provided settings.

                                                                                                  int redPin = 11;
                                                                                                  int bluePin = 10;
                                                                                                  int greenPin = 9;
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  int redVal;
                                                                                                  int blueVal;
                                                                                                  int greenVal;
                                                                                                  
                                                                                                  void flashLED(int redVal=0, int blueVal=0, int greenVal=0){
                                                                                                      
                                                                                                    analogWrite(redPin, redVal);
                                                                                                    analogWrite(bluePin, blueVal);
                                                                                                    analogWrite(greenPin, greenVal);
                                                                                                    delay(delayTime);
                                                                                                    
                                                                                                    Serial.print("redVal: ");
                                                                                                    Serial.print(redVal);
                                                                                                    Serial.print(", blueVal: ");
                                                                                                    Serial.print(blueVal);
                                                                                                    Serial.print(", greenVal: ");
                                                                                                    Serial.println(greenVal);
                                                                                                    
                                                                                                    analogWrite(redPin, 0);
                                                                                                    analogWrite(bluePin, 0);
                                                                                                    analogWrite(greenPin, 0);
                                                                                                    delay(delayTime);
                                                                                                  
                                                                                                  }
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(redPin, OUTPUT);
                                                                                                    pinMode(bluePin, OUTPUT);
                                                                                                    pinMode(greenPin, OUTPUT);
                                                                                                    
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    // ask
                                                                                                    Serial.println("redVal: 0-255");
                                                                                                    
                                                                                                    // wait
                                                                                                    while(!Serial.available()){
                                                                                                    }
                                                                                                    
                                                                                                    // parse
                                                                                                    redVal = Serial.parseInt();
                                                                                                    
                                                                                                    // ask
                                                                                                    Serial.println("blueVal: 0-255");
                                                                                                    
                                                                                                    // wait
                                                                                                    while(!Serial.available()){
                                                                                                    }
                                                                                                    
                                                                                                    // parse
                                                                                                    blueVal = Serial.parseInt();  
                                                                                                    
                                                                                                    // ask
                                                                                                    Serial.println("greenVal: 0-255");
                                                                                                    
                                                                                                    // wait
                                                                                                    while(!Serial.available()){
                                                                                                    }
                                                                                                    
                                                                                                    // parse
                                                                                                    greenVal = Serial.parseInt();
                                                                                                    
                                                                                                    flashLED(redVal, blueVal, greenVal);
                                                                                                  }

                                                                                                  The RBG LED is essentially the basis of a pixel i.e. a tiny square that has a RBG LED. The screen on your laptop or phone is essentially an array of these pixels and images are essentially a numeric collection of RGB integer values for each pixel.

                                                                                                  Tutorial 22-23: Arduino and an Active Buzzer (Piezo)

                                                                                                  So far we have used a LED as an example of an output device. This output device converts electricity into light. Another output device is the buzzer which instead converts electricity into sound energy.

                                                                                                  In the Elegoo kit there is an active buzzer and also a passive buzzer. Out of the two buzzers, the active buzzer is easiest to use as it has a fixed frequency 2300±500 Hz and all you do is plug it in and apply a voltage in a pretty much identical manner to a digitalWrite on a LED. The passive buzzer on the other hand changes its tone with respect to the duration of the electronic signal applied to it.

                                                                                                  On Tinkercad there is only a Piezo which is essentially a passive buzzer. We can use this to emulate the functionality of an active buzzer although the frequency at the duration we switch it on won't be similar to the physical active buzzer and therefore will sound completely different.

                                                                                                  The active buzzer in the Elegoo kit has an operational voltage of 3.5-5.5 V and an electric current of 2.5 mA. We can therefore wire it directly up to the Arduino. If however we wanted to limit it to 4 V, we would need to apply a current limiting resistor, similar to how we do with an LED:

                                                                                                  We could therefore select a 2 kΩ from our kit.

                                                                                                  We can write a basic sketch prompting the user to input an int and then use an if condition to activate the buzzer if the int is above 100. This emulates for example an input device such as a potentiometer:

                                                                                                  int myNum;
                                                                                                  int buzzPin = 8;
                                                                                                  int delayTime = 2000;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    Serial.begin(9600);
                                                                                                    pinMode(buzzPin, OUTPUT);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    // ask
                                                                                                    Serial.println("Please input a number:");
                                                                                                    
                                                                                                    // wait
                                                                                                    while(!Serial.available()){
                                                                                                    }
                                                                                                    
                                                                                                    // parse int
                                                                                                    myNum = Serial.parseInt();
                                                                                                    
                                                                                                    // if positive:
                                                                                                    if(myNum>100){
                                                                                                    	digitalWrite(buzzPin, HIGH);
                                                                                                    	delay(delayTime);
                                                                                                    	digitalWrite(buzzPin, LOW);
                                                                                                    	delay(delayTime);
                                                                                                    }
                                                                                                  }
                                                                                                  int myNum;
                                                                                                  int buzzPin = 8;
                                                                                                  int potPin = A5;
                                                                                                  int potVal;
                                                                                                  
                                                                                                  int delayTime = 2000;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    Serial.begin(9600);
                                                                                                    pinMode(buzzPin, OUTPUT);
                                                                                                    pinMode(potPin, INPUT);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    potVal = analogRead(potPin);
                                                                                                    Serial.println(potVal);
                                                                                                  
                                                                                                    if(potVal>500){
                                                                                                    	digitalWrite(buzzPin, HIGH);
                                                                                                    	delay(delayTime);
                                                                                                    	digitalWrite(buzzPin, LOW);
                                                                                                    	delay(delayTime);
                                                                                                    }
                                                                                                  }

                                                                                                  Limited changes in the tone can be heard if the duration the active buzzer is on and off changes. This is even more limited in the emulation as we are instead using a Piezo (passive buzzer) opposed to an active buzzer.

                                                                                                  Tutorial 24: Arduino and a Passive Buzzer (Piezo)

                                                                                                  The passive buzzer will change its frequency depending on the duration it is switched on and off for. Unlike the active buzzer, this duration is normally within the microseconds time range. A microsecond is 1 thousandth of a millisecond and this is in turn 1 thousand of a second.

                                                                                                  There is another function called delayMicroseconds which allows for a use of microsecond scaled delay. This passive buzzer seems to work within the range of 60-10000 microseconds.

                                                                                                  Let's create a for loop exploring the differences in tone as the duration on and off increases as there are a large number of possible of delayTimeOn and delayTimeOff values, a larger step will be used to cycle through the nested for loop. You can modify the step in the sketch:

                                                                                                  int myNum;
                                                                                                  int buzzPin = 8;
                                                                                                  int longDelayTime = 1000;
                                                                                                  void setup()
                                                                                                  {
                                                                                                    Serial.begin(9600);
                                                                                                    pinMode(buzzPin, OUTPUT);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    for(int delayTimeOn=60; delayTimeOn<=10000; delayTimeOn+=25){
                                                                                                        for(int delayTimeOff=60; delayTimeOff<=10000; delayTimeOff+=25){
                                                                                                        digitalWrite(buzzPin, HIGH);
                                                                                                        delayMicroseconds(delayTimeOn);
                                                                                                        digitalWrite(buzzPin, LOW);
                                                                                                        delayMicroseconds(delayTimeOff);
                                                                                                      }
                                                                                                    }
                                                                                                    
                                                                                                    delay(longDelayTime);
                                                                                                  }

                                                                                                  Let's now create a circuit that has a passive buzzer and two potentiometers:

                                                                                                  We want the first buzzer to control the duration of the onTime. We must calculate an equation for a straight line so the lower end of onPotVal i.e. 0 corresponds to an onTimeInt of 60 microseconds and the upper end of onPotVal i.e. 1023.

                                                                                                  To get the gradient we require these two datapoints:

                                                                                                  To get the intercept, we can use this gradient and one of the datapoints:

                                                                                                  Therefore our equation is:

                                                                                                  And since it is essentially the same relation:

                                                                                                  We can now make our sketch:

                                                                                                  int myNum;
                                                                                                  int buzzPin = 8;
                                                                                                  int onPotPin = A0;
                                                                                                  int offPotPin = A1;
                                                                                                  
                                                                                                  int onPotVal;
                                                                                                  int offPotVal;
                                                                                                  float onTime;
                                                                                                  float offTime;
                                                                                                  int onTimeInt;
                                                                                                  int offTimeInt;
                                                                                                  
                                                                                                  int longDelayTime = 1000;
                                                                                                  void setup()
                                                                                                  {
                                                                                                    Serial.begin(9600);
                                                                                                    pinMode(buzzPin, OUTPUT);
                                                                                                    pinMode(onPotPin, INPUT);
                                                                                                    pinMode(offPotPin, INPUT);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    onPotVal = analogRead(onPotPin);
                                                                                                    offPotVal = analogRead(offPotPin);
                                                                                                    
                                                                                                    onTime = (float) onPotVal * (10000. - 60.)/(1023. - 0.) + 60;
                                                                                                    offTime = (float) offPotVal * (10000. - 60.)/(1023. - 0.) + 60;
                                                                                                  
                                                                                                    onTimeInt = (int) onTime;
                                                                                                    offTimeInt = (int) offTime;
                                                                                                    
                                                                                                    digitalWrite(buzzPin, HIGH);
                                                                                                    delayMicroseconds(onTimeInt);
                                                                                                    digitalWrite(buzzPin, LOW);
                                                                                                    delayMicroseconds(offTimeInt);
                                                                                                  }

                                                                                                  This gives us an on dial and off dial which we can use to modify the tone. The Tinkercad circuit is availble here:

                                                                                                  Instead of using the function digitalWrite, we can use the function tone. This has three input arguments, the pin, the frequency and the duration:

                                                                                                  tone(pin, frequency, duration);
                                                                                                  delayMicroseconds(delayTime);

                                                                                                  This guide will also include some content from an additional video tutorial:

                                                                                                  We will use our basic circuit from before.

                                                                                                  This sounds very similar to the audio on a Nintendo Entertainment System (NES) released in 1983 which used a similar simple passive buzzer as an audio output device. Note that the Tinkercad emulation will distort the audio with respect to a physical buzzer:

                                                                                                  int myNum;
                                                                                                  int buzzPin = 8;
                                                                                                  int longDelayTime = 2000;
                                                                                                  void setup()
                                                                                                  {
                                                                                                    Serial.begin(9600);
                                                                                                    pinMode(buzzPin, OUTPUT);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    tone(buzzPin, 659, 100);
                                                                                                    delay(150);
                                                                                                    tone(buzzPin, 659, 100);
                                                                                                    delay(300);
                                                                                                    tone(buzzPin, 659, 100);
                                                                                                    delay(300);
                                                                                                    tone(buzzPin, 523, 100);
                                                                                                    delay(100);
                                                                                                    tone(buzzPin, 659, 100);
                                                                                                    delay(300);
                                                                                                    tone(buzzPin, 784, 100);
                                                                                                    delay(550);
                                                                                                    tone(buzzPin, 392, 100);
                                                                                                    delay(1000);
                                                                                                  }

                                                                                                  A number of Arduino Sketches are available for popular songs that were out on the NES and SNES.

                                                                                                  These sketches tend to define a series of notes and then play them sequentially to make the desired tune.

                                                                                                  Tutorial 25-26: Arduino and PhotoResistor

                                                                                                  The internal resistance of a photoresistor decreases with light intensity. The emulated resistor gives an internal resistance of 180 kΩ in darkness and 506 Ω in light.

                                                                                                  We can only measure voltage in an Arduino. In order to measure a voltage value that is roughly proportional to this resistance, we need to setup a voltage divider. We can then use one of our analog inputs to measure the voltage in the middle of this voltage divider. Generally we want to setup the photoresistor up in series with a resistor that has approximately a resistance in the middle of the two extremes of the photoresistors resistance as that will give the highest dynamic range.

                                                                                                  int photoPin = A0;
                                                                                                  int photoVal;
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(photoPin, INPUT);
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    photoVal = analogRead(photoPin);
                                                                                                    Serial.print("photoVal: ");
                                                                                                    Serial.println(photoVal);
                                                                                                    delay(delayTime);
                                                                                                  }

                                                                                                  Let's try:

                                                                                                  The closest resistor to this is 100 kΩ however with this resistor we don't have much dynamic range:

                                                                                                  366

                                                                                                  996

                                                                                                  Let's instead try a 50 kΩ resistor:

                                                                                                  223

                                                                                                  999

                                                                                                  We get more dynamic range but it still isn't great. Let's instead try a 5 kΩ resistor:

                                                                                                  28

                                                                                                  929

                                                                                                  As we see this combination covers the highest dynamic range.

                                                                                                  Let's combine a photoresistor in a voltage divider with two indicator LEDs. The aim of this circuit is to indicate between darkness when the room lights are off, in which case the green LED should be illuminated and the red LED should be switched off. This sensor will also be able to sense a brightness level when the room lights are on, say for the case of emulation this is 500 and in this case the red LED should be illuminated and the green LED should be switched off.

                                                                                                  int photoPin = A0;
                                                                                                  int photoVal;
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  int redLED = 11;
                                                                                                  int greenLED = 10;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(photoPin, INPUT);
                                                                                                    pinMode(redLED, OUTPUT);
                                                                                                    pinMode(greenLED, OUTPUT);
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    photoVal = analogRead(photoPin);
                                                                                                    Serial.print("photoVal: ");
                                                                                                    Serial.println(photoVal);
                                                                                                    delay(delayTime);
                                                                                                    
                                                                                                    if(photoVal>500){
                                                                                                    	digitalWrite(redLED, LOW);
                                                                                                      digitalWrite(greenLED, HIGH);
                                                                                                    }
                                                                                                    else{
                                                                                                      digitalWrite(redLED, HIGH);
                                                                                                      digitalWrite(greenLED, LOW);
                                                                                                    }
                                                                                                  }

                                                                                                  Let's now say instead of wanting two LEDs to indicate the brightness level, that we instead want to incorporate a passive buzzer or Piezo and we want to change the tone of the passive buzzer, so that a higher frequency is heard in response to more light. This will behave essentially like a Geiger counter but measure light intensity instead of radiation.

                                                                                                  The circuit will look like the following:

                                                                                                  Recall that the upper and lower limits of the photodiode photoVal in this configuration are 28 and 929 respectively and the range of buzzTime for the passive buzzer (piezo) is 60-10000. We want the lowest frequency at the highest photoVal. We can therefore calculate the gradient from these two datapoints:

                                                                                                  And then substitute one of the datapoints into the equation for the straight line with the gradient to calculate the intercept:

                                                                                                  Therefore:

                                                                                                  And our equation is:

                                                                                                  int photoPin = A0;
                                                                                                  int photoVal;
                                                                                                  
                                                                                                  int buzzPin = 9;
                                                                                                  float fbuzzTime;
                                                                                                  int buzzTime;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(photoPin, INPUT);
                                                                                                    pinMode(buzzPin, OUTPUT);
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    photoVal = analogRead(photoPin);
                                                                                                    fbuzzTime = -11.032 * (float) photoVal + 10308.728;
                                                                                                    buzzTime = (int) fbuzzTime;
                                                                                                    
                                                                                                    digitalWrite(buzzPin, HIGH);
                                                                                                    delayMicroseconds(buzzTime);
                                                                                                    digitalWrite(buzzPin, LOW);
                                                                                                    delayMicroseconds(buzzTime);
                                                                                                    
                                                                                                    Serial.print("buzzTime: ");
                                                                                                    Serial.println(buzzTime);
                                                                                                  }

                                                                                                  The Tinkercad emulation is here and when the intensity slider above the photodiode changes, the sound of the buzzer indicates the light intensity as expected:

                                                                                                  Tutorial 27: Arduino and Pushbuttons and Pull Up or Pull Down Resistors

                                                                                                  If the 5V pin is connected to a 10 kΩ and no path to ground is available, then there is no current flowing across the resistor and a reading at the other end of the resistor will therefore be 5V:

                                                                                                  If now a ground connection is made, a current flows through the circuit and across the resistor and therefore a reading at the other end of the resistor will now read 0V:

                                                                                                  Instead of using an analogRead we can use a digital Read. Just to recap:

                                                                                                  int val;
                                                                                                  val = digitalRead(pin);

                                                                                                  For a digitalRead val ranges from 0-1

                                                                                                  int val;
                                                                                                  val = analogRead(pin);

                                                                                                  For an analogRead val ranges from 0-1023

                                                                                                  digitalWrite(pin, LOW);
                                                                                                  digitalWrite(pin, HIGH);

                                                                                                  For a digitalWrite we can write the values LOW (0) or HIGH (1)

                                                                                                  int val;
                                                                                                  analogWrite(pin, val);

                                                                                                  For an analogWrite, we can write the values between 0-255

                                                                                                  A digitalRead of the top circuit reads a 1 and the bottom circuit reads a 0 respectively.

                                                                                                  int readPin = A0;
                                                                                                  int delayTime = 1000;
                                                                                                  int readVal;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(readPin, INPUT);
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    readVal = digitalRead(readPin);
                                                                                                    Serial.print("readVal: ");
                                                                                                    Serial.println(readVal);
                                                                                                    delay(delayTime);
                                                                                                  }

                                                                                                  Now let's examine a push button.

                                                                                                  • When the button is not pressed, there is no connection between pin 14 and pin 16 i.e. the red and black wire are not connected.
                                                                                                  • When the button is pressed, there is a connection between pin 14 and pin 16 i.e. the red and black wire are connected.

                                                                                                  The two legs of the button on column 14 are internally connected and the two legs of the button on column 16 are likewise internally connected.

                                                                                                  Let's incorporate a push button into our circuit above.

                                                                                                  • Notice that now when the button is not pressed, there is no connection to ground and no current runs through the resistor. A digitalWrite of pin A0 will therefore read 1 corresponding to +5 V.
                                                                                                  • When the button is pressed, there is a connection to ground and the current runs across the resistor. A digitalWrite of pin A0 will therefore read 0 corresponding to 0 V i.e. ground.

                                                                                                  This can be seen by running the emulation and pressing the button:

                                                                                                  Now let's use this button to turn an LED On or Off.

                                                                                                  Recall that when the button is pressed the digitalRead value is 0 and when the button is not pressed the digitalRead value is 1.

                                                                                                  • We therefore want to perform a digitalWrite of HIGH to the red LED when the digitalRead of pin A0 is 0.
                                                                                                  • And want to perform a digitalWrite of LOW to the red LED when the digitalRead of pin A0 is 1.
                                                                                                  int readPin = A0;
                                                                                                  int readVal;
                                                                                                  
                                                                                                  int redPin = 11;
                                                                                                  
                                                                                                  int delayTime = 100;
                                                                                                  
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(readPin, INPUT);
                                                                                                    pinMode(redPin, OUTPUT);
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    readVal = digitalRead(readPin);
                                                                                                    Serial.print("readVal: ");
                                                                                                    Serial.println(readVal);
                                                                                                    delay(delayTime);
                                                                                                    
                                                                                                    if(readVal==0){
                                                                                                    	digitalWrite(redPin, HIGH);
                                                                                                    }
                                                                                                    else{
                                                                                                      digitalWrite(redPin, LOW);
                                                                                                    }
                                                                                                  }

                                                                                                  Tutorial 28: Arduino and Push Button Toggle Switch

                                                                                                  In the circuit above, we have to hold down the button in order to keep the red LED illuminated which is quite inconvenient.

                                                                                                  This image has an empty alt attribute; its file name is image-146.png

                                                                                                  Let's look at the same circuit but instead code the button to operate as a toggle switch. In order to do this we need to think of how do we want the button to work:

                                                                                                  We are interested in the cases highlighted in the square box which are:

                                                                                                  • buttonReleased and ledState off in which case we want to switch the LED on.
                                                                                                  • buttonReleased and ledState on in which case we want to switch the LED off.

                                                                                                  In order to monitor buttonReleased we will need to read two values from the button. The value now and the previous value. Let's call these readValPrevious and readValNow. We also need to record the ledState i.e. whether the LED is off or on.

                                                                                                  int readPin = A0;
                                                                                                  int readValPrevious=1;
                                                                                                  int readValNow;
                                                                                                  int redPin = 11;
                                                                                                  
                                                                                                  int ledState = 0;
                                                                                                  int delayTime = 100;
                                                                                                  
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(readPin, INPUT);
                                                                                                    pinMode(redPin, OUTPUT);
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    readValNow = digitalRead(readPin);
                                                                                                    Serial.print("readValNow: ");
                                                                                                    Serial.println(readValNow);
                                                                                                    
                                                                                                    if(readValPrevious==0 && readValNow==1){
                                                                                                      // The button has been released.
                                                                                                      if(ledState==0){
                                                                                                        	// if the LED is off turn it on
                                                                                                      	digitalWrite(redPin, HIGH);
                                                                                                      	ledState=1;
                                                                                                      }
                                                                                                      else{
                                                                                                        	// else the LED is on so turn it off
                                                                                                          digitalWrite(redPin, LOW);
                                                                                                      	ledState=0;
                                                                                                      }
                                                                                                    }
                                                                                                    
                                                                                                    readValPrevious = readValNow;
                                                                                                    Serial.print("readValPrevious: ");
                                                                                                    Serial.println(readValPrevious);
                                                                                                    delay(delayTime);
                                                                                                    
                                                                                                  }

                                                                                                  Tutorial 29: Using Push Buttons to Create a Dimmable LED

                                                                                                  Let's now look at using an analogWrite to the red LED and using one push button to increase the brightness of the LED and the second push button to decrease the brightness of the LED. In addition we will also make a noise using a passive buzzer (piezo) to warn the user when they have reached the limits of each switch and no changes are therefore being made to the LED.

                                                                                                  int upPin = A0;
                                                                                                  int downPin = A1;
                                                                                                  
                                                                                                  int readUpVal;
                                                                                                  int readDownVal;
                                                                                                  int redPin = 11;
                                                                                                  
                                                                                                  int redVal = 0;
                                                                                                  
                                                                                                  int buzzPin = 9;
                                                                                                  
                                                                                                  int delayTime = 100;
                                                                                                  int microDelayTime = 500;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(upPin, INPUT);
                                                                                                    pinMode(downPin, INPUT);
                                                                                                    pinMode(redPin, OUTPUT);
                                                                                                    pinMode(buzzPin, OUTPUT);
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    readUpVal = digitalRead(upPin);
                                                                                                    readDownVal = digitalRead(downPin);
                                                                                                    Serial.print("readUpVal: ");
                                                                                                    Serial.println(readUpVal);
                                                                                                    Serial.print("readDownVal: ");
                                                                                                    Serial.println(readDownVal);
                                                                                                    
                                                                                                    if(readUpVal==0 && redVal<255){
                                                                                                  	redVal+=5;
                                                                                                    }
                                                                                                    else if(readDownVal==0 && redVal>0){
                                                                                                      redVal-=5;
                                                                                                    }
                                                                                                    else if(readUpVal==0 && redVal==255){
                                                                                                  	digitalWrite(buzzPin, HIGH);
                                                                                                          delayMicroseconds(microDelayTime);
                                                                                                    	digitalWrite(buzzPin, LOW);
                                                                                                          delayMicroseconds(microDelayTime);   
                                                                                                    }
                                                                                                    else if(readDownVal==0 && redVal==0){
                                                                                                  	digitalWrite(buzzPin, HIGH);
                                                                                                          delayMicroseconds(microDelayTime);
                                                                                                    	digitalWrite(buzzPin, LOW);
                                                                                                          delayMicroseconds(microDelayTime);   
                                                                                                    }
                                                                                                    Serial.print("redVal: ");
                                                                                                    Serial.println(redVal);
                                                                                                    
                                                                                                    analogWrite(redPin, redVal);
                                                                                                    delay(delayTime);
                                                                                                    
                                                                                                  }

                                                                                                  Tutorial 30-31: Arduino and Servo

                                                                                                  The servo motor SG90 included in the Elegoo Super Starter Kit has an output voltage of 4.8-6 V (see the datasheet) meaning it can be powered directly from the 5 V pin and ground pin of the Arduino. Other servos may require an external power supply. We also need a pin to communicate with the servo, in this case we will use pin 9.

                                                                                                  To use a servo we need to include the servo library. A library is essentially a separate code file which defines a class of an object that we wish to use. Before moving on it might be insightful to discuss what a class is.

                                                                                                  Each object has a class, which initially can be conceptualised as an abstract blueprint which defines how to create a new object and outlines the properties and functionality behind an object.

                                                                                                  Let's take for example something we are used to interacting with every day such as the class house. An Architect may create a blueprint for a house, this blueprint is an abstract object, that we as an end user cannot interact with. It will also outline the functionality of the house such as the doors in the house frontDoorOpen or frontDoorClose, the windows in the house frontWindowOpen or frontWindowClose, the central heating system controls setHouseTemperature and the sewage controls flushToilet.

                                                                                                  A construction company can follow the instructions in this blueprint called House to create one or multiple houses. Each house will be constructed using the same blueprint but each object created will be unique. To indicate that each house is unique, the construction company will assign each new house object, a name during construction which we know as a post code. This process is known as initialisation or instantiation, for simplicity let's create two houses called houseZero and houseOne respectively.

                                                                                                  The end user (homeowner or tenant) will be able to uniquely interact with their own house object using the functions outlined in the blueprint House. These functions are methods for interacting with a house object. For example the owner of houseZero will be able to leave their house by calling the method houseZero.frontDoorOpen() and houseZero.frontDoorClose() and set the temperature on their central heating system by calling the method houseZero.setHouseTemperature(24). These interactions with houseZero will not change the functionality of houseOne although the behaviour for both houses are defined in the same House class.

                                                                                                  Libraries are typically included at the top of an Arduino sketch using the #include pre-processor directive. Note that this line does not end with a semi-colon:

                                                                                                  #include <Servo.h>

                                                                                                  Once we have included the library we must create an instance of our class. We have done this many times before for example when declaring a variable myNum as an instance of the int class:

                                                                                                  int myNum;

                                                                                                  Likewise we are declaring that myServo is an instance of the Servo class:

                                                                                                  Servo myServo;

                                                                                                  Once we have created an instance, we can use a number of functions, otherwise known as methods and these methods were defined in the objects blueprint (class). In this case we will use two, attach to attach the instance myServo to a physical pin on the Arduino and write, to write an angle to the myServo:

                                                                                                  myServo.attach(pin);
                                                                                                  myServo.write(angle);

                                                                                                  We can create a basic sketch to attach myServo to pin 9 and to write the angle of myServo to angle 0 and angle 30 respectively. A longer delayTime is added to ensure that myServo has enough time to completely move to the angle:

                                                                                                  #include <Servo.h>
                                                                                                  
                                                                                                  int servoPin = 9;
                                                                                                  int servoPos;
                                                                                                  Servo myServo;
                                                                                                  int delayTime = 5000;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    myServo.attach(servoPin);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    servoPos = 0;
                                                                                                    myServo.write(servoPos);
                                                                                                    delay(delayTime);
                                                                                                    
                                                                                                    servoPos = 30;
                                                                                                    myServo.write(servoPos);
                                                                                                    delay(delayTime);
                                                                                                  }

                                                                                                  In C++ we can also create an array of integer values for example an array of 8 integer values corresponding to servoPositions:

                                                                                                  int servoPositions[8] = {0, 15, 30, 45, 60, 90, 120, 160};

                                                                                                  We use square brackets [ ] to specify the size of the array and use braces { } to enclose all the values of the array using a comma , as a delimiter.

                                                                                                  Let's use this array of servoPositions and also use the SerialMonitor to print the servoPosition as myServo moves to the desired location:

                                                                                                  #include <Servo.h>
                                                                                                  
                                                                                                  int servoPin = 9;
                                                                                                  int servoPositions[8] = {0, 15, 30, 45, 60, 90, 120, 160};
                                                                                                  int servoPos;
                                                                                                  Servo myServo;
                                                                                                  int delayTime = 5000;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    myServo.attach(servoPin);
                                                                                                  	Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    for(int idx=0; idx<8; idx++){
                                                                                                      servoPos = servoPositions[idx];
                                                                                                      myServo.write(servoPos);
                                                                                                      Serial.print("servoPos: ");
                                                                                                      Serial.println(servoPos);
                                                                                                      delay(delayTime);
                                                                                                    }
                                                                                                  }

                                                                                                  Let's now use myServo in combination with a photoresistor setup as a voltage divider.

                                                                                                  Let's assume that myServoPos runs between an angle of 0 to an angle of 160 (just shy of 180) and we seen earlier that the photoresistor setup as a voltage divider with a 5 kΩ resistor gives a reading photoVal of 28 in darkness to 929 in full brightness.

                                                                                                  Let's assume we want myServoPos=160 for photoVal=28 for darkness and myServoPos=0 for a photoVal=929 for a high light level and we therefore want myServo to rotate clockwise in response to a higher light intensity. Then we can calculate the gradient from these two points:

                                                                                                  And substitute one of these points and gradient into the equation for a straight line:

                                                                                                  Therefore our equation is:

                                                                                                  Let's incorporate this into our sketch:

                                                                                                  #include <Servo.h>
                                                                                                  int servoPin=9;
                                                                                                  float servoPosF;
                                                                                                  int servoPos;
                                                                                                  Servo myServo;
                                                                                                  
                                                                                                  int photoPin = A0;
                                                                                                  int photoVal;
                                                                                                  
                                                                                                  int delayTime = 3000;
                                                                                                  
                                                                                                  void setup() {
                                                                                                    Serial.begin(9600);
                                                                                                    myServo.attach(servoPin);
                                                                                                    pinMode(photoPin, INPUT);  
                                                                                                  }
                                                                                                  
                                                                                                  void loop() {
                                                                                                    photoVal = analogRead(photoPin);
                                                                                                    Serial.print("photoVal: ");
                                                                                                    Serial.println(photoVal);
                                                                                                    servoPosF = -0.178 * (float) photoVal + 165.362;
                                                                                                    Serial.print("ServoPosF: ");
                                                                                                    Serial.println(servoPosF);
                                                                                                    servoPos = (int) servoPosF;
                                                                                                    Serial.print("ServoPos: ");
                                                                                                    Serial.println(servoPos);
                                                                                                    myServo.write(servoPos);
                                                                                                    delay(delayTime);
                                                                                                  }

                                                                                                  And so at darkness we have:

                                                                                                  And brightness we have:

                                                                                                  Tutorial 32-33: Joysticks

                                                                                                  The Joystick from the Elegoo kit looks like the following.

                                                                                                  There is no direct Tinkercad equivalent. However under the hood, the joystick is essentially 2 potentiometers and a switch with a common 5V and ground connection. i.e. something roughly equivalent to the following:

                                                                                                  With the same 5 pins going from the breadboard to the Arduino highlighted:

                                                                                                  We can call the pins xPin, yPin and sPin which will all be configured to be INPUT pins. We can read xVal and yVal by using analogRead on xPin and yPin respectively. When the joystick is centred, both xVal and yVal read around 512, indicating that both potentiometers attached to xPin and yPin respectively are centred.

                                                                                                  When the joystick is moved to the left, xVal reads 0 indicating that the potentiometer attached to xPin is switched all the way to the left. When the joystick is moved to the right, xVal reads 1023 indicating that the potentiometer attached to xPin is switched all the way to the right.

                                                                                                  When the joystick is moved to the top, yVal reads 0 indicating that the potentiometer attached to yPin is switched all the way to the left. When the joystick is moved to the bottom, yVal reads 1023 indicating that the potentiometer attached to yPin is switched all the way to the right.

                                                                                                  Pressing and holding the middle button will activate the switch and the value sVal will switch from 0 (not pressed) to 1 (pressed).

                                                                                                  int xPin = A0;
                                                                                                  int yPin = A1;
                                                                                                  int sPin = 2;
                                                                                                  int xVal;
                                                                                                  int yVal;
                                                                                                  int sVal;
                                                                                                  int delayTime = 200;
                                                                                                  
                                                                                                  void setup() {
                                                                                                    pinMode(xPin, INPUT);
                                                                                                    pinMode(yPin, INPUT);
                                                                                                    pinMode(sPin, INPUT);
                                                                                                    digitalWrite(sPin, HIGH);
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop() {
                                                                                                    xVal = analogRead(xPin);
                                                                                                    yVal = analogRead(yPin);
                                                                                                    sVal = digitalRead(sPin);
                                                                                                    Serial.print("xVal: ");
                                                                                                    Serial.print(xVal);
                                                                                                    Serial.print(" yVal: ");
                                                                                                    Serial.print(yVal);
                                                                                                    Serial.print(" sVal: ");
                                                                                                    Serial.println(sVal);
                                                                                                    delay(delayTime);
                                                                                                  }

                                                                                                  This can partially be emulated in Tinkercad using 2 potentiometers and a switch:

                                                                                                  Let's look at using this JoyStick to control other components such as two servos. If these servos are mechanically attached to each other, we can use the joystick to orientate an object attached to the servos such as a laser pointer. The joysticks middle button i.e. the switch will activate the buzzer and reset the position of each of the potentiometers to 0 when pressed:

                                                                                                  So let's examine the relationship between xVal, which will will conceptualise as a potentiometer and xServoPos. Let's assume we want the independent variable xServoPos which ranges between 0-180 to vary with respect to the independent variable xVal which ranges from 0-1023.

                                                                                                  To calculate the gradient we need two datapoints:

                                                                                                  And because one of the datapoints is 0, the intercept is therefore also 0:

                                                                                                  And therefore:

                                                                                                  And because it is essentially the same relationship:

                                                                                                  #include <Servo.h>
                                                                                                  
                                                                                                  int xPin = A0;
                                                                                                  int yPin = A1;
                                                                                                  int sPin = 2;
                                                                                                  int xServoPin = 9;
                                                                                                  int yServoPin = 10;
                                                                                                  int buzzPin = 7;
                                                                                                  int xAngle;
                                                                                                  int yAngle;
                                                                                                  int xVal;
                                                                                                  int yVal;
                                                                                                  int sVal;
                                                                                                  int delayTime = 200;
                                                                                                  Servo xServo;
                                                                                                  Servo yServo;
                                                                                                  
                                                                                                  void setup() {
                                                                                                    pinMode(xPin, INPUT);
                                                                                                    pinMode(yPin, INPUT);
                                                                                                    pinMode(sPin, INPUT);
                                                                                                    pinMode(xServoPin, OUTPUT);
                                                                                                    pinMode(yServoPin, OUTPUT);
                                                                                                    pinMode(buzzPin, OUTPUT);
                                                                                                    xServo.attach(9);
                                                                                                    yServo.attach(10);
                                                                                                    digitalWrite(sPin, HIGH);
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop() {
                                                                                                    xVal = analogRead(xPin);
                                                                                                    xAngle = (180. / 1023.) * (float) xVal;
                                                                                                    xServo.write(xAngle);
                                                                                                    yVal = analogRead(yPin);
                                                                                                    yAngle = (180. / 1023.) * (float) yVal;
                                                                                                    yServo.write(yAngle);
                                                                                                    sVal = digitalRead(sPin);
                                                                                                    if(sVal==0){
                                                                                                      tone(buzzPin, 659, 100);
                                                                                                      delay(150);
                                                                                                    }
                                                                                                    Serial.print("xVal: ");
                                                                                                    Serial.print(xVal);
                                                                                                    Serial.print(" yVal: ");
                                                                                                    Serial.print(yVal);
                                                                                                    Serial.print(" sVal: ");
                                                                                                    Serial.println(sVal);
                                                                                                    Serial.print("xAngle: ");
                                                                                                    Serial.print(xAngle);
                                                                                                    Serial.print(" yAngle: ");
                                                                                                    Serial.println(yAngle);
                                                                                                    delay(delayTime);
                                                                                                  }

                                                                                                  Tutorial 34: Arduino AnalogWrite of INPUT Pins

                                                                                                  Although the analogWrite is more commonly used with an OUTPUT pin, it may also be used with an INPUT pin. What this will do internally within the Arduino circuit is essentially bring a pull-up resistor to 5V and this can be used in preference to our own pull up resistor when using a simple component such as a push button.

                                                                                                  int buttonPin = 2;
                                                                                                  int buttonVal;
                                                                                                  int delayTime = 100;
                                                                                                  
                                                                                                  void setup(){
                                                                                                    pinMode(buttonPin, INPUT);
                                                                                                    // Bringing internally into the circuit a pull-up resistor
                                                                                                    digitalWrite(buttonPin, HIGH);
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    buttonVal = digitalRead(buttonPin);
                                                                                                    Serial.print("buttonVal: ");
                                                                                                    Serial.println(buttonVal);
                                                                                                    delay(delayTime);
                                                                                                  }

                                                                                                  Tutorial 35: Arduino and Stepper Motor

                                                                                                  Typically a device such as a stepper motor needs more power and needs to be powered externally from the Arduino. The ground connection of the Arduino and the power device need to be internally connected.

                                                                                                  Besides the power and ground pin, a stepper motor takes four GPIO pins and in this case we will use pins 8, 9, 10 and 11.

                                                                                                  To use a stepper motor we use the Stepper.h library and must include it at the top of our code using:

                                                                                                  #include <Stepper.h>

                                                                                                  We need to create an instance that we can interact with:

                                                                                                  Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

                                                                                                  Here there are 5 input arguments, the stepsPerRevolution which is motor specific and the order of the pins connected.

                                                                                                  We can then set the motor speed using the function setSpeed and step using the function step. Enough delay time must be allowed in the sketch for the motor to finish moving. An example is given below:

                                                                                                  #include <Stepper.h>
                                                                                                  int stepsPerRevolution = 2048; // motor specific
                                                                                                  int motSpeed = 10;
                                                                                                  int delayTime = 500;
                                                                                                  Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    Serial.begin(9600);
                                                                                                    myStepper.setSpeed(motSpeed);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    // rotate clockwise 1/4 of a revolution
                                                                                                    myStepper.step(stepsPerRevolution/4);
                                                                                                    delay(delayTime);
                                                                                                    // rotate anti-clockwise 1/4 of a revolution
                                                                                                    myStepper.step(-stepsPerRevolution/4);
                                                                                                    delay(delayTime);
                                                                                                  }

                                                                                                  Note this sketch is supposed to move the motor 1/4 of a turn clockwise and then 1/4 of a turn anti-clockwise but it seems that the emulation in Tinkercad is limited:

                                                                                                  Tutorial 36: Tilt Switch

                                                                                                  A tilt switch can be conceptualised as metal ball in the can. In some tilt switches a single ball is present the bottom of the can and completes a connection between the two ends of the can allowing current to flow through the switch. The tilt ball switch in the Elegoo kit is of this form and reads 0 when upright and 1 when tilted.

                                                                                                  In other switches such as the SW200D in the Tinkercad emulation, a dual ball configuration is used. In contrast, the switch has no connection when upright and reads 1 and 0 when tilted.

                                                                                                  An example of using this switch alongside some indicator LEDs is shown below:

                                                                                                  int tiltSwitchPin = 2;
                                                                                                  int redPin = 7;
                                                                                                  int greenPin = 8;
                                                                                                  int tiltSwitchVal;
                                                                                                  
                                                                                                  void setup() {
                                                                                                    pinMode(greenPin, OUTPUT);
                                                                                                    pinMode(redPin, OUTPUT);
                                                                                                    pinMode(tiltSwitchPin, INPUT);
                                                                                                    digitalWrite(tiltSwitchPin, HIGH);
                                                                                                  
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop() {
                                                                                                    tiltSwitchVal = digitalRead(tiltSwitchPin);
                                                                                                    Serial.print("tiltSwitchVal: ");
                                                                                                    Serial.println(tiltSwitchVal);
                                                                                                    if(tiltSwitchVal==1){
                                                                                                      digitalWrite(greenPin, HIGH);
                                                                                                      digitalWrite(redPin, LOW);
                                                                                                    }
                                                                                                    else{
                                                                                                      digitalWrite(greenPin, LOW);
                                                                                                      digitalWrite(redPin, HIGH);
                                                                                                    }
                                                                                                  }

                                                                                                  Note if using the other type of tilt switch such as the tilt switch present in the Elegoo Starter Kit, tiltSwitchVal will be inverted and therefore the if condition must be changed to 0 opposed to 1.

                                                                                                  Tutorial 37: Arduino, L293D Motor Driver and DC Motor

                                                                                                  The L293D is a 16 pin chip. The start of the chip is indicated with the small circle above pin 1. This chip has the capability to drive 2 DC motors. We will only focus on driving 1 DC motor and therefore only use the bottom half of the chip. You can see there is a rough equivalence in the pins if the chip is rotated upside down.

                                                                                                  We have the power (pin 8) and the ground (pin 4 or 5). A DC motor requires more power than the Arduino 5V pin so we must use an external power supply. The Arduino must also be grounded to this same power supply. I had to also attach pin 16 to this power supply (otherwise Tinkercad blew up the L293D, this was not needed for 1 motor when using actual hardware).

                                                                                                  Next are three pins which attach from the L293D to the GPIO pins on the Arduino. Pin 1 is the Enable 1 and 2 which Enables the Input 1/Output 1 and Input 2/Output 2 pins on the L293D. Pin 2 is Input 1 and Pin 7 is Input 2.

                                                                                                  These pins expect the pinMode of the Arduino to be an OUTPUT and the L293D is waiting to receive this OUTPUT as an INPUT with respect to the L293D itself.

                                                                                                  From the Arduinos perspective, Enable 1 and 2 (L293D pin 1) attached to pin 5 is a speedPin and the two pins (L293D pin 2) attached to pin 4 and (L293D pin 7) attached to pin 3 are directional pins dir1Pin and dir2Pin respectively. The motor will rotate one direction if dir1Pin has a digitalWrite to HIGH and dir2Pin has a digitalWrite to LOW and the reverse direction in the inverse situation.

                                                                                                  Finally pin 3 and pin 6, the output pins of the L293D connect to the 2 input pins of the DC motor:

                                                                                                  Putting the full circuit together:

                                                                                                  int speedPin = 5;
                                                                                                  int dir1Pin = 4;
                                                                                                  int dir2Pin = 3;
                                                                                                  int mSpeed = 255;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(speedPin, OUTPUT);
                                                                                                    pinMode(dir1Pin, OUTPUT);
                                                                                                    pinMode(dir2Pin, OUTPUT);
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    digitalWrite(dir1Pin, HIGH);
                                                                                                    digitalWrite(dir2Pin, LOW);
                                                                                                    analogWrite(speedPin, mSpeed);
                                                                                                  }

                                                                                                  Tutorial 38: Using a Tilt Switch to Cut Off a DC Motor

                                                                                                  We can add a tilt switch to the DC motor and code in a safety mechanism to cut the motor if the fan tilts.

                                                                                                  int speedPin = 5;
                                                                                                  int dir1Pin = 4;
                                                                                                  int dir2Pin = 3;
                                                                                                  int mSpeed ;
                                                                                                  int tiltSwitchPin = 2;
                                                                                                  int tiltSwitchVal;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(speedPin, OUTPUT);
                                                                                                    pinMode(dir1Pin, OUTPUT);
                                                                                                    pinMode(dir2Pin, OUTPUT);
                                                                                                    pinMode(tiltSwitchPin, INPUT);
                                                                                                    digitalWrite(tiltSwitchPin, HIGH);
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    tiltSwitchVal = digitalRead(tiltSwitchPin); 
                                                                                                    if(tiltSwitchVal==1){
                                                                                                      mSpeed = 255;
                                                                                                    }
                                                                                                    else{
                                                                                                      mSpeed = 0;
                                                                                                    }
                                                                                                  
                                                                                                    analogWrite(speedPin, mSpeed);
                                                                                                    digitalWrite(dir1Pin, HIGH);
                                                                                                    digitalWrite(dir2Pin, LOW);
                                                                                                  }

                                                                                                  Tutorial 39: Using a Joystick to Control a DC Motor

                                                                                                  Essentially we want to use the up-down axis of the joystick to control the motor speed and direction. Recall the up-down axis can be conceptualised as a potentiometer with a value yPos ranging from 0-1023.

                                                                                                  We want a motor speed mSpeed of 0 when the yPos is centred, that is yPos is equal to 512. When the joystick is turned upwards i.e. with a yPos at the maximum value of 255, we want the mSpeed to be at a maximum of 255 and for the motor to rotate clockwise. In contrast when the joystick is turned downwards, we want the motor to be at a maximum speed of 255 and for the motor to rotate counter-clockwise. All other values should be intermediate.

                                                                                                  Let's look at values where yPos is above 512 and our two end points i.e. yVal=513 and mSpeed=0 and yVal=1023 and mSpeed=255. Let's calculate an equation for a straight line:

                                                                                                  To calculate the gradient from these two datapoints we can use:

                                                                                                  And we can substitute one of these points into the straight line to get the intercept:

                                                                                                  This gives the equation for yPos>512 as:

                                                                                                  And because the problem is symmetrical about the y-axis, for yPos<512:

                                                                                                  We can create our sketch with these equations:

                                                                                                  int xPin = A0;
                                                                                                  int yPin = A1;
                                                                                                  int sPin = 2;
                                                                                                  int xVal;
                                                                                                  int yVal;
                                                                                                  int sVal;
                                                                                                  int speedPin = 11;
                                                                                                  int dir1Pin = 10;
                                                                                                  int dir2Pin = 9;
                                                                                                  int mSpeed ;
                                                                                                  int delayTime = 20;
                                                                                                  
                                                                                                  void setup() {
                                                                                                    pinMode(xPin, INPUT);
                                                                                                    pinMode(yPin, INPUT);
                                                                                                    pinMode(sPin, INPUT);
                                                                                                    pinMode(speedPin, OUTPUT);
                                                                                                    pinMode(dir1Pin, OUTPUT);
                                                                                                    pinMode(dir2Pin, OUTPUT);
                                                                                                    digitalWrite(sPin, HIGH);
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop() {
                                                                                                    xVal = analogRead(xPin);
                                                                                                    yVal = analogRead(yPin);
                                                                                                    sVal = digitalRead(sPin);
                                                                                                    Serial.print("xVal: ");
                                                                                                    Serial.print(xVal);
                                                                                                    Serial.print(" yVal: ");
                                                                                                    Serial.print(yVal);
                                                                                                    Serial.print(" sVal: ");
                                                                                                    Serial.println(sVal);
                                                                                                    
                                                                                                    if(yVal==512){
                                                                                                      mSpeed = 0;
                                                                                                      analogWrite(speedPin, mSpeed);
                                                                                                      digitalWrite(dir1Pin, HIGH);
                                                                                                    	digitalWrite(dir2Pin, LOW);
                                                                                                    }
                                                                                                    else if(yVal<512){
                                                                                                      mSpeed = -0.5 * (float) yVal + 256.5;
                                                                                                      analogWrite(speedPin, mSpeed);
                                                                                                      digitalWrite(dir1Pin, HIGH);
                                                                                                    	digitalWrite(dir2Pin, LOW);
                                                                                                    }
                                                                                                    else if(yVal>512){
                                                                                                      mSpeed = 0.5 * (float) yVal - 256.5;
                                                                                                      analogWrite(speedPin, mSpeed);
                                                                                                      digitalWrite(dir1Pin, LOW);
                                                                                                    	digitalWrite(dir2Pin, HIGH);
                                                                                                    }
                                                                                                    
                                                                                                    delay(delayTime);
                                                                                                  }

                                                                                                  Tutorial 40: Controlling DC Motor Speed and Direction with Push Buttons

                                                                                                  Let's incorporate two push buttons an upButton and a downButton and write a sketch which uses these buttons to seamlessly control motor speed mSpeed reaching an off state and switching direction.

                                                                                                  Recall that the motor has a working threshold speed mSpeed at say 100. We want to therefore approach this problem at four different mSpeed values.

                                                                                                  mSpeed==0: This is the starting point and we want to select direction and jump to a mSpeed of 100 when a button is pressed.

                                                                                                  mSpeed==100: We want to either press a button in the opposite direction to bring mSpeed down to 0 or we want to press a button in the supporting direction to increment mSpeed gradually for example in steps of 5.

                                                                                                  mSpeed>100 and mSpeed<255: We want to increment or decrement mSpeed gradually in steps of 5 if a button in the supporting or opposing direction is pressed.

                                                                                                  mSpeed==255: This is the maximum value for an analogWrite. We only want opposing buttons to decrement mSpeed in a gradual step of 5 when pressed.

                                                                                                  int speedPin = 5;
                                                                                                  int dir1Pin = 4;
                                                                                                  int dir2Pin = 3;
                                                                                                  
                                                                                                  int upButtonPin = 8;
                                                                                                  int downButtonPin = 9;
                                                                                                  
                                                                                                  int upButtonVal;
                                                                                                  int downButtonVal;
                                                                                                  
                                                                                                  int mSpeed = 0;
                                                                                                  
                                                                                                  int delayTime = 100;
                                                                                                  
                                                                                                  int mDir = 1;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(speedPin, OUTPUT);
                                                                                                    pinMode(dir1Pin, OUTPUT);
                                                                                                    pinMode(dir2Pin, OUTPUT);
                                                                                                  
                                                                                                    pinMode(upButtonPin, INPUT);
                                                                                                    digitalWrite(upButtonPin, HIGH);
                                                                                                    pinMode(downButtonPin, INPUT);
                                                                                                    digitalWrite(downButtonPin, HIGH);
                                                                                                  
                                                                                                    digitalWrite(dir1Pin, HIGH);
                                                                                                    digitalWrite(dir2Pin, LOW);
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    upButtonVal = digitalRead(upButtonPin);
                                                                                                    downButtonVal = digitalRead(downButtonPin);
                                                                                                  
                                                                                                  
                                                                                                    Serial.print("upButtonVal: ");
                                                                                                    Serial.print(upButtonVal);
                                                                                                    Serial.print(" downButtonVal: ");
                                                                                                    Serial.print(downButtonVal);
                                                                                                    Serial.print(" mSpeed: ");
                                                                                                    Serial.println(mSpeed);
                                                                                                  
                                                                                                    delay(delayTime);
                                                                                                  
                                                                                                  
                                                                                                    if (mSpeed == 0) {
                                                                                                      if (upButtonVal == 0) {
                                                                                                        digitalWrite(dir1Pin, HIGH);
                                                                                                        digitalWrite(dir2Pin, LOW);
                                                                                                        mDir = 1;
                                                                                                        mSpeed = 100;
                                                                                                      }
                                                                                                      else if (downButtonVal == 0) {
                                                                                                        digitalWrite(dir1Pin, LOW);
                                                                                                        digitalWrite(dir2Pin, HIGH);
                                                                                                        mDir = -1;
                                                                                                        mSpeed = 100;
                                                                                                      }
                                                                                                    }
                                                                                                  
                                                                                                    else if (mSpeed == 100) {
                                                                                                      if (upButtonVal == 0 && mDir == 1) {
                                                                                                        mSpeed += 5;
                                                                                                      }
                                                                                                      else if (upButtonVal == 0 && mDir == -1) {
                                                                                                        mSpeed = 0;
                                                                                                      }
                                                                                                      else if (downButtonVal == 0 && mDir == -1) {
                                                                                                        mSpeed += 5;
                                                                                                      }
                                                                                                      else if (downButtonVal == 0 && mDir == 1) {
                                                                                                        mSpeed = 0;
                                                                                                      }
                                                                                                    }
                                                                                                  
                                                                                                    else if (mSpeed > 100 && mSpeed < 255) {
                                                                                                      if (upButtonVal == 0 && mDir == 1) {
                                                                                                        mSpeed += 5;
                                                                                                      }
                                                                                                      else if (upButtonVal == 0 && mDir == -1) {
                                                                                                        mSpeed -= 5;
                                                                                                      }
                                                                                                      else if (downButtonVal == 0 && mDir == 1) {
                                                                                                        mSpeed -= 5;
                                                                                                      }
                                                                                                      else if (downButtonVal == 0 && mDir == -1) {
                                                                                                        mSpeed += 5;
                                                                                                      }
                                                                                                    }
                                                                                                  
                                                                                                    else if (mSpeed == 255) {
                                                                                                      if (downButtonVal == 0 && mDir == 1) {
                                                                                                        mSpeed -= 5;
                                                                                                      }
                                                                                                      else if (upButtonVal == 0 && mDir == -1) {
                                                                                                        mSpeed -= 5;
                                                                                                      }
                                                                                                    }
                                                                                                  
                                                                                                    analogWrite(speedPin, mSpeed);
                                                                                                  }

                                                                                                  Tutorial 41: Binary and Hexadecimal Revisited

                                                                                                  Data is stored in a computer using a series of switches which at its core is binary. One of the main problems when using binary directly is it consists of a long series of characters for example the decimal value 221 is B11011101. When transcribing such a large number it very easy to make a mistake. Instead we group four of the switches together and use a Hexadecimal character. In this case 1101 is D and 1101 is D. Hexadecimal makes it relatively easy to transcribe any value up to 255 using 2 hexadecimal characters with the prefix 0x but it can also be readily converted into Binary to see what is going on at the hardware level with respect to the actual physical switches. It is insightful to have a look at the conversions between the binary, hexadecimal and decimal numbering systems for 8 bytes (0-255 values which we have used frequently for example when using the analogWrite).

                                                                                                  byte myByte =  B00000000;
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    if(myByte==256){
                                                                                                    	myByte=0;
                                                                                                    }
                                                                                                    Serial.print("B");
                                                                                                    Serial.print(myByte, BIN);
                                                                                                    Serial.print(" 0x");
                                                                                                    Serial.print(myByte, HEX);
                                                                                                    Serial.print(" ");
                                                                                                    Serial.println(myByte);
                                                                                                    
                                                                                                    myByte += 1;
                                                                                                    delay(delayTime);
                                                                                                  }

                                                                                                  Tutorial 42-47: Arduino and a 74HC595 Parallel Shift Register

                                                                                                  The 74HC595 is a parallel Shift register. We can essentially use this to increase our output pins on our Arduino by 8.

                                                                                                  Let's have a look at wiring this up. We have 3 pins which we connect to GPIO pins on the Arduino.

                                                                                                  Pin 14 of the 74HC595 which is our dataPin (pin 12 on the Arduino). The dataPin sends bit values from the Arduino to the shift register.

                                                                                                  Pin 11 of the 74HC595 is the Shift Register Clock which is our clockPin (pin 9 of the Arduino). The clockPin essentially synchronises the transmission of bits from the Arduino to the shift register.

                                                                                                  Pin 12 of the 74HC595 is the Output Register Clock which is our latchPin (pin 11 of the Arduino). The latch is set to LOW while bits are being shifted from the Arduino to the 74HC595 and raised to HIGH once all the bits have been received by the 74HC595. When the latch is set to HIGH, the 74HC595 will then transmit the instructions received to its attached OUTPUT devices.

                                                                                                  A +5 V and a GND rail will be setup from the Arduino.

                                                                                                  Pin 16 and Pin 8 on the 74HC595 are Power and GND respectively and are attached to the +5V and GND rails respectively.

                                                                                                  Pin 10 on the 74HC595 the Shift Register Clear is attached to +5 V meaning the shift register is always enabled.

                                                                                                  Pin 13 on the 74HC595 the Output Enable is attached to GND as we are not wanting to Output any values from the 74HC595.

                                                                                                  Finally we have the 8 LEDs and their associated current limiting resistor attached to the 8 output pins 15, 1, 2, 3, 4, 5, 6, and 7 respectively:

                                                                                                  With all the connections made:

                                                                                                  We can write a byte pattern to the LEDs using:

                                                                                                  shiftOut(dataPin, clockPin, LSBFIRST, bytePatternForLEDS);

                                                                                                  And recall, we must also lower the latch in order to write:

                                                                                                    digitalWrite(latchPin, LOW);
                                                                                                    shiftOut(dataPin, clockPin, LSBFIRST, pattern1LED);
                                                                                                    digitalWrite(latchPin, HIGH);  

                                                                                                  An example sketch which flashes every alternate LED (0xAA or 0b10101010) and then 0xFF or (0b01010101) is shown:

                                                                                                  int latchPin = 11;
                                                                                                  int clockPin = 9;
                                                                                                  int dataPin = 12;
                                                                                                  
                                                                                                  byte bytePatternForLEDS1 = 0xAA;
                                                                                                  byte bytePatternForLEDS2 = 0x55;
                                                                                                  
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(latchPin, OUTPUT);
                                                                                                    pinMode(dataPin, OUTPUT);
                                                                                                    pinMode(clockPin, OUTPUT);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    digitalWrite(latchPin, LOW);
                                                                                                    shiftOut(dataPin, clockPin, LSBFIRST, bytePatternForLEDS1);
                                                                                                    digitalWrite(latchPin, HIGH);  
                                                                                                    
                                                                                                    delay(delayTime);
                                                                                                    
                                                                                                    digitalWrite(latchPin, LOW);
                                                                                                    shiftOut(dataPin, clockPin, LSBFIRST, bytePatternForLEDS2);
                                                                                                    digitalWrite(latchPin, HIGH);
                                                                                                    
                                                                                                    delay(delayTime);
                                                                                                  }

                                                                                                  The Tinkercad emulation is available here:

                                                                                                  We can use this to visualise how we count from 0-255 (1 Byte) in binary:

                                                                                                  int latchPin = 11;
                                                                                                  int clockPin = 9;
                                                                                                  int dataPin = 12;
                                                                                                  
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(latchPin, OUTPUT);
                                                                                                    pinMode(dataPin, OUTPUT);
                                                                                                    pinMode(clockPin, OUTPUT);
                                                                                                    
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    
                                                                                                    for(byte hexVal=0x00; hexVal<=0xFF; hexVal++){ 
                                                                                                    
                                                                                                    	digitalWrite(latchPin, LOW);
                                                                                                    	shiftOut(dataPin, clockPin, LSBFIRST, hexVal);
                                                                                                    	digitalWrite(latchPin, HIGH);  
                                                                                                    
                                                                                                          Serial.print(hexVal);
                                                                                                          Serial.print(" 0x");
                                                                                                          Serial.print(hexVal, HEX);
                                                                                                          Serial.print(" 0b");
                                                                                                          Serial.println(hexVal, BIN);
                                                                                                      
                                                                                                    	delay(delayTime);
                                                                                                      
                                                                                                    } 
                                                                                                    
                                                                                                  }

                                                                                                  We can also visualise a right shift (division by 2):

                                                                                                  int latchPin = 11;
                                                                                                  int clockPin = 9;
                                                                                                  int dataPin = 12;
                                                                                                  
                                                                                                  byte bytePatternForLEDS;
                                                                                                  
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(latchPin, OUTPUT);
                                                                                                    pinMode(dataPin, OUTPUT);
                                                                                                    pinMode(clockPin, OUTPUT);
                                                                                                    
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    bytePatternForLEDS = 0b11011101;
                                                                                                      
                                                                                                      for(int idx=0; idx<8; idx++){
                                                                                                      digitalWrite(latchPin, LOW);
                                                                                                      shiftOut(dataPin, clockPin, LSBFIRST, bytePatternForLEDS);
                                                                                                      digitalWrite(latchPin, HIGH); 
                                                                                                        
                                                                                                      Serial.print(bytePatternForLEDS);
                                                                                                      Serial.print(" 0x");  
                                                                                                      Serial.print(bytePatternForLEDS, HEX);
                                                                                                      Serial.print(" 0b");
                                                                                                      Serial.println(bytePatternForLEDS, BIN);  
                                                                                                  
                                                                                                      delay(delayTime);
                                                                                                      
                                                                                                      bytePatternForLEDS /= 2;
                                                                                                      //bytePatternForLEDS >>= 1;  
                                                                                                   
                                                                                                    }
                                                                                                  }

                                                                                                  To left shift, we can instead multiply by 2:

                                                                                                  int latchPin = 11;
                                                                                                  int clockPin = 9;
                                                                                                  int dataPin = 12;
                                                                                                  
                                                                                                  byte bytePatternForLEDS;
                                                                                                  
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(latchPin, OUTPUT);
                                                                                                    pinMode(dataPin, OUTPUT);
                                                                                                    pinMode(clockPin, OUTPUT);
                                                                                                    
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    bytePatternForLEDS = 0b11011101;
                                                                                                      
                                                                                                      for(int idx=0; idx<8; idx++){
                                                                                                      digitalWrite(latchPin, LOW);
                                                                                                      shiftOut(dataPin, clockPin, LSBFIRST, bytePatternForLEDS);
                                                                                                      digitalWrite(latchPin, HIGH); 
                                                                                                        
                                                                                                      Serial.print(bytePatternForLEDS);
                                                                                                      Serial.print(" 0x");  
                                                                                                      Serial.print(bytePatternForLEDS, HEX);
                                                                                                      Serial.print(" 0b");
                                                                                                      Serial.println(bytePatternForLEDS, BIN);  
                                                                                                  
                                                                                                      delay(delayTime);
                                                                                                              
                                                                                                      bytePatternForLEDS *= 2;
                                                                                                        //bytePatternForLEDS <<= 1;    
                                                                                                    }
                                                                                                  }

                                                                                                  To instead get a right circular shift we can check if the last character is 0 or 1. In the case where it is 1, we can right shift the number and then add 0b10000000 to the result:

                                                                                                  int latchPin = 11;
                                                                                                  int clockPin = 9;
                                                                                                  int dataPin = 12;
                                                                                                  
                                                                                                  byte bytePatternForLEDS;
                                                                                                  
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(latchPin, OUTPUT);
                                                                                                    pinMode(dataPin, OUTPUT);
                                                                                                    pinMode(clockPin, OUTPUT);
                                                                                                    
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    bytePatternForLEDS = 0b11011101;
                                                                                                      
                                                                                                      for(int idx=0; idx<8; idx++){
                                                                                                      digitalWrite(latchPin, LOW);
                                                                                                      shiftOut(dataPin, clockPin, LSBFIRST, bytePatternForLEDS);
                                                                                                      digitalWrite(latchPin, HIGH); 
                                                                                                        
                                                                                                      Serial.print(bytePatternForLEDS);
                                                                                                      Serial.print(" 0x");  
                                                                                                      Serial.print(bytePatternForLEDS, HEX);
                                                                                                      Serial.print(" 0b");
                                                                                                      Serial.println(bytePatternForLEDS, BIN);  
                                                                                                        
                                                                                                      delay(delayTime);
                                                                                                      
                                                                                                        if(bytePatternForLEDS%2==1){
                                                                                                        	bytePatternForLEDS = bytePatternForLEDS/2 + 0b10000000;
                                                                                                          Serial.println("odd");
                                                                                                        }
                                                                                                        else{
                                                                                                          bytePatternForLEDS = bytePatternForLEDS/2;
                                                                                                          Serial.println("even");
                                                                                                        } 
                                                                                                    }
                                                                                                  }

                                                                                                  To instead perform a circular left shift we can check if the number is >=0b10000000 and in the case where it is add 0b00000001:

                                                                                                  int latchPin = 11;
                                                                                                  int clockPin = 9;
                                                                                                  int dataPin = 12;
                                                                                                  
                                                                                                  byte bytePatternForLEDS;
                                                                                                  
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(latchPin, OUTPUT);
                                                                                                    pinMode(dataPin, OUTPUT);
                                                                                                    pinMode(clockPin, OUTPUT);
                                                                                                    
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    bytePatternForLEDS = 0b11011101;
                                                                                                      
                                                                                                      for(int idx=0; idx<8; idx++){
                                                                                                      digitalWrite(latchPin, LOW);
                                                                                                      shiftOut(dataPin, clockPin, LSBFIRST, bytePatternForLEDS);
                                                                                                      digitalWrite(latchPin, HIGH); 
                                                                                                        
                                                                                                      Serial.print(bytePatternForLEDS);
                                                                                                      Serial.print(" 0x");  
                                                                                                      Serial.print(bytePatternForLEDS, HEX);
                                                                                                      Serial.print(" 0b");
                                                                                                      Serial.println(bytePatternForLEDS, BIN);  
                                                                                                        
                                                                                                      delay(delayTime);
                                                                                                      
                                                                                                        if(bytePatternForLEDS>=0b10000000){
                                                                                                        	bytePatternForLEDS = bytePatternForLEDS*2 + 0b00000001;
                                                                                                          Serial.println("odd");
                                                                                                        }
                                                                                                        else{
                                                                                                          bytePatternForLEDS = bytePatternForLEDS*2;
                                                                                                          Serial.println("even");
                                                                                                        } 
                                                                                                    }
                                                                                                  }

                                                                                                  To invert a number we can take advantage of the fact that 0b11111111 is the sum of the number and its inverse and therefore subtract the original number from 0b11111111:

                                                                                                  int latchPin = 11;
                                                                                                  int clockPin = 9;
                                                                                                  int dataPin = 12;
                                                                                                  
                                                                                                  byte bytePatternForLEDS = 0b11011101;
                                                                                                  
                                                                                                  int delayTime = 1000;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    pinMode(latchPin, OUTPUT);
                                                                                                    pinMode(dataPin, OUTPUT);
                                                                                                    pinMode(clockPin, OUTPUT);
                                                                                                    
                                                                                                    Serial.begin(9600);
                                                                                                  }
                                                                                                  
                                                                                                  void loop()
                                                                                                  {
                                                                                                    
                                                                                                      digitalWrite(latchPin, LOW);
                                                                                                      shiftOut(dataPin, clockPin, LSBFIRST, bytePatternForLEDS);
                                                                                                      digitalWrite(latchPin, HIGH); 
                                                                                                        
                                                                                                      Serial.print(bytePatternForLEDS);
                                                                                                      Serial.print(" 0x");  
                                                                                                      Serial.print(bytePatternForLEDS, HEX);
                                                                                                      Serial.print(" 0b");
                                                                                                      Serial.println(bytePatternForLEDS, BIN); 
                                                                                                      bytePatternForLEDS = 0b11111111 - bytePatternForLEDS;
                                                                                                      delay(delayTime);
                                                                                                    
                                                                                                  }

                                                                                                  Tutorial 48-49: Arduino and LCD Display

                                                                                                  The LCD display has 16 pins.

                                                                                                  We need to make a +5V and GND rail.

                                                                                                  The VCC and GND should be attached to the +5 V and GND rail respectively to power the LCD. To the right hand side there is the LED Anode and LED Cathode which are is used to power the LED behind the LCD screen. The LED Anode should be attached to a 1 kΩ protection resistor before being attached to +5 V and the LED Cathode should be attached to GND. The RW pin should also be attached to GND, because we are writing to the LCD and not reading from a LCD.

                                                                                                  The VO pin attaches to the voltage out pin in the middle of a potentiometer. The rest of the potentiometer attaches to +5 V and GND respectively. This potentiometer is used to control the brightness of the LCD display.

                                                                                                  Next we need to connect 6 GPIO pins to RS, E and DB4-7, for convenience I am going to use 2,3 and 8-11:

                                                                                                  The complete connections look like:

                                                                                                  To use the LCD Display we need to include the LiquidCrystal library and create an instance of the LiquidCrystal class which we call lcd. During instantiation we need to supply the 6 GPIO pins used by the LCD Display:

                                                                                                  #include <LiquidCrystal.h>
                                                                                                  int rs = 2;
                                                                                                  int en = 3;
                                                                                                  int d4 = 8;
                                                                                                  int d5 = 9;
                                                                                                  int d6 = 10;
                                                                                                  int d7 = 11;
                                                                                                  LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

                                                                                                  We then need to use the begin function and specify the number of columns by the number of rows. N.B. we specify columns and then rows which is inconsistent with the standard practice when dealing with matrices. In this case it is 16 by 2:

                                                                                                  lcd.begin(16,2);

                                                                                                  Each cell has a numeric index, column and then row, counting from 0 upwards. As there are 16 columns it is easier to conceptualise this using hexadecimal:

                                                                                                  To write we must specify a position for the cursor.

                                                                                                  lcd.setcursor(0xA, 0x1);

                                                                                                  We can then print using the print command by supplying a string:

                                                                                                  lcd.print("Hello");

                                                                                                  Note that the cursor will now be here:

                                                                                                  Using another print command will print at this cursor location, for example:

                                                                                                  lcd.print("!");

                                                                                                  Any other print commands will not be shown as the cursor is off the edge of the lcd.

                                                                                                  To clear the contents of the lcd display we can use the clear command:

                                                                                                  lcd.clear()

                                                                                                  Generally we select the cursor position, print, delay and then clear. We can make a small sketch which displays Hello World and then counts to 10000:

                                                                                                  #include <LiquidCrystal.h>
                                                                                                  int rs = 2;
                                                                                                  int en = 3;
                                                                                                  int d4 = 8;
                                                                                                  int d5 = 9;
                                                                                                  int d6 = 10;
                                                                                                  int d7 = 11;
                                                                                                  LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
                                                                                                  
                                                                                                  int delayTime1 = 1500;
                                                                                                  int delayTime2 = 10;
                                                                                                  
                                                                                                  void setup() {
                                                                                                    lcd.begin(16, 2);
                                                                                                  }
                                                                                                  
                                                                                                  void loop() {
                                                                                                    delay(500);
                                                                                                    lcd.setCursor(0, 0);
                                                                                                    lcd.print("Hello World.");
                                                                                                    delay(delayTime1);
                                                                                                    lcd.clear();
                                                                                                    
                                                                                                    lcd.setCursor(0, 0);
                                                                                                    lcd.print("Watch me count.");
                                                                                                    
                                                                                                    for (int idx=1; idx<=10000; idx+=1){
                                                                                                        lcd.setCursor(0,1);
                                                                                                        lcd.print(idx);
                                                                                                        delay(delayTime2);
                                                                                                    }
                                                                                                    
                                                                                                    lcd.clear();
                                                                                                  }

                                                                                                  We can also practice using the LCD by making a simple calculator which uses the keyboard as an input device and the LCD as a screen~:

                                                                                                  #include <LiquidCrystal.h>
                                                                                                  int rs = 2;
                                                                                                  int en = 3;
                                                                                                  int d4 = 8;
                                                                                                  int d5 = 9;
                                                                                                  int d6 = 10;
                                                                                                  int d7 = 11;
                                                                                                  LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
                                                                                                  
                                                                                                  int delayTime1 = 500;
                                                                                                  int delayTime2 = 1500;
                                                                                                  
                                                                                                  float num1;
                                                                                                  float num2;
                                                                                                  float result;
                                                                                                  String operation;
                                                                                                  
                                                                                                  int validOperation;
                                                                                                  
                                                                                                  void setup() {
                                                                                                    lcd.begin(16, 2);
                                                                                                    Serial.begin(9600);
                                                                                                  
                                                                                                  }
                                                                                                  
                                                                                                  void loop() {
                                                                                                    lcd.setCursor(0, 0);
                                                                                                    lcd.print("Calculator");
                                                                                                    delay(delayTime1);
                                                                                                    lcd.clear();
                                                                                                    
                                                                                                    lcd.setCursor(0, 0);
                                                                                                    lcd.print("Float 1");
                                                                                                    lcd.setCursor(0, 1);
                                                                                                    lcd.print("Input a number:");
                                                                                                    while(!Serial.available()){}
                                                                                                    num1 = Serial.parseFloat();
                                                                                                    lcd.clear();
                                                                                                    Serial.println(num1);
                                                                                                    
                                                                                                    lcd.setCursor(0, 0);
                                                                                                    lcd.print("Operator");
                                                                                                    lcd.setCursor(0, 1);
                                                                                                    lcd.print("+, -, *, /");
                                                                                                    while(!Serial.available()){}
                                                                                                    operation = Serial.readString();
                                                                                                    lcd.clear();
                                                                                                    Serial.println(operation);
                                                                                                    
                                                                                                    lcd.setCursor(0, 0);
                                                                                                    lcd.print("Float 2");
                                                                                                    lcd.setCursor(0, 1);
                                                                                                    lcd.print("Input a number:");
                                                                                                    while(!Serial.available()){}
                                                                                                    num2 = Serial.parseInt();
                                                                                                    lcd.clear();
                                                                                                    Serial.println(num2);
                                                                                                    
                                                                                                    if(operation == "+"){
                                                                                                      result = num1 + num2;
                                                                                                      validOperation = 1;
                                                                                                      lcd.setCursor(0, 0);
                                                                                                      lcd.print(num1);
                                                                                                      lcd.print(" + ");
                                                                                                    	lcd.print(num2);
                                                                                                      lcd.print(" = ");
                                                                                                    	lcd.setCursor(0, 1);
                                                                                                    	lcd.print(result);
                                                                                                    }
                                                                                                      
                                                                                                    else if(operation == "-"){
                                                                                                      result = num1 - num2;
                                                                                                      validOperation = 1;
                                                                                                      lcd.setCursor(0, 0);
                                                                                                      lcd.print(num1);
                                                                                                      lcd.print(" - ");
                                                                                                    	lcd.print(num2);
                                                                                                      lcd.print(" = ");
                                                                                                    	lcd.setCursor(0, 1);
                                                                                                    	lcd.print(result);
                                                                                                    }
                                                                                                    
                                                                                                      else if(operation == "*"){
                                                                                                      result = num1 * num2;
                                                                                                      validOperation = 1;  
                                                                                                      lcd.setCursor(0, 0);
                                                                                                      lcd.print(num1);
                                                                                                      lcd.print(" * ");
                                                                                                    	lcd.print(num2);
                                                                                                      lcd.print(" = ");
                                                                                                    	lcd.setCursor(0, 1);
                                                                                                    	lcd.print(result);
                                                                                                    }
                                                                                                    
                                                                                                      else if(operation == "/"){
                                                                                                      result = num1 / num2;
                                                                                                      validOperation = 1;
                                                                                                      lcd.setCursor(0, 0);
                                                                                                      lcd.print(num1);
                                                                                                      lcd.print(" / ");
                                                                                                    	lcd.print(num2);
                                                                                                      lcd.print(" = ");
                                                                                                    	lcd.setCursor(0, 1);
                                                                                                    	lcd.print(result);
                                                                                                    }
                                                                                                    else{
                                                                                                    	result = 0;
                                                                                                      validOperation = 0;
                                                                                                      lcd.setCursor(0, 0);
                                                                                                      lcd.print("invalid");
                                                                                                      lcd.setCursor(0, 1);
                                                                                                      lcd.print("operation");
                                                                                                    }
                                                                                                    
                                                                                                    delay(delayTime2);
                                                                                                    
                                                                                                    lcd.clear();
                                                                                                    if(validOperation==1){
                                                                                                    	lcd.setCursor(0, 0);
                                                                                                    	lcd.print("Result: ");
                                                                                                    	lcd.print(result);
                                                                                                    	lcd.setCursor(0, 1);
                                                                                                      lcd.print("Exit?");
                                                                                                    }
                                                                                                      
                                                                                                    else if(validOperation==0){
                                                                                                    	lcd.setCursor(0, 0);
                                                                                                    	lcd.print("Invalid");
                                                                                                    	lcd.setCursor(0, 1);
                                                                                                      lcd.print("Exit?");
                                                                                                    }
                                                                                                    
                                                                                                    while(!Serial.available()){}
                                                                                                    Serial.readString();
                                                                                                    lcd.clear();
                                                                                                  }

                                                                                                  Tutorial 50-52: DHT11 Temperature and Humidity Sensor

                                                                                                  Unfortunately at the time of writing the DHT11 sensor or associated library are not available on Tinkercad. We will therefore use the TMP36 instead which is slightly simpler. This sensor reports the temperature as an analogReading which we can convert to a voltage and then there is a simple formula to convert the voltage to a temperature reading. The sensor has three pins, a + 5V pin, a GND pin and a sense pin which must be attached to +5 V, GND and an analog input pin respectively:

                                                                                                  int sensorPin = A0; 
                                                                                                  float analogReading;
                                                                                                  float voltageReading;
                                                                                                  float tempReading;
                                                                                                  
                                                                                                  void setup()
                                                                                                  {
                                                                                                    Serial.begin(9600);
                                                                                                    pinMode(sensorPin, INPUT);
                                                                                                  }
                                                                                                   
                                                                                                  void loop()
                                                                                                  {
                                                                                                   analogReading = analogRead(sensorPin);
                                                                                                   Serial.print("analogReading: ");
                                                                                                   Serial.print(analogReading);
                                                                                                    
                                                                                                   // converting that reading to voltage
                                                                                                   voltageReading = analogReading * 5.0 / 1024.0; 
                                                                                                   Serial.print("\tVoltage: ");
                                                                                                   Serial.print(voltageReading); 
                                                                                                   Serial.print(" V \t");
                                                                                                   
                                                                                                   // convert to temperature 0.1 V/degree and 0.5 V offset
                                                                                                   tempReading = (voltageReading - 0.5) * 100 ; 
                                                                                                   Serial.print("Temperature: ");
                                                                                                   Serial.print(tempReading);
                                                                                                   Serial.println(" C");
                                                                                                   
                                                                                                   delay(1000);                                    
                                                                                                  }

                                                                                                  Let's incorporate this sensor into our Arduino circuit with an LCD display and update the LCD display to display the temperature:

                                                                                                  #include <LiquidCrystal.h>
                                                                                                  int rs = 2;
                                                                                                  int en = 3;
                                                                                                  int d4 = 8;
                                                                                                  int d5 = 9;
                                                                                                  int d6 = 10;
                                                                                                  int d7 = 11;
                                                                                                  LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
                                                                                                  
                                                                                                  int sensorPin = A0; 
                                                                                                  float analogReading;
                                                                                                  float voltageReading;
                                                                                                  float tempReading;
                                                                                                  
                                                                                                  int delayTime1 = 1000;
                                                                                                  
                                                                                                  
                                                                                                  void setup() {
                                                                                                    lcd.begin(16, 2);
                                                                                                    pinMode(sensorPin, INPUT);
                                                                                                    Serial.begin(9600);
                                                                                                  
                                                                                                  }
                                                                                                  
                                                                                                  void loop() {
                                                                                                   int analogReading = analogRead(sensorPin);
                                                                                                   voltageReading = analogReading * 5.0 / 1024.0; 
                                                                                                   tempReading = (voltageReading - 0.5) * 100 ; 
                                                                                                    
                                                                                                   lcd.setCursor(0, 0);
                                                                                                   lcd.print("Temperature: ");
                                                                                                   lcd.setCursor(0, 1);
                                                                                                   lcd.print(tempReading);
                                                                                                   lcd.println(" C");
                                                                                                   
                                                                                                   delay(delayTime1);    
                                                                                                    
                                                                                                   lcd.clear();
                                                                                                  
                                                                                                  }

                                                                                                  Tutorial 53-55: Arduino and HC-SR04 Ultrasonic Sensor

                                                                                                  The ultrasonic sensor has 4 pins VCC and GND which attach to +5V and GND respectively and Trig and Echo which attach to GPIO pins on the Arduino.

                                                                                                  The ultrasonic range finder operates by sending small square pulse to the trigger OUTPUT which activates the transmitter. When the trigger OUTPUT is activated, the echo INPUT is raised to HIGH until the rangefinder times out, assuming no interaction with an object.

                                                                                                  On the other hand if the ultrasonic pulse interacts with an object, a proportion of the signal is sent back towards the ultrasonic rangefinder and detected by the receiver. Once the receiver has received the reflected signal, the echo INPUT is returned to LOW.

                                                                                                  As a result the Echo pin essentially displays a square pulse and we can measure its duration using the pulseIn command:

                                                                                                  pingTravelTime = pulseIn(echoPin, HIGH, timeout);
                                                                                                  pingTravelTime = pulseIn(echoPin, HIGH);

                                                                                                  Since pingTravelTime is in µs and we are essentially measuring the duration of a round trip (to and from an object):

                                                                                                  And since:

                                                                                                  With the speed of sound in air being a constant: