For Those New To Programming And The Arduino

Transcription

Arduino 101 ClassFor those new to programmingand the ArduinoVersion 3.7 (remote)

This PresentationI look forward to your questions and feedbackdavid@thekramers.netYou can download my Arduino presentations athttp://www.thekramers.net/r/arduino/

About Me My name is David Kramer. I’ve been volunteering forfor the Watertown Hatch for about 2.5 yearsMost of my career I’ve been an Agile Coach, SoftwareEngineer, or Software Engineering ManagerMost people come to Arduino from a hardwarebackground; I come to Arduino from a softwarebackgroundThat means my approach is more “Let’s do softwareright” than “Let’s just get the software working”, whichcan lead to over-engineering.

Objectives This class is designed for people with little or noprogramming or electronics experienceYou will learn what an Arduino is and what it can doYou will learn the basics of programming in C on anArduinoThis class will also cover a lot of what can be donewithout the details, so you know where to explore laterWe will go back and forth between hardware andsoftware so we can try things outThere will be another class for Arduino 102 aimed atthose who know how to program, and another Arduino201 for advanced Arduino training

Parts ListYou can attend this class and watch without following along with your own Arduino at home, but for the best learning experience,it’s better to have your own Arduino and see it work for yourself.Please install the Arduino IDE onto your computer from https://www.arduino.cc/en/Main/Software Arduino Uno or compatible. Any 5v Arduino will work but the examples in the class use the Uno. Make sure you have amatching USB cable. https://store.arduino.cc/usa/arduino-uno-rev3 -R3/ https://www.adafruit.com/product/2488 1 breadboard. They’re handy so buying more is OK type-PCB-Board/dp/B077DN2PS1 https://www.adafruit.com/product/239 Dupont Jumper wires, male to male. You only need 4 but these are also very ional-Assorted-Multicolored/dp/B07GD25V8D https://www.adafruit.com/product/760 A small breadboard compatible momentary switch utton-Switch/dp/B07VSNN9S2 https://www.adafruit.com/product/367 A 10K resistor, or any value near there. You can’t buy 1 so I recommend getting a variety pack rmistor-Photoresistor/dp/B0792M83JH * This kit also includes LEDsand the required photoresistor https://www.adafruit.com/product/2784 A photoresistor. Almost any one will do, but the larger the more sensitive in general ve-Resistor-Dependent/dp/B01N7V536K https://www.adafruit.com/product/161You can also buy all of this in a kit with lots of other stuff troller-Projects/dp/B01D8KOZF4 patible-Official/dp/B01DGD2GAO

Introductions Who are you? What is your Arduino experience? What are you hoping to get out of this class?

History and PurposeThe Arduino was developed in the early 2000s to createsimple, low cost tools for creating digital projects by nonengineers. It’s great for teaching, too. Everything about the Arduino is open source, and anyonecan make their own clone of an official board, or design theirown Arduino compatible The leading competition at the time was the BASIC Stamp,which was programmed in BASIC, and cost about 50 Because of its roots and purpose, Arduinos strive to make iteasy to do things and have core functionality supported byall boards, abstracting away some of the harder details.

Basic Arduino: The Arduino Uno

Other Arduinos And CompatiblesAdafruit FloraAdafruit Huzzah FeatherAdafruit Gemma (also LilyPad)ArduinoTiny (alsoAtom X1)Circuit Playground ExpressArduino NanoArduino Pro MiniSparkfun Uno clone

Choosing the right microcontrollerSize Speed Memory I/O ports Connectivity (WiFi, Ethernet, Bluetooth, Zigbee, NFC, etc) Price Two helpful sites:https://www.sparkfun.com/standard arduino comparison -an-arduino-for-your-project

What Can Arduinos Do?They have full processors to run any kind of general processing you want,though they are relatively slow, single threaded, and not good at floating pointmath and don’t have lots of memoryThey run “near real time”, which means they are good for exact timing andpredictable execution speedThey draw very little power compared to full computersThey are great at controlling many kinds of devicesThey are great at getting input from many kinds of devicesThey have serial ports and USB to communicate with other devices, includingyour PC. They have other communication interfaces like I2C and SPI, andeven more can be added with small add-on boards like CAN and DMX.

Programming ArduinosAll Arduinos are programmable in a subset ofC/C (there are some things that can’t be done)Many are also programmable in Python or Lua Many have a visual programming environments The Arduino website has a free simpledevelopment environment that will be enough forall but advanced projects This class focuses on programming in C, and notone of those easier programming environments,to help you understand the Arduino better, andso it will work with any Arduino device.

Basic Rules Of Using Arduino C Each logical “line of code” ends in a semicolon (;), which may or maynot be a single line on your screenBlocks of code are surrounded by {curly braces}Names of things are case sensitive, so it’s good to be consistent.Use myvariable or myVariable or my variable, but not a mix of those.Strings (you will learn about them later) are enclosed in “doublequotes”, and single characters are enclosed in single quotes.You write source code which is human readableThe precompiler and the compiler turn the source code intoexecutable instructions (machine language)The linker connects the executable instructions into a singleexecutable programThe executable program is uploaded to the Arduino and runs

Components Of A ProgramComments// foo or/*foo*/Variablesint counter 0;Operationscounter counter 1;Conditionalsif(counter 0) {counter counter -1;}Loopswhile(counter 0) {counter counter – 1; }Function Definitionsint printInt(int x) {Serial.println(x); }Function CallsprintInt(counter);References to othercode#include PS2Keyboard.h

Comments Comments are not used by the compiler at all.They are purely for reference by humansComments can tell you what a block of code isdoing and why, expected inputs, gotchas, etc.There are line comments where anythingfollowing // on a line is ignored by the compilerThere are block comments that can spanmultiple lines, starting with /* and ending with */

Variables Variables are like X in algebra: they are placeholders for values, and that valuemay change over the life of the program. Using longer words instead of just “x”will make it easier to follow your program, but single letter variable names are finefor loops.Variables need to be declared before they are used (int peopleCounter;). Theymay also be defined (assigned a value) at the same time (int peopleCounter 0;)Variables are declared with a specific type, and can only hold that kind of dataever. For instance, there’s char for a single character, int for integers, and floatsand doubles for floating point numbers. In some cases, C will automaticallyconvert data between different types before you, but there may be some data lossin the process.Each variable is associated with a memory address that holds the value for thatvariable. Larger data types take up more memory to store.Variables can be arrays, which is an ordered list of data, all of the same type. Theprogram can iterate through all of the array elements. More on this later.Some variables are pointers to memory addresses, which in turn may be othervariables or parts of other variables. This is a very hard topic, and we will onlycover certain important uses of pointers.

Constants Some variables are set up in the beginning of your program so the same value canbe defined once and used throughout your program, but the value will neverchange. This is a very good practice, as it saves memory, makes it clear that allreferences are referring to the same thing, and makes it easier to change thosevalues centrally.This is often used for pin assignments, messages, min/max values, identifiers,mathematical constants (number of seconds in a day) etc.One way of creating a constant is to use the #define precompiler keyword. Thisdoesn’t actually create a variable at all, but the precompiler basically does a searchand replace in the code #define BUZZER PIN 7 #define SECONDS PER DAY 86400Another way is to use a real variable, but tell the compiler it’s a constant const int BUZZER PIN 7;

Operations Most operations are some kind of mathhappening on variables to change their value.The common ones use the same symbols usedin regular math, though some are done usingfunctions. force mass * (velocity-initialVelocity)/time; x (a * b) – (m /2); x ; // That’s the same as x x 1

Conditionalsif( col MAX COL) {col MAX COL);}if( col MIN COL) {col 17;}if( col MAX COL) {col MAX COL;} else {col ;}// is comparison// is assignment// Increment col if within range“if()” is the main conditional, but there are othersnew col col MAX COL ? MAX COL : col 1; // ternary operatorSwitch statements can be used to branch based on different possible values

Loops// Loop the integer x through all the digits// for(setup ; conditional ; iteration) { }for(int x 0; x 10 ; x ) {Serial.println(x);}// while(conditional) { }int x 0;while(x 10) {Serial.println(x);x ;}

Unique To Arduino Arduino C/C has several additions to the standard to interact with thehardware and because it’s embedded. Constants defined (HIGH, LOW, INPUT, OUTPUT, LED BUILTIN, etc) Classes defined to talk to the built-in hardware, like Serial Functions defined to talk to the inputs and outputs Program flow: setup() loop() I/O: digitalRead() digitalWrite() analogRead() analogWrite() pinMode() Timing: delay() millis() micros() Math: map()Classes in libraries that abstract external devices (sensors, indicators, etc)

OK! Let’s look at some code! Launch the Arduino IDE (integrated Development Environment)Connect the USB cable between the computer and the Arduino.The USB cable can power the board, but is also used foruploading programs and communicating with themYou should see the power light on the Arduino go on.Set the specific Arduino model you are using by choosing Tools /BoardSet the serial port the Arduino is connected to by choosing Tools/ Port (this will be different on different computers)We are now ready to begin

Hello World, Arduino Style The Arduino IDE comes with tons of examplesalready built in, nicely categorized. We will choosethe simplest one, BlinkChoose File / Examples / 01. Basics / BlinkChoose Sketch / Verify. This compiles the code butdoesn’t upload it, to verify it builds cleanlyChoose Sketch / Upload. This sends the compiledprogram to the Arduino Did it upload successfully? Do you see the light blinking?

The Blink Example, Annotated/* ------- Anything between /* and */ are comments, and not executed.BlinkTurns an LED on for one second, then off for one second, repeatedly. */// the setup function runs once when you press reset or power the boardvoid setup() { ------- setup() is a function called at the startup// initialize digital pin LED BUILTIN as an output.pinMode(LED BUILTIN, OUTPUT);}// the loop function runs over and over again forevervoid loop() { ------- Arduino programs don’t have an end. They loop forever.digitalWrite(LED BUILTIN, HIGH);// Turn the pin on, turning the LED ondelay(1000);// wait for a seconddigitalWrite(LED BUILTIN, LOW);// Turn the pin off, turning the LED offdelay(1000);// wait for a second}

Let’s Make Blink Interactive We will wire up a button to the Arduino for it to“listen to”. We will use a breadboard to makethe wiring easy and removable.

Digital InputsArduinos usually have quite a few digital inputs.Digital here means the input is either on (HIGH)or off (LOW) based on the voltage at the inputpin. In reality voltages are continuous so “close tozero” is off and “close to 5V” is on. Exact voltagelimits will vary between some boards. These conventions are called “TTL” or Transistorto Transistor Logic. Some boards use 3V or3.3V instead of 5V.

Wiring UpThe Button

Wiring Up The ButtonConnect the button between E2 and E4 (we’reonly using 2 pins, yours may have 4 pins) Connect the resistor between D2 and D6 Connect a jumper between C2 on thebreadboard and digital input pin 2 on the Arduino Connect a jumper between C4 on thebreadboard and 5V on the Arduino Connect a jumper between C6 on thebreadboard and either GND on the Arduino

Wiring UpThe Button

Change The Software And Run It Open another example: Choose File / Examples / 02.Digital / ButtonChoose Sketch / Verify. This compiles the code butdoesn’t upload it, to verify it builds cleanlyChoose Sketch / Upload. This sends the compiledprogram to the ArduinoDid it upload successfully?Do you see the light blinking only when you press thebutton?

What’s Changed in the code? We define a variable buttonPin to hold the pin numberthe button is connected toWe define the pin the LED is onWe define a variable to hold the state of thebutton/switchAt the top of the loop, every time we check the state ofthe switch using digitalRead(buttonPin). If it’s HIGH(positive voltage) we turn the LED on, and if not, weturn the LED off

Get it so far? What of the material we covered so far do youfind easy to understand?What of the material we covered so far do youfind hard to understand?

Let’s Turn It Into A Light Sensor Arduinos have LOTS of inputs and outputs so we can hook up allsorts of devices at the same timeLet’s hook up a photosensor to an analog input and use it to blinkthe LED slower or fasterAnalog inputs return a number between 0 and 1023 inclusivebased on 0V to 5V fed to themThe photosensor will change its resistance based on the lightlevel. The more light the lower the resistance, the higher thevoltageWe can hook it up to an analog input and measure the drop involtage through it, and change how fast the LED on the Arduinoblinks

Wiring Up The PhotosensorConnect a jumper between B2 on thebreadboard and the analog input pin A0 on theArduino Connect the photosensor between A2 and A4 onthe breadboard The photosensor can “bypass” the switch. Theyare electrically in parallel. Either one will make aconnection between row 2 and row 4

Wiring UpThePhotosensor

lightblink.inoconst int sensorPin A0;// Select the input pin for the light sensorconst int ledPin 13;// Select the pin for the LED// You may need to play with the sensorMin and sensorMax depending on your photosensorconst int sensorMin 60;// Minimum value expected from the sensorconst int sensorMax 700; // Maximum value expected from the sensorconst int delayMin 200;// Shortest delay time in msconst int delayMax 1000; // Longest delay time in msvoid setup() {Serial.begin(9600);// Set up the serial port to talk to the PCpinMode(ledPin, OUTPUT); // Declare the ledPin as an OUTPUT:Serial.println("Starting"); // Note: println has an L not a 1}void loop() {// Read the value from the sensor, 0-1024, but generally over 600int sensorValue analogRead(sensorPin);// map() takes a value in an expected input range and scales it to// a different output range. Here I am also reversing the low and// high so the higher the resistance, the lower the delay, the// faster it blinksint delayValue map(sensorValue, sensorMin, sensorMax, delayMax, delayMin);Serial.print("Sensor: ");Serial.print(sensorValue);Serial.print(" Delay: ");Serial.println(delayValue);digitalWrite(ledPin, HIGH);delay(delayValue);digitalWrite(ledPin, LOW);delay(delayValue);}// Turn the ledPin on// Pause for delayValue milliseconds:// Turn the ledPin off:// Pause for for delayValue milliseconds:

Change The Software And Run It Open up a new sketch, and type in the code from the previous slideChoose Sketch / Verify. This compiles the code but doesn’t upload it, to verify itbuilds cleanly Choose Sketch / Upload. This sends the compiled program to the Arduino Did it upload successfully? Do you see the light blinking? Choose Tools / Serial Monitor, and you can see the output written by the Serial.printand Serial.println statements. This is a great way of debugging your program withoutadding hardware.If you cover up the photosensor, the delays will reduce and the light will blink slowerIf you cover up the photosensor AND press the button, the light blinks faster again,because the button “bypasses” the photosensor and sends full voltage to the input pin

Keep Calm And Code On At this point, you have hooked up severaldevices to an Arduino, ran several programsthat did different things, and gained a lot ofknowledgeThe rest of the presentation covers slightlyharder topics, but nothing you have to try now.

https://www.youtube.com/watch?v thLv8S9t7S0https://www.youtube.com/watch?v mc979OhitAghttps://www.youtube.com/watch?v 6Maq5IyHSucO is for Ohm @adafruitHow ELECTRICITY worksSimple guide to electronic components

Example Projects Learning roboticsHome and environmentalmonitoring, alarms, andcontrol, IoTControlling signs anddisplaysCosplay and theaterGaming andentertainment

What Would Your First Project Be? Now that you have an idea what Arduinos cando, and what they’re good at, can you think ofsome Arduino projects?Can you think of interesting or useful things tohook up to an Arduino as input or output?

Arrays Arrays are ordered collections of a fixed number of elements, all of the samedata type, and stored one after another contiguously in memoryYour program can access or update each individual element of the array, oriterate through the arrayArray elements are numbered starting at 0, not 1, So the last element of a 4element array is actually 3#define COINS MAX 4int coins[COINS MAX];coins[0] 1;coins[1] 5;coins[2] 10;coins[3] 25;for(int x 0; x COINS MAX; x ) {// x should go from 0 to 1 to 2 to 3 but not 4Serial.println( coins[x]);}

Strings Strings are a series of numbers, letters, and symbols, often holdingsome human readable message, like “Hello, world!”.There isn’t really a native data type for strings in C/C . They arestored as an array of characters (char arrays, or char []) where eachcharacter in the string is one element of the array, plus the value 0after the last character in the string to denote the end of the string.There are many C functions that know how to deal with char arrayswith a 0 at the end, so you can search strings, append to string,concatenate strings, compare strings, etc. They all start with “str.()”,like strcmp().char myString[] ”Hello, world!”;myString[5] would be equal to ‘,’

What can you connect to an Arduinoas input or output? Switches LCD displays Potentiometers Other computers Networking devices Motors Solenoids, actuators Low voltage lighting Power transistors Current, voltage, light,sound, heat, humidity,magnetism, distance(and many more)sensorsOutput from othercomputers

What have I done with Arduinos I built a wearable convention badge with colorchanging lights that responds to the environment,using the Adafruit Circuit Playground ExpressI created a lighting controller that switches 110vlights, and can make RGB color changing LEDs goto the music, has Bluetooth and keyboard controlI am made a basement monitor that reportstemperature, humidity, lights left on, faulty sumppumps, HVAC error conditions, and water leaksI am working on a StreamDeck controller

What should I change? Are there topics I should add? Something you would like more detail in? Something I should leave out?

Reference Arduino website: https://www.arduino.cc/ Espressif ESP32 https://en.wikipedia.org/wiki/ESP32 Esspressif ESP8266 https://en.wikipedia.org/wiki/ESP8266 Adafruit https://www.adafruit.com/ Circuit Playground Express https://www.adafruit.com/product/3333 Sparkfun https://www.sparkfun.com You Do It Electronics http://www.youdoitelectronics.com/ Microcenter https://www.microcenter.com/ MIT AppInventor (create phone apps) https://appinventor.mit.edu/

Thank you all!I look forward to your questions and feedbackdavid@thekramers.netYou can download my presentations athttp://www.thekramers.net/r/arduino/

Arduino 101 Class For those new to programming and the Arduino Version 3.7 (remote) This Presentation I look forward to your questions and feedback . The Arduino was developed in the early 2000s to create simple, low cost tools for creating digital