Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev...

35
Basics What is Arduino ? Arduino is an open-source prototyping platform based on easy-to-use hardware and software. Arduino boards are able to read inputs - light on a sensor, a finger on a button, or a Twitter message - and turn it into an output - activating a motor, turning on an LED, publishing something online. You can tell your board what to do by sending a set of instructions to the microcontroller on the board. To do so you use the Arduino programming language (based on Wiring ), and the Arduino Software (IDE) , based on Processing . Over the years Arduino has been the brain of thousands of projects, from everyday objects to complex scientific instruments. A worldwide community of makers - students, hobbyists, artists, programmers, and professionals - has gathered around this open-source platform, their contributions have added up to an incredible amount of accessible knowledge that can be of great help to novices and experts alike. Arduino was born at the Ivrea Interaction Design Institute as an easy tool for fast prototyping, aimed at students without a background in electronics and programming. As soon as it reached a wider community, the Arduino board started changing to adapt to new needs and challenges, differentiating its offer from simple 8-bit boards to products for IoT applications, wearable, 3D printing, and embedded environments. All Arduino boards are completely open-source, empowering users to build them independently and eventually adapt them to their particular needs. Thesoftware , too, is open-source, and it is growing through the contributions of users worldwide. Why Arduino ? Thanks to its simple and accessible user experience, Arduino has been used in thousands of different projects and applications. The Arduino software is easy-to-use for beginners, yet flexible enough for advanced users. It runs on Mac, Windows, and Linux. Teachers and students use it to build low cost scientific instruments, to prove chemistry and physics principles, or to get started with programming and robotics. Designers and architects build interactive prototypes, musicians and artists use it for installations and to experiment with new musical instruments. Makers, of course, use it to build many of the projects exhibited at the Maker Faire, for example. Arduino is a key tool to learn new things. Anyone - children, hobbyists, artists, programmers - can start tinkering just following the step by step instructions of a kit, or sharing ideas online with other members of the Arduino community. There are many other microcontrollers and microcontroller platforms available for physical computing. Parallax Basic Stamp, Netmedia's BX-24, Phidgets, MIT's Handyboard, and many others offer similar functionality. All of these tools take the messy details of microcontroller programming and wrap it up in an easy-to-use package. Arduino also simplifies the process of working with microcontrollers, but it offers some advantage for teachers, students, and interested amateurs over other systems: Inexpensive - Arduino boards are relatively inexpensive compared to other microcontroller platforms. The least expensive version of the Arduino module can be assembled by hand, and even the pre- assembled Arduino modules cost less than $50 Cross-platform - The Arduino Software (IDE) runs on Windows, Macintosh OSX, and Linux operating systems. Most microcontroller systems are limited to Windows. Simple, clear programming environment - The Arduino Software (IDE) is easy-to-use for beginners, yet flexible enough for advanced users to take advantage of as well. For teachers, it's conveniently based on the Processing programming environment, so students learning to program in that environment will be familiar with how theArduino IDE works. Open source and extensible software - The Arduino software is published as open source tools, available for extension by experienced programmers. The language can be expanded through C++ libraries, and people wanting to understand the technical details can make the leap from Arduino to the AVR C programming language on which it's based. Similarly, you can add AVR-C code directly into your Arduino programs if you want to.

Transcript of Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev...

Page 1: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

BasicsWhat is Arduino?Arduino is an open-source prototyping platform based on easy-to-use hardware and software. Arduinoboards are able to read inputs - light on a sensor, a finger on a button, or a Twitter message - and turnit into an output - activating a motor, turning on an LED, publishing something online. You can tellyour board what to do by sending a set of instructions to the microcontroller on the board. To do so youuse the Arduino programming language (based on Wiring), and the Arduino Software (IDE), based onProcessing.

Over the years Arduino has been the brain of thousands of projects, from everyday objects to complexscientific instruments. A worldwide community of makers - students, hobbyists, artists, programmers,and professionals - has gathered around this open-source platform, their contributions have added up toan incredible amount of accessible knowledge that can be of great help to novices and experts alike.

Arduino was born at the Ivrea Interaction Design Institute as an easy tool for fast prototyping, aimed atstudents without a background in electronics and programming. As soon as it reached a wider community,the Arduino board started changing to adapt to new needs and challenges, differentiating its offer fromsimple 8-bit boards to products for IoT applications, wearable, 3D printing, and embedded environments.All Arduino boards are completely open-source, empowering users to build them independently andeventually adapt them to their particular needs. Thesoftware, too, is open-source, and it is growingthrough the contributions of users worldwide.

Why Arduino?Thanks to its simple and accessible user experience, Arduino has been used in thousands of differentprojects and applications. The Arduino software is easy-to-use for beginners, yet flexible enough foradvanced users. It runs on Mac, Windows, and Linux. Teachers and students use it to build low costscientific instruments, to prove chemistry and physics principles, or to get started with programming androbotics. Designers and architects build interactive prototypes, musicians and artists use it for installationsand to experiment with new musical instruments. Makers, of course, use it to build many of the projectsexhibited at the Maker Faire, for example. Arduino is a key tool to learn new things. Anyone - children,hobbyists, artists, programmers - can start tinkering just following the step by step instructions of a kit, orsharing ideas online with other members of the Arduino community.

There are many other microcontrollers and microcontroller platforms available for physical computing.Parallax Basic Stamp, Netmedia's BX-24, Phidgets, MIT's Handyboard, and many others offer similarfunctionality. All of these tools take the messy details of microcontroller programming and wrap it upin an easy-to-use package. Arduino also simplifies the process of working with microcontrollers, but itoffers some advantage for teachers, students, and interested amateurs over other systems:

Inexpensive - Arduino boards are relatively inexpensive compared to other microcontroller platforms.The least expensive version of the Arduino module can be assembled by hand, and even the pre-assembled Arduino modules cost less than $50

Cross-platform - The Arduino Software (IDE) runs on Windows, Macintosh OSX, and Linux operatingsystems. Most microcontroller systems are limited to Windows.

Simple, clear programming environment - The Arduino Software (IDE) is easy-to-use for beginners, yetflexible enough for advanced users to take advantage of as well. For teachers, it's conveniently based onthe Processing programming environment, so students learning to program in that environment will befamiliar with how theArduino IDE works.

Open source and extensible software - The Arduino software is published as open source tools, availablefor extension by experienced programmers. The language can be expanded through C++ libraries, andpeople wanting to understand the technical details can make the leap from Arduino to the AVR Cprogramming language on which it's based. Similarly, you can add AVR-C code directly into yourArduino programs if you want to.

Page 2: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

Open source and extensible hardware - The plans of the Arduino boards are published under a CreativeCommons license, so experienced circuit designers can make their own version of the module, extendingit and improving it. Even relatively inexperienced users can build the breadboard version of the modulein order to understand how it works and save money.

How does the arduino work?I will attempt to explain how the hardware works as far as I understand it at the moment.

Page 3: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

Like every complex system, it is modular. There is the power system, that chooses between the powerjack and the USB power and produces 5v and 3v3 for the rest of the system. There is a USB to serialcontroller that contains the bootloader which is used to load programs into the ATMEGA328P.

The Power System

If there is a power supply connected to the power jack. The power supply should be between 9v and 15v.The two chips are voltage regulators that produce 5v. I still don't understand why there are two voltageregulator chips. I would guess to provide enough current.

The Vin is directly connected to the power supply.

Page 4: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

Vin is connected to the LM385D chip which contains two op amps. One of the opamps is used as acomparator and the other is not used at all. 3V3 is compared to Vin/2 if Vin/2>3V3 then the output is 5vand that is used to turn off the supply from the USB. The 5v generated is then connected to the LP2985chip which is a voltage regulator that takes in 5v and outputs 3v3 .

If instead Vin/2<3.3 , the mosfet is turned on and the USB power is used instead. USB provides the 5v tothe LP2985 chip.

USB to Serial ControllerThe USB controller is implemented with the ATMEGA8U2-MU. It is used to load the code unto theATMEGA328P.

Page 5: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

This includes support circuitry like the silicon crystals and the pull-up resistors. There is also the ICSPinterface that can be used to program the chip. The ICSP connects to the microcontroller SPI interface.

The ATMEGA328PThis is the main controller. The code you write for the arduino is executed by this controller. And it isdirectly connected to the I/O pins. The controller is programmed via the TX, RX pins connected to theUSB to serial controller and contains bootloader code. it can also be programmed directly via the ICSPpins.

Page 6: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

Arduino/Genuino Uno Board AnatomyArduino/Genuino boards senses the environment by receiving inputs from many sensors, and affectstheir surroundings by controlling lights, motors, and other actuators. Arduino/Genuino boards are themicrocontroller development platform that will be at the heart of your projects. When making somethingyou will be building the circuits and interfaces for interaction, and telling the microcontroller how tointerface with other components. Here the anatomy of Arduino/Genuino Uno.

Page 7: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

1. Digital pins Use these pins with digitalRead(), digitalWrite(), and analogWrite(). analogWrite() worksonly on the pins with the PWM symbol.

2. Pin 13 LED The only actuator built-in to your board. Besides being a handy target for your first blinksketch, this LED is very useful for debugging.

3. Power LED Indicates that your Genuino is receiving power. Useful for debugging.

4. ATmega microcontroller The heart of your board.

5. Analog in Use these pins with analogRead().

6. GND and 5V pins Use these pins to provide +5V power and ground to your circuits.

7. Power connector This is how you power your Genuino when it’s not plugged into a USB port forpower. Can accept voltages between 7-12V.

8. TX and RX LEDs These LEDs indicate communication between your Genuino and your computer.Expect them to flicker rapidly during sketch upload as well as during serial communication. Useful fordebugging.

9. USB port Used for powering your Genuino Uno, uploading your sketches to your Genuino, and forcommunicating with your Genuino sketch (via Serial. println() etc.).

10. Reset button Resets the ATmega microcontroller.

Example Arduino Boards:

1.Arduino Diecimila in Stoicheia

2.Arduino Duemilanove (rev 2009b)

Page 8: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

3.Arduino UNO

4.Arduino Mega

5.Arduino Nano

6.Arduino Due

7.LilyPad Arduino (rev 2007)

8.Arduino Yun

Basic Arduino Components1.WireA Wire is one of the most basic, and crucial components available. A wire allows for the unimpeded flowof electricity. A wire is used to connect the components of a circuit together. A wire can be thought of asany device that is intended to route electricity from one component to another. In this sense a wire can bethe traditional metal core, insulator wrapped wire. Additionally it can also be the trace on a circuit boardor the solder connection between two components in the absence of a "traditional" wire.

1.1Physical WirePhysical wire (as opposed to pcb traces, or wires on schematics) can be divided into two generalcategories: solid, and stranded. The difference is how easily the wire bends, and how easily it breaks.All wires that need to flex, such as the line cords on appliances or wires to your audio speakers shouldbe stranded wire. Solid wire is used where the wire doesn't need to flex and where having one solidconductor makes the wire easier to work with.

Examples of places where solid wire is used are inside the walls of buildings and on electronicbreadboards. In both cases, the wire won't be doing a lot of flexing, and is easier to use as one solidconductor, rather than lots of smaller strands.

Page 9: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

1.2Wire GaugesBreadboards are generally designed to use 22 gauge wire, although they can accommodate a gauge ortwo either way. Arduino female headers are not designed for inserting wire, but it works well enough formany prototype situations. 20 gauge is probably more dependendable in Arduino headers than 22 gaugebut both will work. In wire gauges, larger numbers correspond with smaller wire.

Radio Shack, although one always hesitates to recommend them, sells solid and stranded wire. Look for22 gauge solid (or alternately 20 gauge solid) wire for use with your 'duino and a breadboard.

If you need a fair quantity of breadboard wire you can obtain it inexpensively, and in several colors, bybuying solid conductor telephone cable. Make sure it's solid conductor though as both solid and strandedare sold. You can find this at home improvement stores and at R.S. This is commonly 24 gauge, so is onesize smaller than ideal, and can be doubled back on itself to make secure connections in 'duino femaleheaders.

Old computer cables contain a wealth of stranded wire in various gauges and colors that is extremelyuseful for wiring small electronic projects. Obtain them wherever tech trash is discarded.

2.BreadboardA Breadboard is a device that facilitates the construction and testing of circuits. Typically they are usedfor prototyping circuit designs.

Some common types are:

a) Solderless Breadboard - has a plastic faceplate with holes that the components can be insertedinto. The components make electrical contact to metal strips underneath the faceplate. In this wayno solder is needed to hold the components in place.

3.Power SupplyA Power Supply is a device that provides a source of electric power for a circuit. A power supply creates avoltage across its output pins. The measure of voltage and current that is supplied varies between devices.

Some common types of power supplies:

a) Benchtop Power Supply - provides power from an AC (alternating current) source to DC(direct current).b) Battery - A self contained device that produces power by chemical reactions in the battery.Properties of these reactions are known and therefore the voltage and current are known.c) "Wall Wart" - typically a small device that plugs into an outlet and converts AC to DC at apredetermined voltage and current.

4.ResistorA Resistor is a device that resists the flow of electricity. This resistance to the flow of electricity can beused to limit the amount of current flowing into an electrical component. Their ability to resist current ismeasured in Ohms [R] or [Capital Omega].

5.CapacitorA Capacitor is a device that can store and release electrical charge in a circuit. Typically a capacitorconsists of two charging plates with a material in between that prevents electrical discharge. Althoughother types of capacitors can be produced. These devices can be used to smooth out signals in a circuit.Additionally, large capacitors can be used as storage systems for current. Their ability to store charge ismeasured in Farads [F].

6.InductorAn Inductor is a device that stores electrical energy in a magnetic field. An inductor is a coil of wire.When a current is sent down the wire a magnetic field is generated. When the flow increases, more energyis stored in the magnetic field; when the flow decreases, the energy is released as electrical power. Aninductor can be used to smooth or filter out variations in current, much in the same way a capacitor can.The ability of an inductor to store electrical energy is measured in Henrys [H].

Page 10: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

7.DiodeA Diode is a device that only allows for the flow of electricity to pass in one direction. These componentsare often used to isolate the effect of one component from another.

Some common types of Diodes:

a) Light Emitting diode (LED)b) Photo diode - detects lightc) Laser diode - emits a coherent light beam (laser)d) Zener diode - prevents current flow up to a voltage threshold.

8.LEDA LED is a diode that generates a specific wavelength of light when a voltage is applied across its leads.This voltage is known as the forward voltage of the LED. The brightness of the light varies as the currentis varied.

An LED has no inherent current limiting, so applying voltages higher than the forward voltage willusually result in overheating or burning out the LED. Often the LED is damaged by this and will still lightup, but never be as bright as its original specification.

Current-limiting series resistorsThe simplest way to limit current to an LED is to use a resistor in series with the LED. To calculatethe proper value of resistor, it is easier to use Ohm's Law to calculate the electrical current through theresistor, and not the LED. This works out well because the current through a series circuit is the same atevery point in a circuit, meaning the current will be the same through the LED as the current through theresistor.

Here's an example: An LED is going to be powered from a 5 volt supply. Checking the LED's datasheet,the forward voltage is 3 volts. So a resistor in series with the LED would have 5 volts - 3 volts = 2 voltsacross the resistor.

To put 20 milliamps through the LED (a typical specification for a brightly lit LED), Ohm's law wouldlook like this.

E = IR

E = voltage in volts I = current in amps R = resistance in ohms

2 volts / .02 amps = 100 ohms, so using a 100 ohm resistor in series with the LED will light it at a currentof .02 amps (20 milliamps).

So can I plug an LED into a 'duino without a resistor?The answer is yes, although this is not necessarily the best of techniques. An Atmega pin can only supplyabout 40 milliamps which is not enough current to damage standard LED's. A better choice would be aseries resistor with a value of between 100 ohms and 1k, connected between the LED and ground.

PushbuttonA Pushbutton is a device that either completes or interrupts the flow of electricity in a circuit due to forceon the button. Pushbuttons come in many configurations and types. A common type is the momentaryswitch. When a force is applied to the button the button will either complete the connection (this is knownas a normally open switch) or will interrupt the connection (this is known as a normally closed switch).These devices can be useful for interrupting signals to the microcontroller (arduino) for input.

TransistorA Transistor is a device that restricts or allows the flow of current between two contacts based on thepresence or absence of current on a third contact. A transistor has three leads: collector, emitter and base.The collector and emitter act as the input and output for the transistor. While the base is the trigger for thesignal.

Two common types of transistors are:

Page 11: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

a) PNP - If the base voltage is less than the emitter voltage, then current flows from the emitter tothe collector.b) NPN - If the base voltage is greater than the emitter voltage, then current flows from thecollector to the emitter.

RelayA Relay is a device that completes a connection between two contact points by means of a mechanicalmovement. A relay may use a solenoid to magnetically move a contact switch. A signal is sent to the relaywhich can be used as the source of the electromagnet. They are typically used as switching mechanismsallowing for small DC current to switch large AC or DC currents. In this application they can isolate themore sensitive control circuitry from the larger components.

PhotoresistorA photoresistor is a special type of resistor that is photo (or light) sensitive i.e. the resistance changesaccording to how much light is on the photoresistor

Arduino Software (IDE)The Arduino Integrated Development Environment - or Arduino Software (IDE) - contains a text editorfor writing code, a message area, a text console, a toolbar with buttons for common functions and a seriesof menus. It connects to the Arduino and Genuino hardware to upload programs and communicate withthem.

Writing SketchesPrograms written using Arduino Software (IDE) are called sketches. These sketches are written in thetext editor and are saved with the file extension .ino. The editor has features for cutting/pasting andfor searching/replacing text. The message area gives feedback while saving and exporting and alsodisplays errors. The console displays text output by the Arduino Software (IDE), including complete errormessages and other information. The bottom righthand corner of the window displays the configuredboard and serial port. The toolbar buttons allow you to verify and upload programs, create, open, and savesketches, and open the serial monitor.

NB: Versions of the Arduino Software (IDE) prior to 1.0 saved sketches with the extension .pde. It ispossible to open these files with version 1.0, you will be prompted to save the sketch with the .inoextension on save.

File NewCreates a new instance of the editor, with the bare minimum structure of a sketch already in place. OpenAllows to load a sketch file browsing through the computer drives and folders. Open RecentProvides a short list of the most recent sketches, ready to be opened. SketchbookShows the current sketches within the sketchbook folder structure; clicking on any name opensthe corresponding sketch in a new editor instance. ExamplesAny example provided by the Arduino Software (IDE) or library shows up in this menu item. Allthe examples are structured in a tree that allows easy access by topic or library. CloseCloses the instance of the Arduino Software from which it is clicked. SaveSaves the sketch with the current name. If the file hasn't been named before, a name will beprovided in a "Save as.." window.

Page 12: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

Save as...Allows to save the current sketch with a different name. Page SetupIt shows the Page Setup window for printing. PrintSends the current sketch to the printer according to the settings defined in Page Setup. PreferencesOpens the Preferences window where some settings of the IDE may be customized, as thelanguage of the IDE interface. QuitCloses all IDE windows. The same sketches open when Quit was chosen will be automaticallyreopened the next time you start the IDE. Edit Undo/RedoGoes back of one or more steps you did while editing; when you go back, you may go forwardwith Redo. CutRemoves the selected text from the editor and places it into the clipboard. CopyDuplicates the selected text in the editor and places it into the clipboard. Copy for ForumCopies the code of your sketch to the clipboard in a form suitable for posting to the forum,complete with syntax coloring. Copy as HTMLCopies the code of your sketch to the clipboard as HTML, suitable for embedding in web pages. PastePuts the contents of the clipboard at the cursor position, in the editor. Select AllSelects and highlights the whole content of the editor. Comment/UncommentPuts or removes the // comment marker at the beginning of each selected line. Increase/Decrease IndentAdds or subtracts a space at the beginning of each selected line, moving the text one space on theright or eliminating a space at the beginning. FindOpens the Find and Replace window where you can specify text to search inside the currentsketch according to several options. Find NextHighlights the next occurrence - if any - of the string specified as the search item in the Findwindow, relative to the cursor position. Find PreviousHighlights the previous occurrence - if any - of the string specified as the search item in the Findwindow relative to the cursor position. Sketch Verify/CompileChecks your sketch for errors compiling it; it will report memory usage for code and variables inthe console area. UploadCompiles and loads the binary file onto the configured board through the configured Port. Upload Using ProgrammerThis will overwrite the bootloader on the board; you will need to use Tools > Burn Bootloader to

Page 13: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

