SlideShare a Scribd company logo
Arduino foundations: sketch
basics, what’s on board, more
         programming
http://arduino.cc/en/Tutorial/Founda
                tions
Basics

What’s a sketch and how does it
             work?
Sketch: comments and variables
• A sketch is the name Arduino uses for a program
• Comments are used to explain what the program
  does:
   – Use /* blah */ to comment out an area of code
   – Use // to add a comment to the end of a line of code
• A variable is a place for storing data:
   – type name = value;
   – int ledPin = 13;
   – Every time ledPin is referred to in code, value is
     retrieved
   – Can also change variable value in code
Sketch: functions
• Functions are named pieces of code that can be
  used from elsewhere in a sketch:
   – setup(), loop(), pinMode()
• First line of a function provides info about it, like
  its name (e.g. setup), and the text before / after
  the name specify its return type and parameters:
     void setup()
     {
     [body of function]
     }
Sketch: functions (2)
• Can call a pre-defined function as part of the
  Arduino language or functions defined in your
  sketch:
  – e.g. pinMode(ledPin, OUTPUT); calls pinMode()
    with the parameters ledPin and OUTPUT


• We’ll now describe some sample functions
  that you may have seen already
Function: pinmode()
• The pinMode() function configures a pin as
  either an input or an output
• To use it, you pass it the number of the pin to
  configure and the constant INPUT or OUTPUT
• When configured as an input, a pin can detect
  the state of a sensor like a pushbutton
• As an output, it can drive a device like an LED
Functions: digitalWrite(), delay()
• digitalWrite() outputs a value on a pin
• For example, the line:
   – digitalWrite(ledPin, HIGH);
  sets the ledPin (pin 13) to HIGH, or 5 volts
• Writing a LOW to the pin connects it to ground, or 0 volts

• delay() causes the Arduino to wait for the specified number
  of milliseconds before continuing on to the next line
• There are 1000 milliseconds in a second, so the line:
   – delay(1000);
  creates a one second delay
Special functions: setup(), loop()
• There are two special functions that are a part
  of everyArduino sketch: setup() and loop():
  – setup() is called once, when the sketch starts
     • It's a good place to do setup tasks like setting pin
       modes or initializing libraries
  – The loop() function is called over and over and is
    heart of most sketches
• You need to include both functions in your
  sketch, even if you don't need them for
  anything
Exercises, based on ‘blink’ code
1. Change the code so that the LED is on for 100
   milliseconds and off for 1000
2. Change the code so that the LED turns on
   when the sketch starts and stays on
Problem
• Write a sketch that turns on and off the onboard LED
  (pin 13) in the Morse code-style SOS sequence ‘· · · —
  — — · · ·’, assuming that a unit is of one second
  duration, and Morse code is composed of the following
  five elements:
   – short mark, dot or 'dit' (·) — 'dot duration' is one unit long;
   – longer mark, dash or 'dah' (–) — three units long;
   – inter-element gap between the dots and dashes within a
     character — one unit long;
   – short gap (between letters) — three units long;
   – medium gap (between words) — seven units long.
   – http://en.wikipedia.org/wiki/Morse_code#Representation.
     2C_timing_and_speeds
Morse code code
int pin = 13;

void setup()
{
pinMode(pin, OUTPUT);
}

void loop()
{
  dot(); dot(); dot();
  delay(2000); // plus last one second delay from the dot function = 3
  dash(); dash(); dash();
  delay(2000); // plus last one second delay from the dash function = 3
  dot(); dot(); dot();
  delay(6000); // plus last one second delay from the dot function = 7
}
Morse code code (2)
void dot()
{
digitalWrite(pin, HIGH);
  delay(1000);
digitalWrite(pin, LOW);
  delay(1000);
}

void dash()
{
digitalWrite(pin, HIGH);
  delay(3000);
digitalWrite(pin, LOW);
  delay(1000);
}
Overview
• First, we have the dot() and dash() functions
  that do the actual blinking
• Second, there's the pin variable which the
  functions use to determine which pin to use
• Finally, there's the call to pinMode() that
  initialises the pin as an output
On the microcontroller

    Pins and memory
Configuring digital pins
• Note: the vast majority of Arduino (Atmega)
  analog pins may be configured, and used, in
  exactly the same manner as digital pins

• We’ll look at:
  – Properties of pins configured as INPUT
  – Pull-up resistors
  – Properties of pins configured as OUTPUT
