Code Book for Arduino
The code for the scripts has been sourced from a number of resources. It is intended that all scripts for the exercise can be found here. This way teachers can copy and paste the scripts to where they are required, such as in an email to a student.
Where Sparkfun scripts have been used most of the informational details have been removed for convenience. The scripts Sparkfun has done are excellent with the information they provide and looking at the original scripts is a worthwhile exercise.
Contents
Code Book for Arduino
Exercise 1 - Blink
Exercise 2 – Blink 2
Exercise 3 – Fade
Exercise 4 – Potentiometer
Exercise 5 – RGB
Exercise 6 – Simple traffic Light
Exercise 7 – PWM
Exercise 8 – RGB Mood lamp
Exercise 9 - LED Fire effect
Exercise 10 – Push Button
Exercise 11 – Push Buttons
Exercise 12 – Traffic light with button
Exercise 13 – Multiple LED’s with chase effect
Exercise 14 -
Exercise 15 – LDR Circuit
Exercise 16 – LDR Flicker
Exercise 17 – Tone Melody
Exercise 18 – Tone Multiple
Exercise 19 – Sparkfun buzzer tune
Exercise – Darth Vader tune (bonus)
Exercise 20 – IR Sensor
Exercise 20A – IF statement & IR Sensor
Exercise 21 - Flexiforce
Exercise 21A – Flex Sensor & Servo
Exercise 22 – Temperature Sensor
Exercise 23 – Ultrasonic Sensor
Exercise 24 – Add 2 LED’s, Stop/Go
Exercise 25 – Servos
Exercise 26 – Interactive Servos
Exercise 27 – Motors
Exercise 28 – Relay
Exercise 29 – Shift Register
Exercise 30 – LCD
Exercise 31 – Fono GSM cellphone build
Exercise 31 – Simon Says
Exercise 32, Morse Code transmitter
Exercise 1 - Blink
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.
Most Arduinos have an on-board LED you can control. On the Uno and
Leonardo, it is attached to digital pin 13. If you're unsure what
pin the on-board LED is connected to on your Arduino model, check
the documentation at
This example code is in the public domain.
modified 8 May 2014
by Scott Fitzgerald
*/
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin 13 as an output.
pinMode(13, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
Exercise 2 – Blink 2
//Exercise 2, My 1st Project – LED flasher/blink
int ledPin = 9;
Void setup() {
pinMode (ledPin, OUTPUT);
}
Void loop() {
digitalWrite(ledPin, HIGH);
delay(1000);
digitalWrite(ledPin, LOW);
delay(1000);
}
Exercise 3 – Fade
/*
Fade
This example shows how to fade an LED on pin 9
using the analogWrite() function.
This example code is in the public domain.
*/
int led = 9; // the pin that the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by
// the setup routine runs once when you press reset:
void setup() {
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// set the brightness of pin 9:
analogWrite(led, brightness);
// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
// reverse the direction of the fading at the ends of the fade:
if (brightness == 0 || brightness == 255) {
fadeAmount = -fadeAmount ;
}
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
Exercise 4 – Potentiometer
/*
SparkFun Inventor's Kit
Example sketch 02
POTENTIOMETER
*/
// Here we're creating a variable called "sensorPin" of type "int"
// and initializing it to have the value "0":
int sensorPin = 0; // The potentiometer is connected to
// analog pin 0
int ledPin = 13; // The LED is connected to digital pin 13
void setup() // this function runs once when the sketch starts up
{
// We'll be using pin 13 to light a LED, so we must configure it
// as an output.
// Because we already created a variable called ledPin, and
// set it equal to 13, we can use "ledPin" in place of "13".
// This makes the sketch easier to follow.
pinMode(ledPin, OUTPUT);
// The above line is the same as "pinMode(13, OUTPUT);"
}
void loop() // this function runs repeatedly after setup() finishes
{
int sensorValue;
sensorValue = analogRead(sensorPin);
digitalWrite(ledPin, HIGH); // Turn the LED on
delay(sensorValue); // Pause for sensorValue
digitalWrite(ledPin, LOW); // Turn the LED off
delay(sensorValue); // Pause for sensorValue
}
Exercise 5 – RGB
/*
SparkFun Inventor's Kit
Example sketch 03
RGB LED
*/
const int RED_PIN = 9;
const int GREEN_PIN = 10;
const int BLUE_PIN = 11;
int DISPLAY_TIME = 100; // In milliseconds
void setup()
{
pinMode(RED_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
pinMode(BLUE_PIN, OUTPUT);
}
void loop()
{
mainColors();
showSpectrum();
}
void mainColors()
{
// Off (all LEDs off):
digitalWrite(RED_PIN, LOW);
digitalWrite(GREEN_PIN, LOW);
digitalWrite(BLUE_PIN, LOW);
delay(1000);
// Red (turn just the red LED on):
digitalWrite(RED_PIN, HIGH);
digitalWrite(GREEN_PIN, LOW);
digitalWrite(BLUE_PIN, LOW);
delay(1000);
// Green (turn just the green LED on):
digitalWrite(RED_PIN, LOW);
digitalWrite(GREEN_PIN, HIGH);
digitalWrite(BLUE_PIN, LOW);
delay(1000);
// Blue (turn just the blue LED on):
digitalWrite(RED_PIN, LOW);
digitalWrite(GREEN_PIN, LOW);
digitalWrite(BLUE_PIN, HIGH);
delay(1000);
// Yellow (turn red and green on):
digitalWrite(RED_PIN, HIGH);
digitalWrite(GREEN_PIN, HIGH);
digitalWrite(BLUE_PIN, LOW);
delay(1000);
// Cyan (turn green and blue on):
digitalWrite(RED_PIN, LOW);
digitalWrite(GREEN_PIN, HIGH);
digitalWrite(BLUE_PIN, HIGH);
delay(1000);
// Purple (turn red and blue on):
digitalWrite(RED_PIN, HIGH);
digitalWrite(GREEN_PIN, LOW);
digitalWrite(BLUE_PIN, HIGH);
delay(1000);
// White (turn all the LEDs on):
digitalWrite(RED_PIN, HIGH);
digitalWrite(GREEN_PIN, HIGH);
digitalWrite(BLUE_PIN, HIGH);
delay(1000);
}
void showSpectrum()
{
int x; // define an integer variable called "x"
for (x = 0; x < 768; x++)
// Each time we loop (with a new value of x), do the following:
{
showRGB(x); // Call RGBspectrum() with our new x
delay(10); // Delay for 10 ms (1/100th of a second)
}
}
void showRGB(int color)
{
int redIntensity;
int greenIntensity;
int blueIntensity;
if (color <= 255) // zone 1
{
redIntensity = 255 - color; // red goes from on to off
greenIntensity = color; // green goes from off to on
blueIntensity = 0; // blue is always off
}
else if (color <= 511) // zone 2
{
redIntensity = 0; // red is always off
greenIntensity = 255 - (color - 256); // green on to off
blueIntensity = (color - 256); // blue off to on
}
else // color >= 512 // zone 3
{
redIntensity = (color - 512); // red off to on
greenIntensity = 0; // green is always off
blueIntensity = 255 - (color - 512); // blue on to off
}
analogWrite(RED_PIN, redIntensity);
analogWrite(BLUE_PIN, blueIntensity);
analogWrite(GREEN_PIN, greenIntensity);
}
Exercise 6 – Simple traffic Light
//Exercise 6 - Simple Traffic light
// Next lesson will add a button to this, for a pedestrian crossing type of effect
// Sourced from McRoberts, Michael. 'Beginning Arduino. 2nd Ed.'
int ledDelay = 10000; //delay between changes
int redPin = 10;
int yellowPin = 9;
int greenPin = 8;
void setup() {
pinMode(redPin, OUTPUT);
pinMode(yellowPin, OUTPUT);
pinMode(greenPin, OUTPUT);
}
void loop() {
digitalWrite(redPin, HIGH); //turn the light red on
delay(ledDelay); //wait 10 seconds as per the ledDelay time
digitalWrite(yellowPin, HIGH); //turn the yellow on
delay(2000); //wait 2 seconds
digitalWrite(greenPin, HIGH); //turn the green on
digitalWrite(redPin, LOW); //turn the red off
digitalWrite(yellowPin, LOW); //turn the yellow off
delay(ledDelay); //delay in milliseconds
digitalWrite(yellowPin, HIGH); //turn the yellow on
digitalWrite(greenPin, LOW); //turn the green off
delay(2000); //delay in milliseconds for 2 seconds
}
Exercise 7 – PWM
//Exercise 7 using PWM (Pulse width modulation)
// Sourced from McRoberts, Michael. 'Beginning Arduino. 2nd Ed.' project 7 Pulsating lamp
int ledPin =11;
float sinVal;
int ledVal;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
for (int x=0; x<180; x++) {
//convert degrees to radians then obtain a Sin value
sinVal = (sin(x*(3.1412/180))); //note the value for Pi for converting to radians
ledVal = int (sinVal*255); //note the 255 for converting to computer binary based numeracy
analogWrite(ledPin, ledVal);
delay(25);
}
}
Exercise 8 – RGB Mood lamp
//Exercise 8 RGB Mood lamp
// Sourced from McRoberts, Michael. 'Beginning Arduino. 2nd Ed.' Project 8
float RGB1[3];
float RGB2[3];
float INC[3];
int red, green, blue;
int RedPin = 11
int GreenPin = 10
int BluePin = 9
void setup() {
randomSeed(analogRead(0));
RGB1[0] = 0;
RGB1[1] = 0;
RGB1[2] = 0;
RGB2[0] = random(256);
RGB2[1] = random(256);
RGB2[2] = random(256);
}
void loop() {
randomSeed(analogRead(0));
for (int x=0; x<3; x++) {
INC[x] = (RGB1[x] - RGB2[x])/256; }
for (int x=0; x<256; x++) {
red = int(RGB1[0]);
green = int(RGB1[1]);
blue = int(RGB1[2]);
analogWrite (RedPin, red);
analogWrite (GreenPin, green);
analogWrite (BluePin, blue);
delay(100);
RGB1[0] -= INC[0];
RGB1[1] -= INC[1];
RGB1[2] -= INC[2];
for (int x=0; x<3; x++) {
RGB2[x] = random(556)-300;
RGB2[x] = constrain(RGB2[x], 0, 255);
delay(1000);
}
}
Exercise 9 - LED Fire effect
// Exercise 9 - Fire effect
// Sourced from McRoberts, Michael. 'Beginning Arduino. 2nd Ed.' Project 9
int ledPin1 = 9;
int ledPin2 = 10;
int ledPin3 = 11;
void setup()
{
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
}
void loop()
{
analogWrite(ledPin1, random(120)+135);
analogWrite(ledPin2, random(120)+135);
analogWrite(ledPin3, random(120)+135);
delay(random(100));
}
Exercise 10 – Push Button
/*
Button
This example code is in the public domain.
*/
// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
}
else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}
Exercise 11 – Push Buttons
/*
SparkFun Inventor's Kit
Example sketch 05
Version 2.0 6/2012 MDG
*/
// First we'll set up constants for the pin numbers.
// This will make it easier to follow the code below.
const int button1Pin = 2; // pushbutton 1 pin
const int button2Pin = 3; // pushbutton 2 pin
const int ledPin = 13; // LED pin
void setup()
{
// Set up the pushbutton pins to be an input:
pinMode(button1Pin, INPUT);
pinMode(button2Pin, INPUT);
// Set up the LED pin to be an output:
pinMode(ledPin, OUTPUT);
}
void loop()
{
int button1State, button2State; // variables to hold the pushbutton states
button1State = digitalRead(button1Pin);
button2State = digitalRead(button2Pin);
if (((button1State == LOW) || (button2State == LOW)) // if we're pushing button 1 OR button 2
& ! // AND we're NOT
((button1State == LOW) & (button2State == LOW))) // pushing button 1 AND button 2
// then...
{
digitalWrite(ledPin, HIGH); // turn the LED on
}
else
{
digitalWrite(ledPin, LOW); // turn the LED off
}
}
Exercise 12 – Traffic light with button
//Exercise 12 - Traffic light with button
// Sourced from McRoberts, Michael. 'Beginning Arduino. 2nd Ed.' Project 4
int carRed = 12; // assign the car lights
int carYellow = 11;
int carGreen = 10;
int pedRed = 9; // assign the pedestrian lights
int pedGreen = 8;
int button = 2; // button pin
int crossTime = 5000; // time alloyoud to cross
unsigned long changeTime; // time since button pressed
void setup() {
pinMode(carRed, OUTPUT);
pinMode(carYellow, OUTPUT);
pinMode(carGreen, OUTPUT);
pinMode(pedRed, OUTPUT);
pinMode(pedGreen, OUTPUT);
pinMode(button, INPUT); // button on pin 2
// turn on the green light
digitalWrite(carGreen, HIGH);
digitalWrite(pedRed, HIGH);
}
void loop() {
int state = digitalRead(button);
/* check if button is pressed and it is over 5 seconds since last button press */
if (state == HIGH & (millis() - changeTime) > 5000) {
// Call the function to change the lights
changeLights();
}
}
void changeLights() {
digitalWrite(carGreen, LOW); // green off
digitalWrite(carYellow, HIGH); // yellow on
delay(2000); // wait 2 seconds
digitalWrite(carYellow, LOW); // yellow off
digitalWrite(carRed, HIGH); // red on
delay(1000); // wait 1 second till its safe
digitalWrite(pedRed, LOW); // ped red off
digitalWrite(pedGreen, HIGH); // ped green on
delay(crossTime); // wait for preset time period
// flash the ped green
for (int x=0; x<10; x++) {
digitalWrite(pedGreen, HIGH);
delay(250);
digitalWrite(pedGreen, LOW);
delay(250);
}
// turn ped red on
digitalWrite(pedRed, HIGH);
delay(500);
digitalWrite(carYellow, HIGH); // yellow on
digitalWrite(carRed, LOW); // red off
delay(1000);
digitalWrite(carGreen, HIGH);
digitalWrite(carYellow, LOW); // yellow off
// record the time since last change of lights
changeTime = millis();
// then return to the main program loop
}
Exercise 13 –Multiple LED’s with chase effect
/*
SparkFun Inventor's Kit Example sketch 04
MULTIPLE LEDs
Version 2.0 6/2012 MDG
*/
int ledPins[] = {2,3,4,5,6,7,8,9};
void setup()
{
int index;
for(index = 0; index <= 7; index++)
{
pinMode(ledPins[index],OUTPUT);
// ledPins[index] is replaced by the value in the array.
// For example, ledPins[0] is 2
}
}
void loop()
{
oneAfterAnotherNoLoop(); // Light up all the LEDs in turn
//oneAfterAnotherLoop(); // Same as oneAfterAnotherNoLoop,
//oneOnAtATime(); // Turn on one LED at a time,
//pingPong(); // Light the LEDs middle to the edges
//marquee(); // Chase lights like you see on signs
//randomLED(); // Blink LEDs randomly
}
void oneAfterAnotherNoLoop()
{
int delayTime = 100; // time (milliseconds) to pause between LEDs
// make this smaller for faster switching
// turn all the LEDs on:
digitalWrite(ledPins[0], HIGH); //Turns on LED #0 (pin 2)
delay(delayTime); //wait delayTime milliseconds
digitalWrite(ledPins[1], HIGH); //Turns on LED #1 (pin 3)
delay(delayTime); //wait delayTime milliseconds
digitalWrite(ledPins[2], HIGH); //Turns on LED #2 (pin 4)
delay(delayTime); //wait delayTime milliseconds
digitalWrite(ledPins[3], HIGH); //Turns on LED #3 (pin 5)
delay(delayTime); //wait delayTime milliseconds
digitalWrite(ledPins[4], HIGH); //Turns on LED #4 (pin 6)
delay(delayTime); //wait delayTime milliseconds
digitalWrite(ledPins[5], HIGH); //Turns on LED #5 (pin 7)
delay(delayTime); //wait delayTime milliseconds
digitalWrite(ledPins[6], HIGH); //Turns on LED #6 (pin 8)
delay(delayTime); //wait delayTime milliseconds
digitalWrite(ledPins[7], HIGH); //Turns on LED #7 (pin 9)
delay(delayTime); //wait delayTime milliseconds
// turn all the LEDs off:
digitalWrite(ledPins[7], LOW); //Turn off LED #7 (pin 9)
delay(delayTime); //wait delayTime milliseconds
digitalWrite(ledPins[6], LOW); //Turn off LED #6 (pin 8)
delay(delayTime); //wait delayTime milliseconds
digitalWrite(ledPins[5], LOW); //Turn off LED #5 (pin 7)
delay(delayTime); //wait delayTime milliseconds
digitalWrite(ledPins[4], LOW); //Turn off LED #4 (pin 6)
delay(delayTime); //wait delayTime milliseconds
digitalWrite(ledPins[3], LOW); //Turn off LED #3 (pin 5)
delay(delayTime); //wait delayTime milliseconds
digitalWrite(ledPins[2], LOW); //Turn off LED #2 (pin 4)
delay(delayTime); //wait delayTime milliseconds
digitalWrite(ledPins[1], LOW); //Turn off LED #1 (pin 3)
delay(delayTime); //wait delayTime milliseconds
digitalWrite(ledPins[0], LOW); //Turn off LED #0 (pin 2)
delay(delayTime); //wait delayTime milliseconds
}
void oneAfterAnotherLoop()
{
int index;
int delayTime = 100; // milliseconds to pause between LEDs
for(index = 0; index <= 7; index++)
{
digitalWrite(ledPins[index], HIGH);
delay(delayTime);
}
for(index = 7; index >= 0; index--)
{
digitalWrite(ledPins[index], LOW);
delay(delayTime);
}
}
void oneOnAtATime()
{
int index;
int delayTime = 100; // milliseconds to pause between LEDs
// make this smaller for faster switching
for(index = 0; index <= 7; index++)
{
digitalWrite(ledPins[index], HIGH); // turn LED on
delay(delayTime); // pause to slow down
digitalWrite(ledPins[index], LOW); // turn LED off
}
}
void pingPong()
{
int index;
int delayTime = 100; // milliseconds to pause between LEDs
for(index = 0; index <= 7; index++)
{
digitalWrite(ledPins[index], HIGH); // turn LED on
delay(delayTime); // pause to slow down
digitalWrite(ledPins[index], LOW); // turn LED off
}
for(index = 7; index >= 0; index--)
{
digitalWrite(ledPins[index], HIGH); // turn LED on
delay(delayTime); // pause to slow down
digitalWrite(ledPins[index], LOW); // turn LED off
}
}
void marquee()
{
int index;
int delayTime = 200; // milliseconds to pause between LEDs
for(index = 0; index <= 3; index++) // Step from 0 to 3
{
digitalWrite(ledPins[index], HIGH); // Turn a LED on
digitalWrite(ledPins[index+4], HIGH); // Skip four, and turn that LED on
delay(delayTime); // Pause to slow down the sequence
digitalWrite(ledPins[index], LOW); // Turn the LED off
digitalWrite(ledPins[index+4], LOW); // Skip four, and turn that LED off
}
}
void randomLED()
{
int index;
int delayTime;
index = random(8);// pick a random number between 0 and 7
delayTime = 100;
digitalWrite(ledPins[index], HIGH); // turn LED on
delay(delayTime); // pause to slow down
digitalWrite(ledPins[index], LOW); // turn LED off
}
Exercise 14 -
Code for Project 6
byte ledPin[] = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; // Create array for LED pins
int ledDelay; // delay between changes
int direction = 1;
int currentLED = 0;
unsigned long changeTime;
int potPin = 2; // select the input pin for the potentiometer
void setup() {
for (int x=0; x<10; x++) { // set all pins to output
pinMode(ledPin[x], OUTPUT); }
changeTime = millis();
}
void loop() {
ledDelay = analogRead(potPin); // read the value from the pot
if ((millis() - changeTime) > ledDelay) { // if it has been ledDelay ms since
last change
changeLED();
changeTime = millis();
}
}
void changeLED() {
for (int x=0; x<10; x++) { // turn off all LED's
digitalWrite(ledPin[x], LOW);
}
digitalWrite(ledPin[currentLED], HIGH); // turn on the current LED
currentLED += direction; // increment by the direction value
// change direction if we reach the end
if (currentLED == 9) {direction = -1;}
if (currentLED == 0) {direction = 1;}
}
Exercise 15 –LDR Circuit
/*
SparkFun Inventor's Kit Example sketch 06
PHOTO RESISTOR
Version 2.0 6/2012 MDG
*/
const int sensorPin = 0;
const int ledPin = 9;
int lightLevel, high = 0, low = 1023;
void setup()
{
pinMode(ledPin, OUTPUT);
}
void loop()
{
lightLevel = analogRead(sensorPin);
// lightLevel = map(lightLevel, 0, 1023, 0, 255);
manualTune(); // manually change the range from light to dark
analogWrite(ledPin, lightLevel);
}
void manualTune()
{
lightLevel = map(lightLevel, 0, 1023, 0, 255);
lightLevel = constrain(lightLevel, 0, 255);
}
void autoTune()
{
if (lightLevel < low)
{
low = lightLevel;
}
if (lightLevel > high)
{
high = lightLevel;
}
lightLevel = map(lightLevel, low+30, high-30, 0, 255);
lightLevel = constrain(lightLevel, 0, 255);
}
Exercise 16 –LDR Flicker
// LDR - Exercise 16
// blink faster in the dark and slower in the light
// sourced from p49 Karvinen, Kimmo & Karvinen, Tero. 'Make: Getting started with Sensors'
// This sketch was also used for a pot
// to do so change photoPin to potPin
int photoPin=A0;
int ledPin=13;
int x=-1; //0..1023
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
x=analogRead(photoPin);
digitalWrite(ledPin, HIGH);
delay(x/10);
digitalWrite(ledPin, LOW);
delay(x/10);
}
Exercise 17 –Tone Melody
/*
Melody
circuit:
* 8-ohm speaker on digital pin 8
created 21 Jan 2010
modified 30 Aug 2011
by Tom Igoe
This example code is in the public domain.
*/
#include "pitches.h"
// notes in the melody:
int melody[] = {
NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};
int noteDurations[] = {
4, 8, 8, 4, 4, 4, 4, 4
};
void setup() {
// iterate over the notes of the melody: