SlideShare una empresa de Scribd logo
1 de 43
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);
}

Más contenido relacionado

La actualidad más candente

Arduino learning
Arduino   learningArduino   learning
Arduino learning
Anil Yadav
 

La actualidad más candente (20)

Introduction to Arduino
Introduction to ArduinoIntroduction to Arduino
Introduction to Arduino
 
Intro to Arduino Revision #2
Intro to Arduino Revision #2Intro to Arduino Revision #2
Intro to Arduino Revision #2
 
IOTC08 The Arduino Platform
IOTC08 The Arduino PlatformIOTC08 The Arduino Platform
IOTC08 The Arduino Platform
 
Introduction to Arduino
Introduction to ArduinoIntroduction to Arduino
Introduction to Arduino
 
Arduino spooky projects_class1
Arduino spooky projects_class1Arduino spooky projects_class1
Arduino spooky projects_class1
 
Arduino and its hw architecture
Arduino and its hw architectureArduino and its hw architecture
Arduino and its hw architecture
 
Arduino slides
Arduino slidesArduino slides
Arduino slides
 
Arduino uno
Arduino unoArduino uno
Arduino uno
 
Programming with arduino
Programming with arduinoProgramming with arduino
Programming with arduino
 
برمجة الأردوينو - اليوم الأول
برمجة الأردوينو - اليوم الأولبرمجة الأردوينو - اليوم الأول
برمجة الأردوينو - اليوم الأول
 
Presentation S4A
Presentation S4A Presentation S4A
Presentation S4A
 
Codesign-Oriented Platform for Agile Internet of Things Prototype Development
Codesign-Oriented Platform for Agile Internet of Things Prototype DevelopmentCodesign-Oriented Platform for Agile Internet of Things Prototype Development
Codesign-Oriented Platform for Agile Internet of Things Prototype Development
 
LinnStrument : the ultimate open-source hacker instrument
LinnStrument : the ultimate open-source hacker instrumentLinnStrument : the ultimate open-source hacker instrument
LinnStrument : the ultimate open-source hacker instrument
 
Introduction to arduino
Introduction to arduinoIntroduction to arduino
Introduction to arduino
 
Multi Sensory Communication 2/2
Multi Sensory Communication 2/2Multi Sensory Communication 2/2
Multi Sensory Communication 2/2
 
PLC operation part 1
PLC operation part 1PLC operation part 1
PLC operation part 1
 
Arduino Workshop
Arduino WorkshopArduino Workshop
Arduino Workshop
 
Arduino learning
Arduino   learningArduino   learning
Arduino learning
 
Presentation
PresentationPresentation
Presentation
 
Introduction to Arduino and Circuits
Introduction to Arduino and CircuitsIntroduction to Arduino and Circuits
Introduction to Arduino and Circuits
 

Destacado

Robotix Tutorial 8
Robotix Tutorial 8Robotix Tutorial 8
Robotix Tutorial 8
ankuredkie
 
Robotix Tutorial 6
Robotix Tutorial 6Robotix Tutorial 6
Robotix Tutorial 6
ankuredkie
 
Robotix Tutorial 4
Robotix Tutorial 4Robotix Tutorial 4
Robotix Tutorial 4
ankuredkie
 
Robotix Tutorial 9
Robotix Tutorial 9Robotix Tutorial 9
Robotix Tutorial 9
ankuredkie
 
Robotix Tutorial 7
Robotix Tutorial 7Robotix Tutorial 7
Robotix Tutorial 7
ankuredkie
 
A Tutorial On Ip 2
A Tutorial On Ip 2A Tutorial On Ip 2
A Tutorial On Ip 2
ankuredkie
 
A Tutorial On Ip 1
A Tutorial On Ip 1A Tutorial On Ip 1
A Tutorial On Ip 1
ankuredkie
 
Robotix Tutorial 5
Robotix Tutorial 5Robotix Tutorial 5
Robotix Tutorial 5
ankuredkie
 
Robotics workshop PPT
Robotics  workshop PPTRobotics  workshop PPT
Robotics workshop PPT
avikdhupar
 
How does a Quadrotor fly? A journey from physics, mathematics, control system...
How does a Quadrotor fly? A journey from physics, mathematics, control system...How does a Quadrotor fly? A journey from physics, mathematics, control system...
How does a Quadrotor fly? A journey from physics, mathematics, control system...
Corrado Santoro
 

Destacado (20)

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

Similar a Arduino Foundations

4 IOT 18ISDE712 MODULE 4 IoT Physical Devices and End Point-Aurdino Uno.pdf
4 IOT 18ISDE712  MODULE 4 IoT Physical Devices and End Point-Aurdino  Uno.pdf4 IOT 18ISDE712  MODULE 4 IoT Physical Devices and End Point-Aurdino  Uno.pdf
4 IOT 18ISDE712 MODULE 4 IoT Physical Devices and End Point-Aurdino Uno.pdf
Jayanthi Kannan MK
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
SAURABHKUMAR892774
 
arduinocourse-180308074529 (1).pdf
arduinocourse-180308074529 (1).pdfarduinocourse-180308074529 (1).pdf
arduinocourse-180308074529 (1).pdf
ssusere5db05
 
teststststststLecture_3_2022_Arduino.pptx
teststststststLecture_3_2022_Arduino.pptxteststststststLecture_3_2022_Arduino.pptx
teststststststLecture_3_2022_Arduino.pptx
ethannguyen1618
 
introductiontoarduino-111120102058-phpapp02.pdf
introductiontoarduino-111120102058-phpapp02.pdfintroductiontoarduino-111120102058-phpapp02.pdf
introductiontoarduino-111120102058-phpapp02.pdf
HebaEng
 

Similar a Arduino Foundations (20)

Arduino Programming Basic
Arduino Programming BasicArduino Programming Basic
Arduino Programming Basic
 
Arduino intro.pptx
Arduino intro.pptxArduino intro.pptx
Arduino intro.pptx
 
Arduino windows remote control
Arduino windows remote controlArduino windows remote control
Arduino windows remote control
 
IOT ARDUINO UNO.pptx
IOT ARDUINO UNO.pptxIOT ARDUINO UNO.pptx
IOT ARDUINO UNO.pptx
 
ARDUINO AND ITS PIN CONFIGURATION
 ARDUINO AND ITS PIN  CONFIGURATION ARDUINO AND ITS PIN  CONFIGURATION
ARDUINO AND ITS PIN CONFIGURATION
 
4 IOT 18ISDE712 MODULE 4 IoT Physical Devices and End Point-Aurdino Uno.pdf
4 IOT 18ISDE712  MODULE 4 IoT Physical Devices and End Point-Aurdino  Uno.pdf4 IOT 18ISDE712  MODULE 4 IoT Physical Devices and End Point-Aurdino  Uno.pdf
4 IOT 18ISDE712 MODULE 4 IoT Physical Devices and End Point-Aurdino Uno.pdf
 
Neno Project.docx
Neno Project.docxNeno Project.docx
Neno Project.docx
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
Arduino course
Arduino courseArduino course
Arduino course
 
arduinocourse-180308074529 (1).pdf
arduinocourse-180308074529 (1).pdfarduinocourse-180308074529 (1).pdf
arduinocourse-180308074529 (1).pdf
 
teststststststLecture_3_2022_Arduino.pptx
teststststststLecture_3_2022_Arduino.pptxteststststststLecture_3_2022_Arduino.pptx
teststststststLecture_3_2022_Arduino.pptx
 
AVR arduino dasar
AVR arduino dasarAVR arduino dasar
AVR arduino dasar
 
Introduction to arduino!
Introduction to arduino!Introduction to arduino!
Introduction to arduino!
 
Arduino اردوينو
Arduino اردوينوArduino اردوينو
Arduino اردوينو
 
Arduino_Beginner.pptx
Arduino_Beginner.pptxArduino_Beginner.pptx
Arduino_Beginner.pptx
 
Fun with arduino
Fun with arduinoFun with arduino
Fun with arduino
 
Introduction to Arduino 16822775 (2).ppt
Introduction to Arduino 16822775 (2).pptIntroduction to Arduino 16822775 (2).ppt
Introduction to Arduino 16822775 (2).ppt
 
arduinoworkshop-160204051621.pdf
arduinoworkshop-160204051621.pdfarduinoworkshop-160204051621.pdf
arduinoworkshop-160204051621.pdf
 
Ardui no
Ardui no Ardui no
Ardui no
 
introductiontoarduino-111120102058-phpapp02.pdf
introductiontoarduino-111120102058-phpapp02.pdfintroductiontoarduino-111120102058-phpapp02.pdf
introductiontoarduino-111120102058-phpapp02.pdf
 

Más de John Breslin

Más de John Breslin (20)

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

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 

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