Properties of pins configured as INPUT
• Arduino pins default to INPUT:
  – Don’t need to be explicitly defined as INPUT-type
    using pinMode()
• Input pins are high impedance (order of M ):
  – Will draw little current (order of A)
  – Suitable for low current apps like capacitive touch
    sensors, FSRs, phototransistors / photodiodes, etc.
• But with nothing connected, become sensitive
  to external noise from the environment
Pull-up resistors
• Used to steer an input to a particular (default)
  state if no input is present
• Could add a pull-up resistor to +5 volts or a pull-
  down resistor to 0 volts, e.g. using a 10 kΩ value
• There are built-in 20 kΩ pull-up resistors on the
  Atmega chips, which can be enabled via software:
   – pinMode(pinX, INPUT); // set pin to input
   – digitalWrite(pinX, HIGH); // turn on pull-up resistors
Pull-up resistors (2)
• Pull-ups will provide enough current to dimly
  light LEDs on a pin configured (by default) in
  INPUT mode:
  – So if an LED lights dimly, the pin probably hasn’t
    been set to OUTPUT mode
Switching from INPUT to OUTPUT
• Note also that the pull-up resistors are controlled by
  the same registers (internal chip memory locations)
  that control whether a pin is HIGH or LOW
• Consequently, a pin that is configured to have pull-up
  resistors turned on when the pin is an INPUT will have
  the pin configured as HIGH if the pin is then switched
  to an OUTPUT with pinMode()
• This works in the other direction as well, and an output
  pin that is left in a HIGH state will have the pull-up
  resistors set if switched to an input with pinMode()
Special case: digital input pin 13
• Digital pin 13 is harder to use as a digital input
  than the other pins because it has an LED and
  resistor attached to it that's soldered to the board
  on most Arduinos
• If you enable its internal 20 kΩ pull-up resistor, it
  will hang at around 1.7 V instead of the expected
  5 V because the onboard LED and series resistor
  pull the voltage level down, meaning it always
  returns LOW
• If you must use pin 13 as a digital input, use an
  external pull down resistor…
Properties of pins configured as
                OUTPUT
• Pins configured as OUTPUT with pinMode()
  are said to be in a low-impedance state:
  – Can provide a substantial current to other circuits,
    up to 40 mA
  – Enough to brightly light up an LED (via a series
    resistor), or run many types of sensors, but not a
    motor, for example
Properties of pins configured as
              OUTPUT (2)
• Short circuits on Arduino pins, or attempting to
  run high current devices, can damage or destroy
  the output transistors in the pin, or damage the
  entire Atmega chip:
  – Often this will result in a "dead" pin but the remaining
    chip will still function
• It is a good idea to connect OUTPUT pins to other
  devices with 470 Ω or 1kΩ resistors, unless
  maximum current draw from pins is required for
  a particular app
Analog input pins / ADC
• The Atmega controllers used for the Arduino
  contain an onboard 6-channel analog-to-digital
  (A/D) converter:
  – The converter has 10 bit resolution, returning integers
    from 0 to 1023
• While the main function of the analog pins is to
  read analog sensors, the analog pins also have all
  the functionality of general purpose input/output
  (GPIO) pins (the same as digital pins 0 – 13)
Pin mapping
• The analog pins can be used identically to the
  digital pins, using the aliases A0 (for analog
  input 0), A1, etc.
• For example, the code would look like this to
  set analog pin 0 to an output, and to set it
  HIGH:
  – pinMode(A0, OUTPUT);
  – digitalWrite(A0, HIGH);
Pull-up resistors for analog pins
• The analog pins also have pull-up resistors, which
  work identically to pull-up resistors on the digital
  pins
• They are enabled by issuing a command such as:
   – digitalWrite(A0, HIGH); // set pull-up on analog pin 0
  while the pin is an input
• Be aware however that turning on a pull-up will
  affect the values reported by analogRead()
• Note that the same issue as for digital pins
  applies to analog pins when switching from
  INPUT to OUTPUT as regards the pull-up settings
Pulse width modulation
Memory on the Arduino
• Three pools of memory in the microcontroller
  used on Arduino boards (ATmega168):
  – Flash memory (program space) is where the sketch is
    stored [16 kbytes non-volatile, 2k used for
    bootloader]
  – SRAM (static random access memory) is where the
    sketch creates and manipulates variables when it runs
    [1 kbyte volatile]
  – EEPROM is memory space that programmers can use
    to store long-term information [512 bytes non-
    volatile]
SRAM limits
• Not much SRAM available, so can be used up
  quite quickly by defining strings, etc.:
  – char message[] = "I support the Arduino project.";
• If program not running successfully, it may be
  that you’ve run out of SRAM:
  – Try commenting out string definitions, lookup
    tables, large arrays to see if it works without them
  – If interfacing with a PC, move data and/or calculations
    to the PC instead if possible
  – Store strings or data in flash memory instead with
    PROGMEM
Programming techniques

Variables, functions and libraries
Variables
• As mentioned, a variable is a place to store a
  piece of data
• A variable has other advantages over a value like
  a number, once it’s declared (int pin = 13;)
• Most importantly, you can change the value of a
  variable using an assignment (indicated by an
  equals sign), for example:
  – pin = 12;
• The name of the variable is permanently
  associated with a type; only its value changes
Assigning a variable to another
• When you assign one variable to another, you're
  making a copy of its value and storing that copy
  in the location in memory associated with the
  other variable
• Changing one has no effect on the other
• For example, after:
  – int pin = 13;
  – int pin2 = pin;
  – pin = 12;
  only pin has the value 12; pin2 is still 13
Scope: global
• If you want to be able to use a variable anywhere in your
  program, declare it at top of your code (a global variable):
       int pin = 13;
       void setup() {
        pin = 12;
       pinMode(pin, OUTPUT); }
       void loop() {
       digitalWrite(pin, HIGH); }
• Both functions are using pin and referring to the same
  variable, so that changing in one will affect value in the other
• Here, the digitalWrite() function called from loop() will be
  passed a value of 12, since that was assigned in setup()
Scope: local
• If you only need to use a variable in a single
  function, you can declare it there, in which case
  its scope will be limited to that function
• For example:
   void setup()
   {
   int pin = 13;
   pinMode(pin, OUTPUT);
   digitalWrite(pin, HIGH);
   }
Global vs. local scope
• Local scope can make it easier to figure out what
  happens to a variable
• If a variable is global, its value could be changed
  anywhere in the code, meaning that you need to
  understand the whole program to know what will
  happen to the variable
• For example, if your variable has a value you
  didn't expect, it can be much easier to figure out
  where the value came from if the variable has a
  limited scope
Functions
• Segmenting code into functions allows a
  programmer to create modular pieces of code
  that perform a defined task and then return to
  the area of code from which the function was
  "called”
• The typical case for creating a function is
  when one needs to perform the same action
  multiple times in a program
Advantages of code fragments in
              functions
• Functions help the programmer stay organised:
   – Often this helps to conceptualize the program
• Functions codify one action in one place so that the
  function only has to be thought out/debugged once:
   – This also reduces chances for errors in modification if the
     code needs to be changed
• Functions make a sketch smaller/more compact
  because code sections are reused many times
• They make it easier to reuse code in other
  programs, and as a nice side effect, using functions
  also often makes the code more readable
Example: multiply function




• Function needs to be declared outside any other function, so
  "myMultiplyFunction()" can go either above or below the "loop()" area
Calling the example function
• To "call" our simple multiply function, we pass it
  parameters of the data-type that it is expecting:
   void loop{
   inti = 2;
   intj = 3;
   intk;

   k = myMultiplyFunction(i, j); // k now contains 6
   }
Another example: average analog read
intReadSens_and_Condition(){
inti;
intsval = 0;

 for (i = 0; i< 5; i++){
sval = sval + analogRead(0); // sensor on analog pin 0
 }

sval = sval / 5; // average
sval = sval / 4; // scale to 8 bits (0 - 255)
sval = 255 - sval; // invert output
  return sval;
}
Libraries
• Earlier on, we had the Morse code example
• Can also convert its functions into a library
• This allows other people to easily use the code
  that you've written and to easily update it as
  you improve the library
What’s required?
• You need at least two files for a library:
  – Header file (with the extension .h)
  – Source file (with the extension .cpp)
• The header file has definitions for the library:
  basically a listing of everything that's inside;
  while the source file has the actual code

• More at:
  – http://arduino.cc/en/Hacking/LibraryTutorial
Morse.h
#ifndefMorse_h
#define Morse_h

#include "WProgram.h"

class Morse
{
  public:
Morse(int pin);
   void dot();
   void dash();
  private:
int _pin;
};

