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

What's hot (20)

PDF
Intro to Arduino Revision #2
Qtechknow
 
PDF
IOTC08 The Arduino Platform
Eoin Brazil
 
PDF
Introduction to Arduino
Karim El-Rayes
 
PDF
Arduino spooky projects_class1
Felipe Belarmino
 
PPTX
Arduino and its hw architecture
Zeeshan Rafiq
 
PPTX
Arduino slides
sdcharle
 
PPTX
Arduino uno
SAKIBNESARRATUL20135
 
PPTX
Programming with arduino
Makers of India
 
PDF
برمجة الأردوينو - اليوم الأول
Ahmed Sakr
 
PDF
Presentation S4A
Pedro González Romero
 
PDF
Codesign-Oriented Platform for Agile Internet of Things Prototype Development
Jonathan Ruiz de Garibay
 
PDF
LinnStrument : the ultimate open-source hacker instrument
Geert Bevin
 
PDF
Introduction to arduino
Jawaher Abdulwahab Fadhil
 
PPT
Multi Sensory Communication 2/2
Satoru Tokuhisa
 
PDF
PLC operation part 1
Sakshi Vashist
 
PPTX
Arduino Workshop
atuline
 
PDF
Arduino learning
Anil Yadav
 
PDF
Presentation
Edson Silva
 
PDF
Introduction to Arduino and Circuits
Jason Griffey
 
Intro to Arduino Revision #2
Qtechknow
 
IOTC08 The Arduino Platform
Eoin Brazil
 
Introduction to Arduino
Karim El-Rayes
 
Arduino spooky projects_class1
Felipe Belarmino
 
Arduino and its hw architecture
Zeeshan Rafiq
 
Arduino slides
sdcharle
 
Programming with arduino
Makers of India
 
برمجة الأردوينو - اليوم الأول
Ahmed Sakr
 
Presentation S4A
Pedro González Romero
 
Codesign-Oriented Platform for Agile Internet of Things Prototype Development
Jonathan Ruiz de Garibay
 
LinnStrument : the ultimate open-source hacker instrument
Geert Bevin
 
Introduction to arduino
Jawaher Abdulwahab Fadhil
 
Multi Sensory Communication 2/2
Satoru Tokuhisa
 
PLC operation part 1
Sakshi Vashist
 
Arduino Workshop
atuline
 
Arduino learning
Anil Yadav
 
Presentation
Edson Silva
 
Introduction to Arduino and Circuits
Jason Griffey
 

Viewers also liked (20)

PPS
Robotix Tutorial 8
ankuredkie
 
PPS
Robotix Tutorial 6
ankuredkie
 
PPS
Robotix Tutorial 4
ankuredkie
 
PPS
Robotix Tutorial 9
ankuredkie
 
PPS
Robotix Tutorial 7
ankuredkie
 
PPS
A Tutorial On Ip 2
ankuredkie
 
PPS
A Tutorial On Ip 1
ankuredkie
 
PDF
Freshers guide 2011, iit guwahati
Siddharth Pipriya
 
PPS
Robotix Tutorial 5
ankuredkie
 
PPT
Raspberry pi 3
Inocentshuja Ahmad
 
PPTX
Robotics workshop PPT
avikdhupar
 
PPTX
QUADCOPTER
tusarjena22
 
PDF
Quadcopter Technology
Michael Bseliss
 
PPTX
Introduction to raspberry pi
praveen_23
 
PDF
QUAD COPTERS FULL PPT
Girija Sankar Dash
 
PPT
Raspberry pi : an introduction
LTG Oxford
 
PPT
Intro to Arduino
avikdhupar
 
PPTX
How Social Media is Running Our Minds ??
Pulkit Agarwal
 
PPTX
Arduino obstacle avoidance robot
Steven Radigan
 
PDF
How does a Quadrotor fly? A journey from physics, mathematics, control system...
Corrado Santoro
 
Robotix Tutorial 8
ankuredkie
 
Robotix Tutorial 6
ankuredkie
 
Robotix Tutorial 4
ankuredkie
 
Robotix Tutorial 9
ankuredkie
 
Robotix Tutorial 7
ankuredkie
 
A Tutorial On Ip 2
ankuredkie
 
A Tutorial On Ip 1
ankuredkie
 
Freshers guide 2011, iit guwahati
Siddharth Pipriya
 
Robotix Tutorial 5
ankuredkie
 
Raspberry pi 3
Inocentshuja Ahmad
 
Robotics workshop PPT
avikdhupar
 
QUADCOPTER
tusarjena22
 
Quadcopter Technology
Michael Bseliss
 
Introduction to raspberry pi
praveen_23
 
QUAD COPTERS FULL PPT
Girija Sankar Dash
 
Raspberry pi : an introduction
LTG Oxford
 
Intro to Arduino
avikdhupar
 
How Social Media is Running Our Minds ??
Pulkit Agarwal
 
Arduino obstacle avoidance robot
Steven Radigan
 
How does a Quadrotor fly? A journey from physics, mathematics, control system...
Corrado Santoro
 
Ad

Similar to Arduino Foundations (20)

PPTX
Arduino intro.pptx
SanthanaMari11
 
DOCX
Arduino windows remote control
VilayatAli5
 
PPTX
arduino and its introduction deep dive ppt.pptx
SruSru1
 
PPTX
IOT ARDUINO UNO.pptx
SanaMateen7
 
PPT
01 Intro to the Arduino and it's basics.ppt
pindi2197
 
PDF
Mechatronics material . Mechanical engineering
sachin chaurasia
 
PPT
ARDUINO AND ITS PIN CONFIGURATION
soma saikiran
 
PDF
4 IOT 18ISDE712 MODULE 4 IoT Physical Devices and End Point-Aurdino Uno.pdf
Jayanthi Kannan MK
 
DOCX
Neno Project.docx
AditiBhushan3
 
PPT
Arduino_CSE ece ppt for working and principal of arduino.ppt
SAURABHKUMAR892774
 
PPTX
Arduino course
Ahmed Shelbaya
 
PDF
arduinocourse-180308074529 (1).pdf
ssusere5db05
 
PPTX
Arduino . .
dryazhinians
 
PDF
Arduino microcontroller ins and outs with pin diagram
ArifatunNesa
 
PPTX
teststststststLecture_3_2022_Arduino.pptx
ethannguyen1618
 
PDF
The document proceeds to explain the main components of an Arduino Uno board ...
QucngV
 
PDF
AVR arduino dasar
Oktaf Kharisma
 
PPTX
Introduction To Arduino-converted for s.pptx
rtnmsn
 
PPTX
Introduction to arduino!
Makers of India
 
Arduino intro.pptx
SanthanaMari11
 
Arduino windows remote control
VilayatAli5
 
arduino and its introduction deep dive ppt.pptx
SruSru1
 
IOT ARDUINO UNO.pptx
SanaMateen7
 
01 Intro to the Arduino and it's basics.ppt
pindi2197
 
Mechatronics material . Mechanical engineering
sachin chaurasia
 
ARDUINO AND ITS PIN CONFIGURATION
soma saikiran
 
4 IOT 18ISDE712 MODULE 4 IoT Physical Devices and End Point-Aurdino Uno.pdf
Jayanthi Kannan MK
 
Neno Project.docx
AditiBhushan3
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
SAURABHKUMAR892774
 
Arduino course
Ahmed Shelbaya
 
arduinocourse-180308074529 (1).pdf
ssusere5db05
 
Arduino . .
dryazhinians
 
Arduino microcontroller ins and outs with pin diagram
ArifatunNesa
 
teststststststLecture_3_2022_Arduino.pptx
ethannguyen1618
 
The document proceeds to explain the main components of an Arduino Uno board ...
QucngV
 
AVR arduino dasar
Oktaf Kharisma
 
Introduction To Arduino-converted for s.pptx
rtnmsn
 
Introduction to arduino!
Makers of India
 
Ad

More from John Breslin (20)

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

Recently uploaded (20)

PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
Advancing WebDriver BiDi support in WebKit
Igalia
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
July Patch Tuesday
Ivanti
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
Biography of Daniel Podor.pdf
Daniel Podor
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Advancing WebDriver BiDi support in WebKit
Igalia
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
July Patch Tuesday
Ivanti
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Biography of Daniel Podor.pdf
Daniel Podor
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 

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); }