restore it and be able to Upload to USB serial port again. However, it allows you to use the fullcapacity of the Flash memory for your sketch. Please note that this command will NOT burn thefuses. To do so a Tools -> Burn Bootloader command must be executed. Export Compiled BinarySaves a .hex file that may be kept as archive or sent to the board using other tools. Show Sketch FolderOpens the current sketch folder. Include LibraryAdds a library to your sketch by inserting #include statements at the start of your code. For moredetails, seelibraries below. Additionally, from this menu item you can access the Library Managerand import new libraries from .zip files. Add File...Adds a source file to the sketch (it will be copied from its current location). The new file appearsin a new tab in the sketch window. Files can be removed from the sketch using the tab menuaccessible clicking on the small triangle icon below the serial monitor one on the right side onthe toolbar. Tools Auto FormatThis formats your code nicely: i.e. indents it so that opening and closing curly braces line up, andthat the statements inside curly braces are indented more. Archive SketchArchives a copy of the current sketch in .zip format. The archive is placed in the same directoryas the sketch. Fix Encoding & ReloadFixes possible discrepancies between the editor char map encoding and other operating systemschar maps. Serial MonitorOpens the serial monitor window and initiates the exchange of data with any connected board onthe currently selected Port. This usually resets the board, if the board supports Reset over serialport opening. BoardSelect the board that you're using. See below for descriptions of the various boards. PortThis menu contains all the serial devices (real or virtual) on your machine. It should automaticallyrefresh every time you open the top-level tools menu. ProgrammerFor selecting a hardware programmer when programming a board or chip and not using theonboard USB-serial connection. Normally you won't need this, but if you'reburningabootloadertoa new microcontroller, you will use this. Burn BootloaderThe items in this menu allow you to burn a bootloader onto the microcontroller on an Arduinoboard. This is not required for normal use of an Arduino or Genuino board but is useful if youpurchase a new ATmega microcontroller (which normally come without a bootloader). Ensurethat you've selected the correct board from the Boards menu before burning the bootloader on thetarget board. This command also set the right fuses.

SketchbookThe Arduino Software (IDE) uses the concept of a sketchbook: a standard place to store your programs(or sketches). The sketches in your sketchbook can be opened from the File > Sketchbook menu or fromthe Open button on the toolbar. The first time you run the Arduino software, it will automatically create adirectory for your sketchbook. You can view or change the location of the sketchbook location from withthe Preferences dialog.

Page 14: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

Beginning with version 1.0, files are saved with a .ino file extension. Previous versions use the .pdeextension. You may still open .pde named files in version 1.0 and later, the software will automaticallyrename the extension to .ino.

Tabs, Multiple Files, and CompilationAllows you to manage sketches with more than one file (each of which appears in its own tab). Thesecan be normal Arduino code files (no visible extension), C files (.c extension), C++ files (.cpp), or headerfiles (.h).

UploadingBefore uploading your sketch, you need to select the correct items from the Tools > Board and Tools >Port menus. Theboards are described below. On the Mac, the serial port is probably something like /dev/tty.usbmodem241 (for an Uno or Mega2560 or Leonardo) or /dev/tty.usbserial-1B1 (for a Duemilanoveor earlier USB board), or/dev/tty.USA19QW1b1P1.1 (for a serial board connected with a Keyspan USB-to-Serial adapter). On Windows, it's probably COM1 or COM2 (for a serial board) or COM4, COM5,COM7, or higher (for a USB board) - to find out, you look for USB serial device in the ports section of theWindows Device Manager. On Linux, it should be /dev/ttyACMx ,/dev/ttyUSBx or similar. Once you'veselected the correct serial port and board, press the upload button in the toolbar or select the Upload itemfrom the Sketch menu. Current Arduino boards will reset automatically and begin the upload. With olderboards (pre-Diecimila) that lack auto-reset, you'll need to press the reset button on the board just beforestarting the upload. On most boards, you'll see the RX and TX LEDs blink as the sketch is uploaded. TheArduino Software (IDE) will display a message when the upload is complete, or show an error.

When you upload a sketch, you're using the Arduino bootloader, a small program that has been loaded onto the microcontroller on your board. It allows you to upload code without using any additional hardware.The bootloader is active for a few seconds when the board resets; then it starts whichever sketch was mostrecently uploaded to the microcontroller. The bootloader will blink the on-board (pin 13) LED when itstarts (i.e. when the board resets).

LibrariesLibraries provide extra functionality for use in sketches, e.g. working with hardware or manipulating data.To use a library in a sketch, select it from the Sketch > Import Library menu. This will insert one or more#include statements at the top of the sketch and compile the library with your sketch. Because librariesare uploaded to the board with your sketch, they increase the amount of space it takes up. If a sketch nolonger needs a library, simply delete its #includestatements from the top of your code.

There is a list of libraries in the reference. Some libraries are included with the Arduino software. Otherscan be downloaded from a variety of sources or through the Library Manager. Starting with version 1.0.5of the IDE, you do can import a library from a zip file and use it in an open sketch.

Third-Party HardwareSupport for third-party hardware can be added to the hardware directory of your sketchbook directory.Platforms installed there may include board definitions (which appear in the board menu), core libraries,bootloaders, and programmer definitions. To install, create the hardware directory, then unzip the third-party platform into its own sub-directory. (Don't use "arduino" as the sub-directory name or you'lloverride the built-in Arduino platform.) To uninstall, simply delete its directory.

Serial MonitorDisplays serial data being sent from the Arduino or Genuino board (USB or serial board). To send datato the board, enter text and click on the "send" button or press enter. Choose the baud rate from the drop-down that matches the rate passed to Serial.begin in your sketch. Note that on Windows, Mac or Linux,the Arduino or Genuino board will reset (rerun your sketch execution to the beginning) when you connectwith the serial monitor.

PreferencesSome preferences can be set in the preferences dialog (found under the Arduino menu on the Mac, or Fileon Windows and Linux)

Page 15: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

Language Support

Since version 1.0.1 , the Arduino Software (IDE) has been translated into 30+ different languages. Bydefault, the IDE loads in the language selected by your operating system. (Note: on Windows and possiblyLinux, this is determined by the locale setting which controls currency and date formats, not by thelanguage the operating system is displayed in.)

If you would like to change the language manually, start the Arduino Software (IDE) and open thePreferences window. Next to the Editor Language there is a dropdown menu of currently supportedlanguages. Select your preferred language from the menu, and restart the software to use the selectedlanguage. If your operating system language is not supported, the Arduino Software (IDE) will default toEnglish.

You can return the software to its default setting of selecting its language based on your operating systemby selectingSystem Default from the Editor Language drop-down. This setting will take effect when yourestart the Arduino Software (IDE). Similarly, after changing your operating system's settings, you mustrestart the Arduino Software (IDE) to update it to the new default language.

BoardsThe board selection has two effects: it sets the parameters (e.g. CPU speed and baud rate) used whencompiling and uploading sketches; and sets and the file and fuse settings used by the burn bootloadercommand. Some of the board definitions differ only in the latter, so even if you've been uploadingsuccessfully with a particular selection you'll want to check it before burning the boot loader. ArduinoSoftware (IDE) includes the built in support for the boards in the following list, all based on the AVRCore. The Boards Manager included in the standard installation allows to add support for the growingnumber of new boards based on different cores like Arduino Due, Arduino Zero, Edison, Galileo and soon.

Page 16: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

▪ Arduino YùnAn ATmega32u4 running at 16 MHz with auto-reset, 12 Analog In, 20 Digital I/O and 7 PWM.

▪ Arduino/Genuino UnoAn ATmega328 running at 16 MHz with auto-reset, 6 Analog In, 14 Digital I/O and 6 PWM.

▪ Arduino Diecimila or Duemilanove w/ ATmega168An ATmega168 running at 16 MHz with auto-reset.

▪ Arduino Nano w/ ATmega328An ATmega328 running at 16 MHz with auto-reset. Has eight analog inputs.

▪ Arduino/Genuino Mega 2560An ATmega2560 running at 16 MHz with auto-reset, 16 Analog In, 54 Digital I/O and 15 PWM.

▪ Arduino MegaAn ATmega1280 running at 16 MHz with auto-reset, 16 Analog In, 54 Digital I/O and 15 PWM.

▪ Arduino Mega ADKAn ATmega2560 running at 16 MHz with auto-reset, 16 Analog In, 54 Digital I/O and 15 PWM.

▪ Arduino LeonardoAn ATmega32u4 running at 16 MHz with auto-reset, 12 Analog In, 20 Digital I/O and 7 PWM.

▪ Arduino/Genuino MicroAn ATmega32u4 running at 16 MHz with auto-reset, 12 Analog In, 20 Digital I/O and 7 PWM.

▪ Arduino EsploraAn ATmega32u4 running at 16 MHz with auto-reset.

▪ Arduino Mini w/ ATmega328An ATmega328 running at 16 MHz with auto-reset, 8 Analog In, 14 Digital I/O and 6 PWM.

▪ Arduino EthernetEquivalent to Arduino UNO with an Ethernet shield: An ATmega328 running at 16 MHz withauto-reset, 6 Analog In, 14 Digital I/O and 6 PWM.

▪ Arduino FioAn ATmega328 running at 8 MHz with auto-reset. Equivalent to Arduino Pro or Pro Mini (3.3V,8 MHz) w/ATmega328, 6 Analog In, 14 Digital I/O and 6 PWM.

▪ Arduino BT w/ ATmega328ATmega328 running at 16 MHz. The bootloader burned (4 KB) includes codes to initialize theon-board bluetooth module, 6 Analog In, 14 Digital I/O and 6 PWM..

▪ LilyPad Arduino USBAn ATmega32u4 running at 8 MHz with auto-reset, 4 Analog In, 9 Digital I/O and 4 PWM.

▪ LilyPad ArduinoAn ATmega168 or ATmega132 running at 8 MHz with auto-reset, 6 Analog In, 14 Digital I/Oand 6 PWM.

▪ Arduino Pro or Pro Mini (5V, 16 MHz) w/ ATmega328An ATmega328 running at 16 MHz with auto-reset. Equivalent to Arduino Duemilanove or Nanow/ ATmega328; 6 Analog In, 14 Digital I/O and 6 PWM.

▪ Arduino NG or older w/ ATmega168An ATmega168 running at 16 MHzwithout auto-reset. Compilation and upload is equivalentto Arduino Diecimila or Duemilanove w/ ATmega168, but the bootloader burned has a slowertimeout (and blinks the pin 13 LED three times on reset); 6 Analog In, 14 Digital I/O and 6 PWM.

▪ Arduino Robot ControlAn ATmega328 running at 16 MHz with auto-reset.

▪ Arduino Robot MotorAn ATmega328 running at 16 MHz with auto-reset.

▪ Arduino GemmaAn ATtiny85 running at 8 MHz with auto-reset, 1 Analog In, 3 Digital I/O and 2 PWM.

Page 17: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

MicrocontrollersDigital PinsThe pins on the Arduino can be configured as either inputs or outputs. This document explains thefunctioning of the pins in those modes. While the title of this document refers to digital pins, it isimportant to note that vast majority ofArduino (Atmega) analog pins, may be configured, and used, inexactly the same manner as digital pins.

Properties of Pins Configured as INPUTArduino (Atmega) pins default to inputs, so they don't need to be explicitly declared as inputs withpinMode() when you're using them as inputs. Pins configured this way are said to be in a high-impedancestate. Input pins make extremely small demands on the circuit that they are sampling, equivalent to aseries resistor of 100 megohm in front of the pin. This means that it takes very little current to movethe input pin from one state to another, and can make the pins useful for such tasks as implementing acapacitive touch sensor, reading an LED as a photodiode, or reading an analog sensor with a scheme suchas RCTime.

This also means however, that pins configured as pinMode(pin, INPUT) with nothing connected to them,or with wires connected to them that are not connected to other circuits, will report seemingly randomchanges in pin state, picking up electrical noise from the environment, or capacitively coupling the stateof a nearby pin.

Pullup Resistors with pins configured as INPUTOften it is useful to steer an input pin to a known state if no input is present. This can be done by adding apullup resistor (to +5V), or a pulldown resistor (resistor to ground) on the input. A 10K resistor is a goodvalue for a pullup or pulldown resistor.

Properties of Pins Configured as INPUT_PULLUPThere are 20K pullup resistors built into the Atmega chip that can be accessed from software. These built-in pullup resistors are accessed by setting the pinMode() as INPUT_PULLUP. This effectively inverts thebehavior of the INPUT mode, where HIGH means the sensor is off, and LOW means the sensor is on.

The value of this pullup depends on the microcontroller used. On most AVR-based boards, the value isguaranteed to be between 20kΩ and 50kΩ. On the Arduino Due, it is between 50kΩ and 150kΩ. For theexact value, consult the datasheet of the microcontroller on your board.

When connecting a sensor to a pin configured with INPUT_PULLUP, the other end should be connectedto ground. In the case of a simple switch, this causes the pin to read HIGH when the switch is open, andLOW when the switch is pressed.

The pullup resistors provide enough current to dimly light an LED connected to a pin that has beenconfigured as an input. If LEDs in a project seem to be working, but very dimly, this is likely what isgoing on.

The pullup resistors are controlled by the same registers (internal chip memory locations) that controlwhether a pin is HIGH or LOW. Consequently, a pin that is configured to have pullup resistors turnedon when the pin is an INPUT, will have the pin configured as HIGH if the pin is then switched to anOUTPUT with pinMode(). This works in the other direction as well, and an output pin that is left in aHIGH state will have the pullup resistors set if switched to an input with pinMode().

Prior to Arduino 1.0.1, it was possible to configure the internal pull-ups in the following manner:

pinMode(pin, INPUT); // set pin to inputdigitalWrite(pin, HIGH); // turn on pullup resistors

NOTE: Digital pin 13 is harder to use as a digital input than the other digital pins because it has an LEDand resistor attached to it that's soldered to the board on most boards. If you enable its internal 20k pull-up resistor, it will hang at around 1.7V instead of the expected 5V because the onboard LED and seriesresistor pull the voltage level down, meaning it always returns LOW. If you must use pin 13 as a digitalinput, set its pinMode() to INPUT and use an external pull down resistor.

Page 18: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

Properties of Pins Configured as OUTPUTPins configured as OUTPUT with pinMode() are said to be in a low-impedance state. This means thatthey can provide a substantial amount of current to other circuits. Atmega pins can source (providepositive current) or sink (provide negative current) up to 40 mA (milliamps) of current to other devices/circuits. This is enough current to brightly light up an LED (don't forget the series resistor), or run manysensors, for example, but not enough current to run most relays, solenoids, or motors.

Short circuits on Arduino pins, or attempting to run high current devices from them, can damage ordestroy the output transistors in the pin, or damage the entire Atmega chip. Often this will result in a"dead" pin in the microcontroller but the remaining chip will still function adequately. For this reason it isa good idea to connect OUTPUT pins to other devices with 470Ω or 1k resistors, unless maximum currentdraw from the pins is required for a particular application.

Analog Input PinsA description of the analog input pins on an Arduino chip (Atmega8, Atmega168, Atmega328, orAtmega1280).

A/D converterThe 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 functionof the analog pins for most Arduino users is to read analog sensors, the analog pins also have all thefunctionality of general purpose input/output (GPIO) pins (the same as digital pins 0 - 13).

Consequently, if a user needs more general purpose input output pins, and all the analog pins are not inuse, the analog pins may be used for GPIO.

Pin mappingThe 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);

Pullup resistorsThe analog pins also have pullup resistors, which work identically to pullup resistors on the digital pins.They are enabled by issuing a command such as

digitalWrite(A0, HIGH); // set pullup on analog pin 0

while the pin is an input.

Be aware however that turning on a pullup will affect the values reported by analogRead().

Details and CaveatsThe analogRead command will not work correctly if a pin has been previously set to an output, so if thisis the case, set it back to an input before using analogRead. Similarly if the pin has been set to HIGH asan output, the pullup resistor will be set, when switched back to an input.

The Atmega datasheet also cautions against switching analog pins in close temporal proximity to makingA/D readings (analogRead) on other analog pins. This can cause electrical noise and introduce jitter in theanalog system. It may be desirable, after manipulating analog pins (in digital mode), to add a short delaybefore using analogRead() to read other analog pins.

PWMThe Fading example demonstrates the use of analog output (PWM) to fade an LED. It is available in theFile->Sketchbook->Examples->Analog menu of the Arduino software.

Pulse Width Modulation, or PWM, is a technique for getting analog results with digital means. Digitalcontrol is used to create a square wave, a signal switched between on and off. This on-off pattern cansimulate voltages in between full on (5 Volts) and off (0 Volts) by changing the portion of the time thesignal spends on versus the time that the signal spends off. The duration of "on time" is called the pulse

Page 19: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

width. To get varying analog values, you change, or modulate, that pulse width. If you repeat this on-offpattern fast enough with an LED for example, the result is as if the signal is a steady voltage between 0and 5v controlling the brightness of the LED.

In the graphic below, the green lines represent a regular time period. This duration or period is theinverse of the PWM frequency. In other words, with Arduino's PWM frequency at about 500Hz, thegreen lines would measure 2 milliseconds each. A call to analogWrite() is on a scale of 0 - 255, such thatanalogWrite(255) requests a 100% duty cycle (always on), and analogWrite(127) is a 50% duty cycle (onhalf the time) for example.

Once you get this example running, grab your arduino and shake it back and forth. What you are doinghere is essentially mapping time across the space. To our eyes, the movement blurs each LED blink intoa line. As the LED fades in and out, those little lines will grow and shrink in length. Now you are seeingthe pulse width.

MemoryThere are three pools of memory in the microcontroller used on avr-based Arduino boards :

• Flash memory (program space), is where the Arduino sketch is stored.• SRAM (static random access memory) is where the sketch creates and manipulates variables

when it runs.• EEPROM is memory space that programmers can use to store long-term information.

Flash memory and EEPROM memory are non-volatile (the information persists after the power is turnedoff). SRAM is volatile and will be lost when the power is cycled.

The ATmega328 chip found on the Uno has the following amounts of memory:

Flash 32k bytes (of which .5k is used for the bootloader)SRAM 2k bytesEEPROM 1k byte

The ATmega2560 in the Mega2560 has larger memory space :

Flash 256k bytes (of which 8k is used for the bootloader)SRAM 8k bytesEEPROM 4k byte

Notice that there's not much SRAM available in the Uno. It's easy to use it all up by having lots of stringsin your program. For example, a declaration like:

char message[] = "I support the Cape Wind project.";

Page 20: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

puts 33 bytes into SRAM (each character takes a byte, plus the '\0' terminator). This might not seem likea lot, but it doesn't take long to get to 2048, especially if you have a large amount of text to send to adisplay, or a large lookup table, for example.

If you run out of SRAM, your program may fail in unexpected ways; it will appear to upload successfully,but not run, or run strangely. To check if this is happening, you can try commenting out or shortening thestrings or other data structures in your sketch (without changing the code). If it then runs successfully,you're probably running out of SRAM. There are a few things you can do to address this problem:

▪ If your sketch talks to a program running on a (desktop/laptop) computer, you can try shiftingdata or calculations to the computer, reducing the load on the Arduino.

▪ If you have lookup tables or other large arrays, use the smallest data type necessary to store thevalues you need; for example, an int takes up two bytes, while a byte uses only one (but can storea smaller range of values).

▪ If you don't need to modify the strings or data while your sketch is running, you can store themin flash (program) memory instead of SRAM; to do this, use the PROGMEM keyword.

ProgrammingArduino programs can be divided in three main parts: structure, values (variables and constants), andfunctions.

VariablesA variable is a place to store a piece of data. It has a name, a value, and a type. For example, this statement(called adeclaration):

int pin = 13;

creates a variable whose name is pin, whose value is 13, and whose type is int. Later on in the program,you can refer to this variable by its name, at which point its value will be looked up and used. Forexample, in this statement:

pinMode(pin, OUTPUT);

it is the value of pin (13) that will be passed to the pinMode() function. In this case, you don't actuallyneed to use a variable, this statement would work just as well:

pinMode(13, OUTPUT);

The advantage of a variable in this case is that you only need to specify the actual number of the pinonce, but you can use it lots of times. So if you later decide to change from pin 13 to pin 12, you onlyneed to change one spot in the code. Also, you can use a descriptive name to make the significance of thevariable clear (e.g. a program controlling an RGB LED might have variables called redPin, greenPin, andbluePin).

A variable has other advantages over a value like a number. Most importantly, you can change the valueof a variable using an assignment (indicated by an equals sign). For example:

pin = 12;

will change the value of the variable to 12. Notice that we don't specify the type of the variable: it's notchanged by the assignment. That is, the name of the variable is permanently associated with a type; onlyits value changes. [1] Note that you have to declare a variable before you can assign a value to it. If youinclude the preceding statement in a program without the first statement above, you'll get a message like:"error: pin was not declared in this scope".

When you assign one variable to another, you're making a copy of its value and storing that copy inthe location in memory associated with the other variable. Changing one has no effect on the other. Forexample, after:

int pin = 13;int pin2 = pin;pin = 12;

Page 21: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

only pin has the value 12; pin2 is still 13.

Now what, you might be wondering, did the word "scope" in that error message above mean? It refers tothe part of your program in which the variable can be used. This is determined by where you declare it.For example, if you want to be able to use a variable anywhere in your program, you can declare at thetop of your code. This is called a globalvariable; here's an example:

int pin = 13;void setup(){ pinMode(pin, OUTPUT);}void loop(){ digitalWrite(pin, HIGH);}

As you can see, pin is used in both the setup() and loop() functions. Both functions are referring to thesame variable, so that changing it one will affect the value it has in the other, as in:

int pin = 13;void setup(){ pin = 12; pinMode(pin, OUTPUT);}void loop(){ digitalWrite(pin, HIGH);}

Here, the digitalWrite() function called from loop() will be passed a value of 12, since that's the value thatwas assigned to the variable in the setup() function.

If you only need to use a variable in a single function, you can declare it there, in which case its scopewill be limited to that function. For example:

void setup(){ int pin = 13; pinMode(pin, OUTPUT); digitalWrite(pin, HIGH);}

In this case, the variable pin can only be used inside the setup() function. If you try to do something likethis:

void loop(){ digitalWrite(pin, LOW); // wrong: pin is not in scope here.}

you'll get the same message as before: "error: 'pin' was not declared in this scope". That is, even thoughyou've declared pin somewhere in your program, you're trying to use it somewhere outside its scope.

Why, you might be wondering, wouldn't you make all your variables global? After all, if I don't knowwhere I might need a variable, why should I limit its scope to just one function? The answer is that it canmake it easier to figure out what happens to it. If a variable is global, its value could be changed anywherein the code, meaning that you need to understand the whole program to know what will happen to thevariable. For example, if your variable has a value you didn't expect, it can be much easier to figure outwhere the value came from if the variable has a limited scope.

FunctionsSegmenting code into functions allows a programmer to create modular pieces of code that perform adefined task and then return to the area of code from which the function was "called". The typical casefor creating a function is when one needs to perform the same action multiple times in a program.

For programmers accustomed to using BASIC, functions in Arduino provide (and extend) the utility ofusing subroutines (GOSUB in BASIC).

Standardizing code fragments into functions has several advantages:

• Functions help the programmer stay organized. Often this helps to conceptualize the program.• Functions codify one action in one place so that the function only has to be thought out and

debugged once.• This also reduces chances for errors in modification, if the code needs to be changed.• Functions make the whole sketch smaller and more compact because sections of code are reused

many times.• They make it easier to reuse code in other programs by making it more modular, and as a nice

side effect, using functions also often makes the code more readable.

There are two required functions in an Arduino sketch, setup() and loop(). Other functions must be createdoutside the brackets of those two functions. As an example, we will create a simple function to multiplytwo numbers.

Page 22: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

Example

To "call" our simple multiply function, we pass it parameters of the datatype that it is expecting:

voidloop(){inti=2;intj=3;int k;

k = myMultiplyFunction(i,j);// k now contains 6}

Our function needs to be declared outside any other function, so "myMultiplyFunction()" can go eitherabove or below the "loop()" function.

The entire sketch would then look like this:

voidsetup(){Serial.begin(9600);}

voidloop(){inti=2;intj=3;int k;

k = myMultiplyFunction(i,j);// k now contains 6Serial.println(k);delay(500);}

int myMultiplyFunction(int x,int y){int result;result = x * y;

return result;}

Page 23: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

Another exampleThis function will read a sensor five times with analogRead() and calculate the average of five readings.It then scales the data to 8 bits (0-255), and inverts it, returning the inverted result.

int ReadSens_and_Condition(){inti;int sval =0;

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

}

sval = sval /5;// averagesval = sval /4;// scale to 8 bits (0 - 255)sval =255- sval;// invert output

return sval;}

To call our function we just assign it to a variable.

int sens;

sens = ReadSens_and_Condition();

Library:What are Libraries?Libraries are a collection of code that makes it easy for you to connect to a sensor, display, module, etc.For example, the built-in LiquidCrystal library makes it easy to talk to character LCD displays. There arehundreds of additional libraries available on the Internet for download.

How to Install a LibraryUsing the Library ManagerTo install a new library into your Arduino IDE you can use the Library Manager (available from IDEversion 1.6.2). Open the IDE and click to the "Sketch" menu and then Include Library > ManageLibraries.

Page 24: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

Then the library manager will open and you will find a list of libraries that are already installed or readyfor installation. In this example we will install the Bridge library. Scroll the list to find it, then select theversion of the library you want to install. Sometimes only one version of the library is available. If theversion selection menu does not appear, don't worry: it is normal.

Page 25: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

Finally click on install and wait for the IDE to install the new library. Downloading may take timedepending on your connection speed. Once it has finished, an Installed tag should appear next to theBridge library. You can close the library manager.

You can now find the new library available in the Include Library menu. If you want to add your ownlibrary open a new issue on github.

Importing a .zip LibraryLibraries are often distributed as a ZIP file or folder. The name of the folder is the name of the library.Inside the folder will be a .cpp file, a .h file and often a keywords.txt file, examples folder, and other filesrequired by the library. Starting with version 1.0.5, you can install 3rd party libraries in the IDE. Do notunzip the downloaded library, leave it as is.

Page 26: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

In the Arduino IDE, navigate to Sketch > Include Library. At the top of the drop down list, select theoption to "Add .ZIP Library''.

You will be prompted to select the library you would like to add. Navigate to the .zip file's location andopen it.

Return to the Sketch > Import Library menu. You should now see the library at the bottom of the drop-down menu. It is ready to be used in your sketch. The zip file will have been expanded in the librariesfolder in your Arduino sketches directory.

NB: the Library will be available to use in sketches, but examples for the library will not be exposed inthe File >Examplesuntil after the IDE has restarted.

Manual installationTo install the library, first quit the Arduino application. Then uncompress the ZIP file containing thelibrary. For example, if you're installing a library called "ArduinoParty", uncompress ArduinoParty.zip. Itshould contain a folder calledArduinoParty, with files like ArduinoParty.cpp and ArduinoParty.h inside.(If the .cpp and .h files aren't in a folder, you'll need to create one. In this case, you'd make a foldercalled "ArduinoParty" and move into it all the files that were in the ZIP file, like ArduinoParty.cpp andArduinoParty.h.)

Drag the ArduinoParty folder into this folder (your libraries folder). Under Windows, it will likely becalled "My Documents\Arduino\libraries". For Mac users, it will likely be called "Documents/Arduino/libraries". On Linux, it will be the "libraries" folder in your sketchbook.

Page 27: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

Your Arduino library folder should now look like this (on Windows):

My Documents\Arduino\libraries\ArduinoParty\ArduinoParty.cpp My Documents\Arduino\libraries\ArduinoParty\ArduinoParty.h My Documents\Arduino\libraries\ArduinoParty\examples ....

or like this (on Mac and Linux):

Documents/Arduino/libraries/ArduinoParty/ArduinoParty.cpp Documents/Arduino/libraries/ArduinoParty/ArduinoParty.h Documents/Arduino/libraries/ArduinoParty/examples ....

There may be more files than just the .cpp and .h files, just make sure they're all there. (The librarywon't work if you put the .cpp and .h files directly into the libraries folder or if they're nested in an extrafolder. For example: Documents\Arduino\libraries\ArduinoParty.cpp and Documents\Arduino\libraries\ArduinoParty\ArduinoParty\ArduinoParty.cpp won't work.)

Restart the Arduino application. Make sure the new library appears in the Sketch->Import Library menuitem of the software. That's it! You've installed a library!

Cores:How to install a coreIn this example we will install the core required by the Arduino Due board.

Click on Tools menu and then Boards > Boards Manager.

The board manager will open and you will see a list of installed and available boards.

Select the SAM core, choose the version in the drop-down menu and click on install.

Page 28: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

The download time will depend on your connection speed.

After installation is complete an Installed tag appears next to the core name. You can close the BoardManager.

Now you can find the new board in the Board menu.

Built-In Examples