#endif
Morse.cpp
#include "WProgram.h"            void Morse::dash()
#include "Morse.h"               {
                                 digitalWrite(_pin, HIGH);
Morse::Morse(int pin)              delay(1000);
{                                digitalWrite(_pin, LOW);
pinMode(pin, OUTPUT);              delay(250);
  _pin = pin;                    }
}

void Morse::dot()
{
digitalWrite(_pin, HIGH);
  delay(250);
digitalWrite(_pin, LOW);
  delay(250);
}

More Related Content

PPTX
KEY
Intro to Arduino
PPTX
Introduction to the Arduino
PPTX
Arduino programming
PPTX
Arduino cic3
PDF
Lab2ppt
PDF
Arduino - Peripherals and interface
PDF
Programming arduino makeymakey
Intro to Arduino
Introduction to the Arduino
Arduino programming
Arduino cic3
Lab2ppt
Arduino - Peripherals and interface
Programming arduino makeymakey

What's hot (20)

PDF
Intro to Arduino Revision #2
PDF
IOTC08 The Arduino Platform
PDF
Introduction to Arduino
PDF
Arduino spooky projects_class1
PPTX
Arduino and its hw architecture
PPTX
Arduino slides
PPTX
PPTX
Programming with arduino
PDF
برمجة الأردوينو - اليوم الأول
PDF
Presentation S4A
PDF
Codesign-Oriented Platform for Agile Internet of Things Prototype Development
PDF
LinnStrument : the ultimate open-source hacker instrument
PDF
Introduction to arduino
PPT
Multi Sensory Communication 2/2
PDF
PLC operation part 1
PPTX
Arduino Workshop
PDF
Arduino learning
PDF
Presentation
PDF
Introduction to Arduino and Circuits
Intro to Arduino Revision #2
IOTC08 The Arduino Platform
Introduction to Arduino
Arduino spooky projects_class1
Arduino and its hw architecture
Arduino slides
Programming with arduino
برمجة الأردوينو - اليوم الأول
Presentation S4A
Codesign-Oriented Platform for Agile Internet of Things Prototype Development
LinnStrument : the ultimate open-source hacker instrument
Introduction to arduino
Multi Sensory Communication 2/2
PLC operation part 1
Arduino Workshop
Arduino learning
Presentation
Introduction to Arduino and Circuits
Ad

Viewers also liked (20)

PPS
Robotix Tutorial 8
PPS
Robotix Tutorial 6
PPS
Robotix Tutorial 4
PPS
Robotix Tutorial 9
PPS
Robotix Tutorial 7
PPS
A Tutorial On Ip 2
PPS
A Tutorial On Ip 1
PDF
Freshers guide 2011, iit guwahati
PPS
Robotix Tutorial 5
PPT
Raspberry pi 3
PPTX
Robotics workshop PPT
PPTX
QUADCOPTER
PDF
Quadcopter Technology
PPTX
Introduction to raspberry pi
PDF
QUAD COPTERS FULL PPT
PPT
Raspberry pi : an introduction
PPT
Intro to Arduino
PPTX
How Social Media is Running Our Minds ??
PPTX
Arduino obstacle avoidance robot
PDF
How does a Quadrotor fly? A journey from physics, mathematics, control system...
Robotix Tutorial 8
Robotix Tutorial 6
Robotix Tutorial 4
Robotix Tutorial 9
Robotix Tutorial 7
A Tutorial On Ip 2
A Tutorial On Ip 1
Freshers guide 2011, iit guwahati
Robotix Tutorial 5
Raspberry pi 3
Robotics workshop PPT
QUADCOPTER
Quadcopter Technology
Introduction to raspberry pi
QUAD COPTERS FULL PPT
Raspberry pi : an introduction
Intro to Arduino
How Social Media is Running Our Minds ??
Arduino obstacle avoidance robot
How does a Quadrotor fly? A journey from physics, mathematics, control system...
Ad

Similar to Arduino Foundations (20)

PPTX
INTRODUCTION TO ARDUINO and sensors for arduino.pptx
DOCX
Arduino and Circuits.docx
PPT
arduino.ppt
PDF
Arduino-workshop.computer engineering.pdf
PPT
01 Intro to the Arduino and it's basics.ppt
PDF
02 Sensors and Actuators Understand .pdf
PPTX
arduino and its introduction deep dive ppt.pptx
PPTX
INTODUCTION OF IOT AND INTERFACING WITH ARDUINO UNO
PPTX
02 General Purpose Input - Output on the Arduino
PPTX
Introduction To Arduino-converted for s.pptx
PDF
Arduino microcontroller ins and outs with pin diagram
PPTX
Arduino Workshop Slides
PPTX
teststststststLecture_3_2022_Arduino.pptx
PPT
arduino Simon power point presentation.ppt
KEY
Hello Arduino.
DOCX
Arduino windows remote control
PPTX
Fun with arduino
PDF
Making things sense - Day 1 (May 2011)
PPT
arduinoSimon.ppt
INTRODUCTION TO ARDUINO and sensors for arduino.pptx
Arduino and Circuits.docx
arduino.ppt
Arduino-workshop.computer engineering.pdf
01 Intro to the Arduino and it's basics.ppt
02 Sensors and Actuators Understand .pdf
arduino and its introduction deep dive ppt.pptx
INTODUCTION OF IOT AND INTERFACING WITH ARDUINO UNO
02 General Purpose Input - Output on the Arduino
Introduction To Arduino-converted for s.pptx
Arduino microcontroller ins and outs with pin diagram
Arduino Workshop Slides
teststststststLecture_3_2022_Arduino.pptx
arduino Simon power point presentation.ppt
Hello Arduino.
Arduino windows remote control
Fun with arduino
Making things sense - Day 1 (May 2011)
arduinoSimon.ppt

More from John Breslin (20)

PDF
Ireland: Island of Innovation and Entrepreneurship
PDF
Old Ireland in Colour
PDF
A Balanced Routing Algorithm for Blockchain Offline Channels using Flocking
PDF
Collusion Attack from Hubs in the Blockchain Offline Channel Network
PDF
Collaborative Leadership to Increase the Northern & Western Region’s Innovati...
PDF
TRICS: Teaching Researchers and Innovators how to Create Startups
PDF
Entrepreneurship is in Our DNA
PDF
Galway City Innovation District
PDF
Innovation Districts and Innovation Hubs
PDF
Disciplined mHealth Entrepreneurship
PDF
Searching for Startups
PPTX
Intellectual Property: Protecting Ideas, Designs and Brands in the Real World...
PDF
Innovation and Entrepreneurship: Tips, Tools and Tricks
PDF
Growing Galway's Startup Community
PDF
Startup Community: What Galway Can Do Next
PDF
Adding More Semantics to the Social Web
PDF
Communities and Tech: Build Which and What Will Come?
PDF
Data Analytics and Industry-Academic Partnerships: An Irish Perspective
PPT
“I Like” - Analysing Interactions within Social Networks to Assert the Trustw...
PPT
John Breslin at the Innovation Academy
Ireland: Island of Innovation and Entrepreneurship
Old Ireland in Colour
A Balanced Routing Algorithm for Blockchain Offline Channels using Flocking
Collusion Attack from Hubs in the Blockchain Offline Channel Network
Collaborative Leadership to Increase the Northern & Western Region’s Innovati...
TRICS: Teaching Researchers and Innovators how to Create Startups
Entrepreneurship is in Our DNA
Galway City Innovation District
Innovation Districts and Innovation Hubs
Disciplined mHealth Entrepreneurship
Searching for Startups
Intellectual Property: Protecting Ideas, Designs and Brands in the Real World...
Innovation and Entrepreneurship: Tips, Tools and Tricks
Growing Galway's Startup Community
Startup Community: What Galway Can Do Next
Adding More Semantics to the Social Web
Communities and Tech: Build Which and What Will Come?
Data Analytics and Industry-Academic Partnerships: An Irish Perspective
“I Like” - Analysing Interactions within Social Networks to Assert the Trustw...
John Breslin at the Innovation Academy

Recently uploaded (20)

PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPT
Teaching material agriculture food technology
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
1. Introduction to Computer Programming.pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
Spectroscopy.pptx food analysis technology
PDF
Electronic commerce courselecture one. Pdf
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
NewMind AI Weekly Chronicles - August'25-Week II
Assigned Numbers - 2025 - Bluetooth® Document
MYSQL Presentation for SQL database connectivity
Digital-Transformation-Roadmap-for-Companies.pptx
Teaching material agriculture food technology
Agricultural_Statistics_at_a_Glance_2022_0.pdf
1. Introduction to Computer Programming.pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Spectroscopy.pptx food analysis technology
Electronic commerce courselecture one. Pdf
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Group 1 Presentation -Planning and Decision Making .pptx
Spectral efficient network and resource selection model in 5G networks
Unlocking AI with Model Context Protocol (MCP)
The Rise and Fall of 3GPP – Time for a Sabbatical?
Encapsulation_ Review paper, used for researhc scholars
Mobile App Security Testing_ A Comprehensive Guide.pdf
Accuracy of neural networks in brain wave diagnosis of schizophrenia
gpt5_lecture_notes_comprehensive_20250812015547.pdf