Built-in Examples are sketches included in the Arduino Software (IDE), to open them click on the toolbarmenu: File > Examples. These simple programs demonstrate all basic Arduino commands. They spanfrom a Sketch Bare Minimum to Digital and Analog IO, to the use of Sensors and Displays.

1. Analog Read SerialThis example shows you how to read analog input from the physical world using a potentiometer.A potentiometer is a simple mechanical device that provides a varying amount of resistance when its shaftis turned. By passing voltage through a potentiometer and into an analog input on your board, it is possibleto measure the amount of resistance produced by a potentiometer (or pot for short) as an analog value.In this example you will monitor the state of your potentiometer after establishing serial communicationbetween your Arduino or Genuino and your computer running the Arduino Software (IDE).

Page 29: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

Hardware Required1. Arduino or Genuino Board2. 10k ohm Potentiometer

CircuitConnect the three wires from the potentiometer to your board. The first goes from one of the outer pinsof the potentiometerto ground . The second goes from the other outer pin of the potentiometer to 5 volts.The third goes from the middle pin of the potentiometer to the analog pin A0.

By turning the shaft of the potentiometer, you change the amount of resistance on either side of the wiper,which is connected to the center pin of the potentiometer. This changes the voltage at the center pin. Whenthe resistance between the center and the side connected to 5 volts is close to zero (and the resistanceon the other side is close to 10k ohm), the voltage at the center pin nears 5 volts. When the resistancesare reversed, the voltage at the center pin nears 0 volts, or ground. This voltage is the analog voltage thatyou're reading as an input.

The Arduino and Genuino boards have a circuit inside called an analog-to-digital converter or ADC thatreads this changing voltage and converts it to a number between 0 and 1023. When the shaft is turnedall the way in one direction, there are 0 volts going to the pin, and the input value is 0. When the shaftis turned all the way in the opposite direction, there are 5 volts going to the pin and the input value is1023. In between, analogRead() returns a number between 0 and 1023 that is proportional to the amountof voltage being applied to the pin.

Page 30: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

Schematic

CodeIn the sketch below, the only thing that you do in the setup function is to begin serial communications, at9600 bits of data per second, between your board and your computer with the command:

Serial.begin(9600);

Next, in the main loop of your code, you need to establish a variable to store the resistance value (whichwill be between 0 and 1023, perfect for an int datatype) coming in from your potentiometer:

int sensorValue = analogRead(A0);

Finally, you need to print this information to your serial monitor window. You can do this with thecommandSerial.println() in your last line of code:

Serial.println(sensorValue)

Page 31: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

Now, when you open your Serial Monitor in the Arduino Software (IDE) (by clicking the icon that lookslike a lens, on the right, in the green top bar or using the keyboard shortcut Ctrl+Shift+M), you should seea steady stream of numbers ranging from 0-1023, correlating to the position of the pot. As you turn yourpotentiometer, these numbers will respond almost instantly.

/*AnalogReadSerialReads an analog input on pin 0, prints the result to the serial monitor.Graphical representation is available using serial plotter (Tools > Serial Plotter menu)Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and

ground.

This example code is in the public domain.*/

// the setup routine runs once when you press reset:void setup() {// initialize serial communication at 9600 bits per second:Serial.begin(9600);

}

// the loop routine runs over and over again forever:void loop() {// read the input on analog pin 0:int sensorValue = analogRead(A0);// print out the value you read:Serial.println(sensorValue);delay(1); // delay in between reads for stability

}

2.Bare Minimum code neededThis example contains the bare minimum of code you need for a sketch to compile properly on ArduinoSoftware (IDE): the setup() method and the loop() method.

Hardware Required1. Arduino or Genuino Board

CircuitOnly your Arduino or Genuino Board is needed for this example.

Page 32: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

CodeThe setup() function is called when a sketch starts. Use it to initialize variables, pin modes, start usinglibraries, etc. The setup function will only run once, after each powerup or reset of the board.

After creating a setup() function, the loop() function does precisely what its name suggests, and loopsconsecutively, allowing your program to change and respond as it runs. Code in the loop() section of yoursketch is used to actively control the board.

The code below won't actually do anything, but it's structure is useful for copying and pasting to get youstarted on any sketch of your own. It also shows you how to make comments in your code.

Any line that starts with two slashes (//) will not be read by the compiler, so you can write anything youwant after it. The two slashes may be put after functional code to keep comments on the same line.Commenting your code like this can be particularly helpful in explaining, both to yourself and others,how your program functions step by step.

void setup() {// put your setup code here, to run once:

}

void loop() {// put your main code here, to run repeatedly:

}

3.BlinkThis example shows the simplest thing you can do with an Arduino or Genuino to see physical output: itblinks an LED.

Hardware Required1. Arduino or Genuino Board2. LED3. 220 ohm resistor

Page 33: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

CircuitTo build the circuit, connect one end of the resistor to Arduino pin 13. Connect the long leg of the LED(the positive leg, called the anode) to the other end of the resistor. Connect the short leg of the LED (thenegative leg, called the cathode) to the Arduino GND, as shown in the diagram and the schematic below.

Most Arduino boards already have an LED attached to pin 13 on the board itself. If you run this examplewith no hardware attached, you should see that LED blink.

The value of the resistor in series with the LED may be of a different value than 220 ohm; the LED willlit up also with values up to 1K ohm.

Page 34: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

Schematic

CodeAfter you build the circuit plug your Arduino or Genuino board into your computer, start the ArduinoSoftware (IDE) and enter the code below. You may also load it from the menu File/Examples/01.Basics/Blink . The first thing you do is to initialize pin 13 as an output pin with the line

pinMode(13, OUTPUT);

In the main loop, you turn the LED on with the line:

digitalWrite(13, HIGH);

This supplies 5 volts to pin 13. That creates a voltage difference across the pins of the LED, and lights itup. Then you turn it off with the line:

digitalWrite(13, LOW);

That takes pin 13 back to 0 volts, and turns the LED off. In between the on and the off, you wantenough time for a person to see the change, so the delay() commands tell the board to do nothing for 1000milliseconds, or one second. When you use the delay() command, nothing else happens for that amountof time. Once you've understood the basic examples, check out the BlinkWithoutDelay example to learnhow to create a delay while doing other things.

Once you've understood this example, check out the DigitalReadSerial example to learn how read aswitch connected to the board.

Page 35: Basics What is Arduino? - The Eye Archive... · Basics What is Arduino? ... 7.LilyPad Arduino (rev 2007) 8.Arduino Yun Basic Arduino Components 1.Wire AWireisoneofthemostbasic,andcrucialcomponentsavailable.Awireallowsfortheunimpededflow

/*BlinkTurns on an LED on for one second, then off for one second, repeatedly.

Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZEROit is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN takes careof use the correct LED pin whatever is the board used.If you want to know what pin the on-board LED is connected to on your Arduino model,

checkthe Technical Specs of your board at

This example code is in the public domain.

modified 8 May 2014by Scott Fitzgerald

modified 2 Sep 2016by Arturo Guadalupi

*/

// the setup function runs once when you press reset or power the boardvoid setup() {// initialize digital pin LED_BUILTIN as an output.pinMode(LED_BUILTIN, OUTPUT);

}

// the loop function runs over and over again forevervoid loop() {digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)delay(1000); // wait for a seconddigitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOWdelay(1000); // wait for a second

}