Arduino Foundations

  • 1. Arduino foundations: sketch basics, what’s on board, more programming http://arduino.cc/en/Tutorial/Founda tions
  • 2. Basics What’s a sketch and how does it work?
  • 3. Sketch: comments and variables • A sketch is the name Arduino uses for a program • Comments are used to explain what the program does: – Use /* blah */ to comment out an area of code – Use // to add a comment to the end of a line of code • A variable is a place for storing data: – type name = value; – int ledPin = 13; – Every time ledPin is referred to in code, value is retrieved – Can also change variable value in code
  • 4. Sketch: functions • Functions are named pieces of code that can be used from elsewhere in a sketch: – setup(), loop(), pinMode() • First line of a function provides info about it, like its name (e.g. setup), and the text before / after the name specify its return type and parameters: void setup() { [body of function] }
  • 5. Sketch: functions (2) • Can call a pre-defined function as part of the Arduino language or functions defined in your sketch: – e.g. pinMode(ledPin, OUTPUT); calls pinMode() with the parameters ledPin and OUTPUT • We’ll now describe some sample functions that you may have seen already
  • 6. Function: pinmode() • The pinMode() function configures a pin as either an input or an output • To use it, you pass it the number of the pin to configure and the constant INPUT or OUTPUT • When configured as an input, a pin can detect the state of a sensor like a pushbutton • As an output, it can drive a device like an LED
  • 7. Functions: digitalWrite(), delay() • digitalWrite() outputs a value on a pin • For example, the line: – digitalWrite(ledPin, HIGH); sets the ledPin (pin 13) to HIGH, or 5 volts • Writing a LOW to the pin connects it to ground, or 0 volts • delay() causes the Arduino to wait for the specified number of milliseconds before continuing on to the next line • There are 1000 milliseconds in a second, so the line: – delay(1000); creates a one second delay
  • 8. Special functions: setup(), loop() • There are two special functions that are a part of everyArduino sketch: setup() and loop(): – setup() is called once, when the sketch starts • It's a good place to do setup tasks like setting pin modes or initializing libraries – The loop() function is called over and over and is heart of most sketches • You need to include both functions in your sketch, even if you don't need them for anything
  • 9. Exercises, based on ‘blink’ code 1. Change the code so that the LED is on for 100 milliseconds and off for 1000 2. Change the code so that the LED turns on when the sketch starts and stays on
  • 10. Problem • Write a sketch that turns on and off the onboard LED (pin 13) in the Morse code-style SOS sequence ‘· · · — — — · · ·’, assuming that a unit is of one second duration, and Morse code is composed of the following five elements: – short mark, dot or 'dit' (·) — 'dot duration' is one unit long; – longer mark, dash or 'dah' (–) — three units long; – inter-element gap between the dots and dashes within a character — one unit long; – short gap (between letters) — three units long; – medium gap (between words) — seven units long. – http://en.wikipedia.org/wiki/Morse_code#Representation. 2C_timing_and_speeds
  • 11. Morse code code int pin = 13; void setup() { pinMode(pin, OUTPUT); } void loop() { dot(); dot(); dot(); delay(2000); // plus last one second delay from the dot function = 3 dash(); dash(); dash(); delay(2000); // plus last one second delay from the dash function = 3 dot(); dot(); dot(); delay(6000); // plus last one second delay from the dot function = 7 }
  • 12. Morse code code (2) void dot() { digitalWrite(pin, HIGH); delay(1000); digitalWrite(pin, LOW); delay(1000); } void dash() { digitalWrite(pin, HIGH); delay(3000); digitalWrite(pin, LOW); delay(1000); }
  • 13. Overview • First, we have the dot() and dash() functions that do the actual blinking • Second, there's the pin variable which the functions use to determine which pin to use • Finally, there's the call to pinMode() that initialises the pin as an output
  • 14. On the microcontroller Pins and memory
  • 15. Configuring digital pins • Note: the vast majority of Arduino (Atmega) analog pins may be configured, and used, in exactly the same manner as digital pins • We’ll look at: – Properties of pins configured as INPUT – Pull-up resistors – Properties of pins configured as OUTPUT
  • 16. Properties of pins configured as INPUT • Arduino pins default to INPUT: – Don’t need to be explicitly defined as INPUT-type using pinMode() • Input pins are high impedance (order of M ): – Will draw little current (order of A) – Suitable for low current apps like capacitive touch sensors, FSRs, phototransistors / photodiodes, etc. • But with nothing connected, become sensitive to external noise from the environment
  • 17. Pull-up resistors • Used to steer an input to a particular (default) state if no input is present • Could add a pull-up resistor to +5 volts or a pull- down resistor to 0 volts, e.g. using a 10 kΩ value • There are built-in 20 kΩ pull-up resistors on the Atmega chips, which can be enabled via software: – pinMode(pinX, INPUT); // set pin to input – digitalWrite(pinX, HIGH); // turn on pull-up resistors
  • 18. Pull-up resistors (2) • Pull-ups will provide enough current to dimly light LEDs on a pin configured (by default) in INPUT mode: – So if an LED lights dimly, the pin probably hasn’t been set to OUTPUT mode
  • 19. Switching from INPUT to OUTPUT • Note also that the pull-up resistors are controlled by the same registers (internal chip memory locations) that control whether a pin is HIGH or LOW • Consequently, a pin that is configured to have pull-up resistors turned on when the pin is an INPUT will have the pin configured as HIGH if the pin is then switched to an OUTPUT with pinMode() • This works in the other direction as well, and an output pin that is left in a HIGH state will have the pull-up resistors set if switched to an input with pinMode()
  • 20. Special case: digital input pin 13 • Digital pin 13 is harder to use as a digital input than the other pins because it has an LED and resistor attached to it that's soldered to the board on most Arduinos • If you enable its internal 20 kΩ pull-up resistor, it will hang at around 1.7 V instead of the expected 5 V because the onboard LED and series resistor pull the voltage level down, meaning it always returns LOW • If you must use pin 13 as a digital input, use an external pull down resistor…
  • 21. Properties of pins configured as OUTPUT • Pins configured as OUTPUT with pinMode() are said to be in a low-impedance state: – Can provide a substantial current to other circuits, up to 40 mA – Enough to brightly light up an LED (via a series resistor), or run many types of sensors, but not a motor, for example
  • 22. Properties of pins configured as OUTPUT (2) • Short circuits on Arduino pins, or attempting to run high current devices, can damage or destroy the output transistors in the pin, or damage the entire Atmega chip: – Often this will result in a "dead" pin but the remaining chip will still function • It is a good idea to connect OUTPUT pins to other devices with 470 Ω or 1kΩ resistors, unless maximum current draw from pins is required for a particular app
  • 23. Analog input pins / ADC • The Atmega controllers used for the Arduino contain an onboard 6-channel analog-to-digital (A/D) converter: – The converter has 10 bit resolution, returning integers from 0 to 1023 • While the main function of the analog pins is to read analog sensors, the analog pins also have all the functionality of general purpose input/output (GPIO) pins (the same as digital pins 0 – 13)
  • 24. Pin mapping • The analog pins can be used identically to the digital pins, using the aliases A0 (for analog input 0), A1, etc. • For example, the code would look like this to set analog pin 0 to an output, and to set it HIGH: – pinMode(A0, OUTPUT); – digitalWrite(A0, HIGH);
  • 25. Pull-up resistors for analog pins • The analog pins also have pull-up resistors, which work identically to pull-up resistors on the digital pins • They are enabled by issuing a command such as: – digitalWrite(A0, HIGH); // set pull-up on analog pin 0 while the pin is an input • Be aware however that turning on a pull-up will affect the values reported by analogRead() • Note that the same issue as for digital pins applies to analog pins when switching from INPUT to OUTPUT as regards the pull-up settings
  • 27. Memory on the Arduino • Three pools of memory in the microcontroller used on Arduino boards (ATmega168): – Flash memory (program space) is where the sketch is stored [16 kbytes non-volatile, 2k used for bootloader] – SRAM (static random access memory) is where the sketch creates and manipulates variables when it runs [1 kbyte volatile] – EEPROM is memory space that programmers can use to store long-term information [512 bytes non- volatile]
  • 28. SRAM limits • Not much SRAM available, so can be used up quite quickly by defining strings, etc.: – char message[] = "I support the Arduino project."; • If program not running successfully, it may be that you’ve run out of SRAM: – Try commenting out string definitions, lookup tables, large arrays to see if it works without them – If interfacing with a PC, move data and/or calculations to the PC instead if possible – Store strings or data in flash memory instead with PROGMEM
  • 30. Variables • As mentioned, a variable is a place to store a piece of data • A variable has other advantages over a value like a number, once it’s declared (int pin = 13;) • Most importantly, you can change the value of a variable using an assignment (indicated by an equals sign), for example: – pin = 12; • The name of the variable is permanently associated with a type; only its value changes
  • 31. Assigning a variable to another • When you assign one variable to another, you're making a copy of its value and storing that copy in the location in memory associated with the other variable • Changing one has no effect on the other • For example, after: – int pin = 13; – int pin2 = pin; – pin = 12; only pin has the value 12; pin2 is still 13
  • 32. Scope: global • If you want to be able to use a variable anywhere in your program, declare it at top of your code (a global variable): int pin = 13; void setup() { pin = 12; pinMode(pin, OUTPUT); } void loop() { digitalWrite(pin, HIGH); } • Both functions are using pin and referring to the same variable, so that changing in one will affect value in the other • Here, the digitalWrite() function called from loop() will be passed a value of 12, since that was assigned in setup()
  • 33. Scope: local • If you only need to use a variable in a single function, you can declare it there, in which case its scope will be limited to that function • For example: void setup() { int pin = 13; pinMode(pin, OUTPUT); digitalWrite(pin, HIGH); }
  • 34. Global vs. local scope • Local scope can make it easier to figure out what happens to a variable • If a variable is global, its value could be changed anywhere in the code, meaning that you need to understand the whole program to know what will happen to the variable • For example, if your variable has a value you didn't expect, it can be much easier to figure out where the value came from if the variable has a limited scope
  • 35. Functions • Segmenting code into functions allows a programmer to create modular pieces of code that perform a defined task and then return to the area of code from which the function was "called” • The typical case for creating a function is when one needs to perform the same action multiple times in a program
  • 36. Advantages of code fragments in functions • Functions help the programmer stay organised: – Often this helps to conceptualize the program • Functions codify one action in one place so that the function only has to be thought out/debugged once: – This also reduces chances for errors in modification if the code needs to be changed • Functions make a sketch smaller/more compact because code sections are reused many times • They make it easier to reuse code in other programs, and as a nice side effect, using functions also often makes the code more readable
  • 37. Example: multiply function • Function needs to be declared outside any other function, so "myMultiplyFunction()" can go either above or below the "loop()" area
  • 38. Calling the example function • To "call" our simple multiply function, we pass it parameters of the data-type that it is expecting: void loop{ inti = 2; intj = 3; intk; k = myMultiplyFunction(i, j); // k now contains 6 }
  • 39. Another example: average analog read intReadSens_and_Condition(){ inti; intsval = 0; for (i = 0; i< 5; i++){ sval = sval + analogRead(0); // sensor on analog pin 0 } sval = sval / 5; // average sval = sval / 4; // scale to 8 bits (0 - 255) sval = 255 - sval; // invert output return sval; }
  • 40. Libraries • Earlier on, we had the Morse code example • Can also convert its functions into a library • This allows other people to easily use the code that you've written and to easily update it as you improve the library
  • 41. What’s required? • You need at least two files for a library: – Header file (with the extension .h) – Source file (with the extension .cpp) • The header file has definitions for the library: basically a listing of everything that's inside; while the source file has the actual code • More at: – http://arduino.cc/en/Hacking/LibraryTutorial
  • 42. Morse.h #ifndefMorse_h #define Morse_h #include "WProgram.h" class Morse { public: Morse(int pin); void dot(); void dash(); private: int _pin; }; #endif
  • 43. Morse.cpp #include "WProgram.h" void Morse::dash() #include "Morse.h" { digitalWrite(_pin, HIGH); Morse::Morse(int pin) delay(1000); { digitalWrite(_pin, LOW); pinMode(pin, OUTPUT); delay(250); _pin = pin; } } void Morse::dot() { digitalWrite(_pin, HIGH); delay(250); digitalWrite(_pin, LOW); delay(250); }