0
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
会员中心
创作中心
发布
  • 发文章

  • 发资料

  • 发帖

  • 提问

  • 发视频

创作活动
BOK-14263

BOK-14263

  • 厂商:

    SPARKFUNELECTRONICS

  • 封装:

  • 描述:

    SPARKFUN INVENTORS KIT GUIDEBOO

  • 数据手册
  • 价格&库存
BOK-14263 数据手册
SparkFun Inventor ’s Kit VERSION 4.0a Your Guide to the SIK for the SparkFun RedBoard SparkFun Inventor’s Kit, Version 4.0 WELCOME TO THE SPARKFUN INVENTOR’S KIT (SIK) GUIDE. This is your map for navigating beginning embedded electronics. This booklet contains all the information you will need to build five projects encompassing the 16 circuits of the SIK for the SparkFun RedBoard. At the center of this manual is one core philosophy: that anyone can (and should) play around with electronics. When you’re done with this guide, you will have built five great projects and acquired the know-how to create countless more. Now enough talk — let’s start something! For a digital version of this guide with more in-depth information for each circuit and links explaining relevant terms and concepts, visit: sparkfun.com/SIKguide Contents INTRODUCTION 2 2 The RedBoard Platform 3 Baseplate Assembly 4 RedBoard Anatomy 5 Breadboard Anatomy 6 The Arduino IDE 10 Inventory of Parts PROJECT 1: LIGHT 12 13 Circuit 1A: Blinking an LED 20 Circuit 1B: Potentiometer 26 Circuit 1C: Photoresistor 31 Circuit 1D: RGB Night-Light PROJECT 2: SOUND 36 37 Circuit 2A: Buzzer 42 Circuit 2B: Digital Trumpet 47 Circuit 2C: “Simon Says” Game PROJECT 3: MOTION 53 54 Circuit 3A: Servo Motors 60 Circuit 3B: Distance Sensor 65 Circuit 3C: Motion Alarm PROJECT 4: DISPLAY 71 72 Circuit 4A: LCD “Hello, World!” 77 Circuit 4B: Temperature Sensor 82 Circuit 4C: “DIY Who Am I?” Game PROJECT 5: ROBOT 88 89 Circuit 5A: Motor Basics 96 Circuit 5B: Remote-Controlled Robot 102 Circuit 5C: Autonomous Robot GOING FURTHER 106 1 : intro The RedBoard Platform THE DIY REVOLUTION: At SparkFun we believe that an understanding of electronics is a core literacy that opens up a world of opportunities in the fields of robotics, Internet of Things (IoT), engineering, fashion, medical industries, environmental sciences, performing arts and more. This guide is designed to explore the connection between software and hardware, introducing Arduino code and SparkFun parts as they are used in the context of building engaging projects. The circuits in this guide progress in difficulty as new concepts and components are introduced. Completing each circuit means much more than just “experimenting”; you will walk away with a fun project you can use — and a sense of accomplishment that is just the beginning of your electronics journey. At the end of each circuit, you'll find coding challenges that extend your learning and fuel ongoing innovation. The SparkFun RedBoard is your RESET A COMPUTER FOR THE PHYSICAL WORLD 7-15V development platform. At its roots, the RedBoard is essentially a small, portable IOREF push of a button or a reading from a light 5V sensor) and interpreting that information GND LED light or spinning an electric motor). A1 A2 A3 A4 A5 ON world of electronics and relating it to the A0 ISP comes in; this board is capable of taking the VIN ANALOG IN That’s where the term “physical computing” GND POWER to control various outputs (like blinking an 3.3V DIGITAL (PWM~) RESET START SOMETHING It is capable of taking inputs (such as the 13 TX RX computer, also known as a microcontroller. SCL SDA AREF GND 13 12 ~11 ~10 ~9 8 7 ~6 ~5 4 ~3 2 TX 1 RX 0 physical world in a real and tangible way. THE SPARKFUN REDBOARD is one of a multitude of development boards based on the ATmega328 microprocessor. It has 14 digital input/output pins (six of which can be PWM outputs), six analog inputs, a 16MHz crystal oscillator, a USB connection, a power jack, and a reset button. You’ll learn more about each of the RedBoard's features as you progress through this guide. 2 : intro Baseplate Assembly Before you can build circuits, you’ll want to first assemble the breadboard baseplate. This apparatus makes circuit building easier by keeping the RedBoard microcontroller and the breadboard connected without the worry of disconnecting or damaging your circuit. TO BEGIN, collect your parts: the RedBoard, breadboard, included screwdriver, baseplate and two baseplate screws. Your screwdriver has both Phillips and flatheads. If it is not already in position, pull the shaft out and switch to the Phillips head. PEEL the adhesive backing off the breadboard. CAREFULLY ALIGN the breadboard over its spot on the baseplate. The text on the breadboard should face the same direction as the text on the baseplate. Firmly press the breadboard to the baseplate to adhere it. ALIGN THE REDBOARD with its spot on the baseplate. The text on it should face the same direction as the text on the breadboard and the baseplate. Using one of the two included screws, affix the RedBoard to one of the four stand-off holes found on the baseplate. The plastic holes are not threaded, so you will need to apply pressure as you twist the screwdriver. Screw the second screw in the stand-off hole diagonally across from the first. With that, your baseplate is now assembled. 3 : intro Anatomy of the SparkFun RedBoard F E B D 7 ~6 ~5 4 ~3 2 TX 1 RX 0 RESET SCL SDA AREF GND 13 12 ~11 ~10 ~9 8 H DIGITAL (PWM~) 13 TX RX ON START SOMETHING C G I K A5 A4 A3 A2 A1 ANALOG IN A0 VIN GND GND POWER 5V 3.3V IOREF 7-15V A RESET ISP J REDBOARD HARDWARE OVERVIEW A POWER IN (BARREL JACK) B POWER IN (USB PORT) C LED (RX: RECEIVING) Shows when the FTDI chip is receiving data bits from the computer. D LED (TX: TRANSMITTING) Shows when the FTDI chip is transmitting data bits to the computer. E ONBOARD LED PIN D13 F PINS AREF, G R O U N D , D I G I TA L , RX, TX, SDA, SCL G POWER LED H RESET BUTTON I ISP HEADER This is the In-System Programming header. It is used to program the ATMega328 directly. It will not be used in this guide. J ANALOG IN, V O L TA G E I N , GROUND, 3.3 AND 5V OUT, RESET The power bus has pins to power your circuits with various voltages. The analog inputs allow you to read analog signals. K RFU 4 : intro Can be used with either a 9V or 12V “wall-wart” or a battery pack. Provides power and communicates with your board when plugged into your computer via USB. This LED, connected to digital pin 13, can be controlled in your program and is great for troubleshooting. These pins can be used for inputs, outputs, power and ground. Illuminated when the board is connected to a power source. A manual reset switch that will restart the RedBoard and your code. This stands for Reserved for Future Use. Anatomy of the Breadboard A breadboard is a circuit-building platform that allows you to connect multiple components without using a soldering iron. POWER BUS H O R I Z O N TA L R O W S Each side of the breadboard has a pair of Each series of 5 sockets marked vertical connections marked – and + a–e and f–j are connected. + POWER: Each + sign runs power anywhere in the vertical column. Components connected to a row will be connected to any other part inserted in the same row. – GROUND: Each – sign runs to ground anywhere in the vertical column. CENTERLINE This line divides the breadboard in half, restricting electricity to one half or the other. MAKING A CONNECTION Most of the components in this kit are breadboardfriendly and can be easily installed and removed. 5 : intro The Arduino IDE IN ORDER TO GET YOUR REDBOARD UP AND RUNNING, you'll need to download the newest version of the Arduino software from www.arduino.cc (it's free!). This software, known as the Arduino IDE (Integrated Development Environment), will allow you to program the RedBoard to do exactly what you want. It’s like a word processor for coding. With an internet-capable computer, open up your favorite browser and type the following URL into the address bar: DOWNLOAD THE SOFTWARE HERE: arduino.cc/downloads 1. DOWNLOAD AND INSTALL ARDUINO IDE Select the installer option appropriate for the operating system you are using. Once finished downloading, open the file and follow the instructions to install. 2. INSTALL USB DRIVERS In order for the RedBoard hardware to work with your computer’s operating system, you will need to install a few drivers. Please go to www.sparkfun.com/FTDI for specific instructions on how to install the USB drivers onto your computer. 3. CONNECT THE REDBOARD TO A COMPUTER Use the USB cable provided in the SIK to connect the RedBoard to one of your computer’s USB inputs. 6 : intro 4. DOWNLOAD AND INSTALL THE SIK CODE Each of the circuits you will build in the SparkFun Inventor’s Kit has an Arduino code sketch already written for it. This guide will show you how to manipulate that code to control your hardware. DOWNLOAD THE CODE HERE: sparkfun.com/SIKcode COPY “SIK GUIDE CODE” INTO “EXAMPLES” LIBRARY IN ARDUINO FOLDER Your browser will download the code automatically or ask you if you would like to download the .zip file. Select “Save File.” Locate the code (usually in your browser’s “Downloads” folder). You'll need to relocate it to the “Examples” subfolder in your Arduino IDE installation in order for it to function properly. Unzip the file “SIK GUIDE CODE.” It should be located in your browser’s “Downloads” folder. Right-click (or ctrl + click) the zipped folder and choose “unzip.” MAC OS: Find “Arduino” in your “Applications” folder in Finder. Arduino Right-click (ctrl + click) on “Arduino” and select “Show Package Contents.” Open Show Package Contents Move to Trash Copy or move the unzipped “SIK Guide Code” folder from your “Downloads” folder into the Arduino application’s folder named “Examples.” Arduino ARDUINO Open Contents C O NShow T E N T Package S JAVA Move to Trash EXAMPLES WINDOWS: Copy or move the unzipped “SIK Guide Code” files from “Downloads” to the Arduino application’s “Examples” folder. LOCAL DISK (C:) PROGRAM FILES ARDUINO EXAMPLES LINUX: Distribution-specific setup instructions for Linux can be found at: http://arduino.cc/playground/learning/linux 7 : intro 5. OPEN THE ARDUINO IDE: Open the Arduino IDE software on your computer. Poke around and get to know the interface. We aren’t going to code right away; this step is to set your IDE to identify your RedBoard. E B D C G Blink | Arduino 1.8.5 A K Blink H THE THREE MOST I M P O R TA N T COMMANDS IN THE ARDUINO IDE I F Arduino/Genuino Uno on/dev/cu.usbserialDNO18JWS GRAPHICAL USER INTERFACE (GUI) A VERIFY Compiles and approves your code. It will catch errors in syntax (like missing semicolons or parentheses). B UPLOAD Sends your code to the RedBoard. When you click it, you should see the lights on your board blink rapidly. C S AV E Saves the currently active sketch. D OPEN Opens an existing sketch. E NEW Opens up a new code window tab. F DEBUG WINDOW G SKETCH NAME H CODE AREA Displays any errors generated by your sketch. Displays the name of the sketch you are currently working on. Where you compose or edit the code for your sketch. I MESSAGE AREA J CONNECTION AREA Displays the board and serial port currently selected. K SERIAL MONITOR Opens a window that displays any serial information your RedBoard is transmitting (useful for debugging). 8 : intro Indicates if the code is compiling, uploading or has errors. J IK_Circuit_1A-Blink IK_Circuit_1A-Potentiometer IK_Circuit_1A-Photoresistor IK_Circuit_1A-RGBNightlight IK_Circuit_1A-Buzzer IK_Circuit_1A-DigitalTrumpet NOTE: Your SparkFun RedBoard and the Arduino/Genuino UNO are IK_Circuit_1A-SimonSays File 6. SELECT YOUR BOARD AND SERIAL DEVICE interchangeable, but you won’t find the RedBoard listed in the Arduino software. Select “ARDUINO/GENUINO UNO” instead. Arduino Edit Sketch File Tools Edit Sketch Help Auto Format Archive Sketch Fix Encoding and Reload Serial Monitor Serial Plotter ircuit_01 ircuit_02 ircuit_03 ircuit_04 File Edit ircuit_05 ircuit_06 ircuit_07 File Circuit_01 Circuit_02 Circuit_03 Circuit_04 Circuit_05 Circuit_06 Circuit_07 Edit Tools Help Auto Format Archive Sketch Fix Encoding and Reload Serial Monitor Serial Plotter Board: “Arduino/Genuino Uno” Port Get Board Info Boards Manager… TeensyDuino Teensy 3.6 Teensy 3.5 SELECT YOUR BOARD Teensy 3.2/3.1 Board: “Arduino/Genuino Uno” Teensy 3.0 Tools > Board > Arduino/Genuino UNO Port Serial Ports Teensy LC Get Board Info /dev/cu.usbserialDNO18JWS Teensy++ 2.0 Programmer: “AVRISPmkII” Teensy 2.0 Burn Bootlader Arduino AVR Boards Arduino/Genuino Uno Arduino Duemilanove or Diecimila Sketch Tools Help Arduino Nano Auto Format Archive Sketch SELECT YOUR PORT (WINDOWS) Fix Encoding and Reload Circuit_01 Serial Monitor Circuit_02 Tools > Port > COM#(Arduino/Genuino UNO) Serial Plotter Circuit_03 Circuit_04 Board: “Arduino/Genuino Uno” Circuit_05 Port Serial Ports Circuit_06 Get Board Info COM1 Circuit_07 COM2 Programmer: “AVRISPmkII” Burn Bootlader COM51(Arduino/Genuino UNO) Sketch Tools Help Auto Format Archive Sketch Fix Encoding and Reload Serial Monitor Serial Plotter SELECT YOUR PORT (MAC OS) Tools > Port > /dev/cu.usbserialXXXXXXXX Board: “Arduino/Genuino Uno” Port Get Board Info Serial Ports /dev/cu.usbserialDNO18JWS Programmer: “AVRISPmkII” Burn Bootlader SELECT YOUR PORT (LINUX) Distribution-specific serial device setup instructions can be found HERE: http://arduino.cc/playground/learning/linux 9 : intro Inventory of Parts The SparkFun Inventor’s Kit contains an extensive array of electronic components. As you work your way through each circuit, you will learn to use new and more complicated parts to accomplish increasingly complex tasks. LEDS L C D D I S P L AY POTENTIOMETER S W I TC H ULTRASONIC D I S TA N C E S E N S O R PIEZO BUZZER M OTO R DRIVER TJP16527BH2 R 10k 100k 330 A12 GND A11 ST BY A02 B11 B02 B12 B01 MOTOR DRIVER GND PWMB GND G E A R M OTO R S JUMPER WIRES 1 O K Ω R E S I S TO R S 10k 100k PWMA VCC A01 GND Echo Trig VCC 1652 T H8106 VM PUSH B U T TO N S 3 3 0 Ω R E S I S TO R S 330 P H OTO R E S I S TO R T E M P E R AT U R E SENSOR TMP BREADBOARD ++ -– 21 20 19 19 18 18 17 17 16 16 15 15 14 14 13 13 12 12 11 11 10 10 9 9 8 8 7 7 6 6 5 5 4 4 3 3 2 2 1 1 a b c d e f g h i j A5 22 21 20 A4 23 22 A3 24 24 23 A2 25 25 ++ -– 7 ~6 ~5 4 ~3 2 TX 1 RX 0 27 26 A1 28 A0 29 VIN 30 GND j GND i 5V h 3.3V g RESET f IOREF e SCL SDA AREF GND 13 12 ~11 ~10 ~9 8 d 7-15V c ++ -– 10 : intro b ANALOG IN a POWER 27 ISP 26 ON START SOMETHING 28 DIGITAL (PWM~) 13 TX RX 29 RESET 30 S PA R K F U N R E D B OA R D ++ -– SERVO M OTO R Let’s Get Started With Your First Circuit! 11 : intro BLINKING AN LED A READING A POTENTIOMETER READING A PHOTORESISTOR B C RGB NIGHT-LIGHT D PROJECT 1 NEW IDEAS Welcome to your first SparkFun Inventor’s Kit Each project will introduce new project. Each project is broken up into several concepts and components, which will circuits, the last circuit being a culmination of be described in more detail as you the technologies that came before. There are five progress through the circuits. projects total, each designed to help you learn about new technologies and concepts. This first project will set the foundation for the rest and will aid in helping you understand the fundamentals of circuit building and electricity! In Project 1, you will learn about LightEmitting Diodes (LEDs), resistors, inputs, outputs and sensors. The first project will be to build and program your own multicolored night-light! The night-light uses a sensor to turn on an RGB (Red, Green, Blue) LED when it gets dark, and you will be able to change the color using an input knob. 13 : circuit 1a NEW COMPONENTS INTRODUCED IN THIS PROJECT • LEDS •   R E S I S TO R S • POTENTIOMETERS •   P H OTO R E S I S TO R S NEW CONCEPTS INTRODUCED IN THIS PROJECT • POLARITY •   O H M ' S L AW •   D I G I TA L O U T P U T •   A N A L O G V S . D I G I TA L • ANALOG INPUT •   A N A L O G T O D I G I TA L C O N V E R S I O N •   V O L TA G E D I V I D E R •   P U L S E - W I D T H M O D U L AT I O N • FUNCTIONS YOU WILL LEARN •   H OW TO U P L OA D A P R OG R A M TO YOUR REDBOARD • CIRCUIT-BUILDING BASICS •   H OW TO CO N T R O L L E D S W I T H D I G I TA L O U T P U T S •   H OW TO R E A D S E N S O R S WITH ANALOG INPUTS Circuit 1A: Blinking an LED You can find LEDs in just about any source of light, from the bulbs lighting your home to the tiny status lights flashing on your home electronics. Blinking an LED is the classic starting point for learning how to program embedded electronics. It’s the “Hello, World!” of microcontrollers. In this circuit, you’ll write code that makes an LED blink on and off. LED 330Ω NEW COMPONENTS which you can look up using are small lights made from a silicon diode. 330 10k YOU NEED 2 JUMPER WIRES bands. Each color stands for a number, 100k LIGHT-EMITTING DIODES (LEDS) RESISTOR a resistor chart. One can be found at the back of this book. They come in different colors, brightnesses and sizes. LEDs (pronounced el-ee-dees) have a positive (+) leg and a negative (-) leg, and they will only let electricity flow NEW CONCEPTS through them in one direction. LEDs can POLARITY: Many electronics also burn out if too much electricity flows components have polarity, through them, so you should always use a meanig electricity can (and – + should) flow through them in only one direction. Polarized components, like an LED, have a positive and a negative leg and only work when electricity flows through them in one direction. Some components, like resistors, do not have polarity; electricity can flow through them in either direction. OHM’S LAW describes the relationship between the three fundamental elements of electricity: resistor to limit the current when you wire voltage, resistance and current. This an LED into a circuit. relationship can be represented by this equation: RESISTORS resist the flow of electricity. You can use them to protect sensitive components like LEDs. The strength of a resistor (measured in ohms) is marked on the body of the resistor using small colored V=I•R V = Voltage in volts I = Current in amps 14 : circuit 1a RESET 7 ~6 ~5 4 ~3 2 TX 1 RX 0 SCL SDA AREF GND 13 12 ~11 ~10 ~9 8 R = Resistance in ohms (Ω) DIGITAL (PWM~) 13 TX RX This equation is used to calculate what resistor values are suitable to sufficiently limit the current flowing to ON the LED so that it does not get too hot and burn out. START SOMETHING ISP DIGITAL OUTPUT: When working with A5 A4 A3 A2 A1 ANALOG IN A0 VIN GND GND 5V 3.3V RESET IOREF 7-15V microcontrollers such as the RedBoard, there POWER are a variety of pins to which you can connect electronic components. Knowing which pins perform which functions is important when building your circuit. In this circuit, we will be using what is known as a digital output. There are 14 of these pins found on the RedBoard. A digital output only has two states: NEW IDEAS ELECTRICAL SAFETY: Never work on your circuits while the board is connected to a power source. The SparkFun RedBoard operates at 5 volts, which, while not enough to injure you, is enough to damage the components in your circuit. COMPONENT ORIENTATION & POLARITY: Instructions on how to orient each of the new components will be given before each circuit diagram. Many components have polarity and have only one correct orientation, while others are nonpolarized. RESISTOR LEADS Components like resistors need to have their legs bent into 90° angles in order to F L AT E D G E SHORT LEG – + POLARIZED COMPONENTS Pay close attention to the LED. The negative side of the LED is the short leg, marked with a flat edge. 15 : circuit 1a correctly fit in the breadboard sockets. HOOKUP GUIDE READY TO START HOOKING EVERYTHING UP? Check out the circuit diagram and hookup table below to see how everything is connected. F L AT E D G E e f g h i j 1 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 ++ -– 7-15V 3.3V 13 13 5V 14 14 15 15 16 16 17 17 18 18 19 19 A2 20 20 A3 21 21 A4 GND GND VIN A0 A1 ON ANALOG IN 23 ISP CIRCUIT DIAGRAMS: Each circuit containsA5a circuit diagram, which 22 23 SCL SDA AREF GND 13 12 ~11 ~10 ~9 8 DIGITAL (PWM~) RESET 12 START SOMETHING IOREF 11 12 13 TX RX 10 11 POWER 10 22 7 ~6 ~5 4 ~3 2 TX 1 RX 0 acts as a visual aid designed to make it easier for you to see how your circuit 24 24 25 25 should be built. Each colored line represents a jumper wire connection in the 26 26 27 27 circuit. All wires should have two connection points, which you also see in the 28 ++ -– d 10k c 100k b 2 330 a 1 RESET ++ -– 28 29 hookup table below. 30 a b c d e f g h i 29 30 j ++ -– COLORS: Please note that while traditionally red is used for power and black is used for ground, all wires, no matter their color, function the same. HOOKUP TABLES: Many electronics beginners find it helpful to have a coordinate system when building their circuits. For each circuit, you’ll find a hookup table that D13 to J2 …means one end of a component connects lists the coordinates of each component or wire and where to digital pin 13 on it connects to the RedBoard, the breadboard, or both. The your RedBoard and breadboard has a letter/number coordinate system, just the other connects to like the game Battleship. REDBOARD CONNECTION CONNECTION TYPES JUMPER WIRES LED 330Ω RESISTOR (ORANGE, ORANGE, BROWN) D13 to A1(-) to E2 to J2 A2(+) F2 GND to J2 on the breadboard BREADBOARD CONNECTION E1 In this table, a yellow highlight indicates that a component has polarity and will only function if properly oriented. 16 : circuit 1a Open the Arduino IDE Connect the RedBoard to a USB port on your computer.   Open the Sketch: File > Examples > SIK_Guide_Code-V_4 > CIRCUIT_1A-BLINK   Select UPLOAD to program the sketch on the RedBoard. Arduino Tools Help File Edit Sketch New Open Open Recent Sketchbook Examples Close Save Save As Page Setup Print Tools Help 01.Basics 02.Digital 03.Analog 04.Communication 05.Control 06.Sensors 07.Display 08.Strings 09.USB 10.Starter Kit ArduinoISP SIK_Guide-Code-v_4 SIK_Circuit_1A-Blink SIK_Circuit_1A-Potentiometer SIK_Circuit_1A-Photoresistor SIK_Circuit_1A-RGBNightlight SIK_Circuit_1A-Buzzer SIK_Circuit_1A-DigitalTrumpet SIK_Circuit_1A-SimonSays W H AT Y O U SHOULD SEE The LED will flash on for two seconds, then off for two seconds. If it doesn’t, make sure you have assembled the circuit correctly and verified and uploaded the code to your board. See the Troubleshooting section at the end of this circuit if that doesn’t work. One of the best ways to understand the code you uploaded is to change something and see how it affects the behavior of your circuit. What happens when you change the number in one or both of the delay(2000); lines of code (try 100 or 5000)? 17 : circuit 1a PROGRAM OVERVIEW 1 Turn the LED on by sending power (5V) to digital pin 13. 2 Wait 2 seconds (2000 milliseconds). 3 Turn the LED off by cutting power (0V) to digital pin 13. 4 Wait 2 seconds (2000 milliseconds). 5 Repeat. ONBOARD LED PIN 13: You may have noticed a second, smaller LED blinking in unison with the LED in your breadboard circuit. This is known as the onboard LED, and you can find one on almost any Arduino or Arduino-compatible board. In most cases, this LED is connected to digital pin 13 (D13), the same pin used in this circuit. NEW IDEAS CODE TO NOTE: The sketches that accompany each circuit introduce new programming techniques and concepts as you progress through the guide. The Code to Note section highlights specific lines of code from the sketch and explains them in greater detail. CODE TO NOTE SETUP AND LOOP: Every Arduino program needs these two functions. Code that goes in void setup(){} & between the loop()curly brackets {} runs over and over until the void loop(){} RedBoard is reset or powered off. INPUT OR OUTPUT?: pinMode(13, OUTPUT); between the curly brackets {} of setup()runs once. The code in Before you can use one of the digital pins, you need to tell the RedBoard whether it is an INPUT or OUTPUT. We use a built-in “function” called pinMode() to make pin 13 a digital output. You’ll learn more about digital inputs in Project 2. 18 : circuit 1a CODE TO NOTE DIGITAL OUTPUT: When you’re using a pin as an OUTPUT, you can command it to be digitalWrite(D13, HIGH); HIGH (output 5 volts) or LOW (output 0 volts). Causes the program to wait on this line of code for the amount of DELAY: time in between the brackets, represented in milliseconds (2000ms delay(2000); = 2s). After the time has passed, the program will continue to the next line of code. Comments are a great way to leave notes in your code explaining COMMENTS: //This is a comment /* So is this */ why you wrote it the way you did. Single line comments use two forward slashes //, while multi-line comments start with a /* and end with a */. NEW IDEAS CODING CHALLENGES: The Coding Challenges section is where you will find suggestions for changes to the circuit or code that will make the circuit more challenging. If you feel underwhelmed by the tasks in each circuit, visit the Coding Challenges section to push yourself to the next level. CODING CHALLENGES PERSISTENCE OF VISION: Computer screens, movies and the lights in your house all flicker so quickly that they appear to be on all of the time but are actually blinking faster than the human eye can detect. See how much you can decrease the delay time in your program before the light appears to be on all the time but is still blinking. MORSE CODE: Try adding and changing the delay() digitalWrite() values and adding more commands to make your program blink a message in Morse code. TROUBLESHOOTING I get an error when The most likely cause is that you have the wrong board selected in the Arduino uploading my code IDE. Make sure you have selected Tools > Board > Arduino/Genuino Uno. 19 : circuit 1a TROUBLESHOOTING I still get an error when uploading my code If you’re sure you have the correct Board selected but you still can’t upload, check that you have selected the correct serial port. You can change this in Tools > Serial Port > your_serial_port. Depending on how many devices you have plugged into your computer, you may have several active serial ports. Make sure you are selecting the Which serial port is correct one. A simple way to determine this is to look at your list of serial the right one? ports. Unplug your RedBoard from your computer. Look at the list again. Whichever serial port has disappeared from the list is the one you want to select once you plug your board back into your computer. My code uploads, but my LEDs will only work in one direction. Try taking it out of your LED won’t turn on breadboard, turning it 180 degrees and reinserting it. Jumper wires unfortunately can go “bad” from getting bent too much. The copper wire inside can break, leaving an open connection in your Still not working? circuit. If you are certain that your circuit is wired correctly and that your code is error-free and uploaded, but you are still encountering issues, try replacing one or more of the jumper wires for the component that is not working. You’ve completed Circuit 1A! Continue to circuit 1B to learn about analog signals and potentiometers. BLINKING AN LED A READING A POTENTIOMETER B READING A PHOTORESISTOR C RGB NIGHT-LIGHT D 20 : circuit 1a Circuit 1B: Potentiometer of the knob with your RedBoard, you can make volume controls, speed controls, angle sensors and a ton of other useful inputs for your projects. In this circuit, Potentiometers (also known as “trimpots” or “knobs”) are one of the basic inputs for electronic devices. By tracking the position LED blinks. POTENTIOMETER NEW COMPONENTS 7 JUMPER WIRES RESISTOR ANALOG INPUTS: So far, we’ve only dealt with outputs. The RedBoard also has POTENTIOMETER: A potentiometer is inputs. Both inputs and outputs can be a 3-pin variable resistor. When powered analog or digital. Based on our previous 10k with 5V, the middle pin outputs a voltage 330Ω between 0V and 5V, depending on the position of the knob on trimpot is a single resistor and a wiper, which cuts the resistor in two and input, which can only sense two values, or IOREF 13 TX RX states. 7-15V RESET 3.3V 5V GND GND VIN A0 analog world. There are an infinite number of colors to paint an object, an infinite number of tones we can hear, and an infinite number of smells we can smell. A3 A4 Digital and some A5 ON ANALOG VS. DIGITAL: We live in an A2 ISP NEW CONCEPTS A1 ANALOG IN some pins labeled your RedBoard. There are only six pins that function as analog inputs; they are labeled A0–A5. VOLTAGE DIVIDER signals is their infinite possibilities. VOLTAGE DIVIDERS are simple discrete or finite, meaning there is a limited set of values they can be. The LED from the previous circuit had only two states it could exist in, ON or OFF, when connected to a digital output. circuits that turn some voltage into a smaller voltage using two resistors. A potentiometer is a variable resistor that can be used to create an adjustable voltage divider. A wiper in the middle position means the output voltage will be half of the input. Voltage dividers will be covered in more detail in the next circuit. 20 : circuit 1b 7 ~6 ~5 4 ~3 2 TX 1 RX 0 labeled Analog In on The common theme among these analog Digital signals deal in the realm of the SCL SDA AREF GND 13 12 ~11 ~10 ~9 8 DIGITAL (PWM~) You may have noticed POWER both halves. values versus a digital START SOMETHING moves to adjust the ratio between an analog input can sense a wide range of RESET the potentiometer. Internal to the definition of analog and digital, that means 330 LED device to control the speed at which your 100k YOU NEED you’ll use a potentiometer as an input HOOKUP GUIDE READY TO START HOOKING EVERYTHING UP? Check out the circuit diagram and hookup table below to see how everything is connected. F L AT E D G E e f g h i j 1 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 ++ -– 7-15V 10k d 100k c 330 b 2 RESET 12 3.3V 13 13 5V 14 14 15 15 16 16 17 17 18 18 19 19 A2 20 20 A3 21 21 A4 22 22 A5 23 23 24 24 25 25 26 26 27 27 28 28 b c d e f g h i j A0 A1 ON 30 a VIN ISP 29 30 GND ANALOG IN 29 GND SCL SDA AREF GND 13 12 ~11 ~10 ~9 8 DIGITAL (PWM~) IOREF 11 12 START SOMETHING 10 11 13 TX RX 10 POWER ++ -– a 1 RESET ++ -– 7 ~6 ~5 4 ~3 2 TX 1 RX 0 ++ -– NEW IDEAS POTENTIOMETERS are not polarized and can be installed in either direction. Note that swapping the 5V and GND pins will reverse its behavior. CONNECTION TYPES JUMPER WIRES LED 330Ω RESISTOR (ORANGE, ORANGE, BROWN) POTENTIOMETER REDBOARD CONNECTION 5V to 5V E25 to 5V (+) A1(-) to E2 to C25 + GND to E27 to GND (-) GND (-) BREADBOARD CONNECTION A0 to E1 to E26 GND (-) D13 to J2 A2(+) F2 C26 + C27 21 : circuit 1b Open the Arduino IDE Connect the RedBoard to a USB port on your computer. Open the Sketch: File > File > Examples > SIK_Guide_Code-V_4 > CIRCUIT_1B-POTENTIOMETER   Select UPLOAD to program the sketch on the RedBoard. W H AT Y O U SHOULD SEE You should see the LED blink faster or slower in accordance with your potentiometer. The delay between each flash will change based on the position of the knob. If it isn’t working, make sure you have assembled the circuit correctly and verified and uploaded the code to your board. If that doesn’t work, see the Troubleshooting section. PROGRAM OVERVIEW 1 Read the position of the potentiometer (from 0 to 1023) and store it in the variable potPosition. 2 Turn the LED on. 3 Wait from 0 to 1023 milliseconds, based on the position of the knob and the value of potPosition. 4 Turn the LED off. 5 Wait from 0 to 1023 milliseconds, based on the position of the knob and the value of potPosition. 6 Repeat. 22 : circuit 1b ARDUINO PRO TIP ARDUINO SERIAL MONITOR: The Blink | Arduino 1.8.5 Serial Monitor is one of the Arduino IDE’s many great included features. When Serial Monitor Blink working with embedded systems, it helps to see and understand the values that your program is trying to work with, and it can be a powerful debugging tool when you run into issues where your code is not behaving the way you expected it to. This Arduino/Genuino Uno on/dev/cu.usbserialDNO18JWS circuit introduces you to the Serial Monitor by showing you how to print the values from your potentiometer to it. To see these Serial Monitor button in the upper-right of the Arduino IDE. values, click the Serial Monitor button, found in the upper-right corner of the IDE in most recent versions. You can also select Tools > Serial Monitor from the menu. You should see numeric values print out in the monitor. Turning the potentiometer changes the value as well as the delay between each print. If you are having trouble seeing the values, ensure that you have selected 9600 Serial Monitor printout and baud-rate menu. baud and have auto scroll checked. CODE TO NOTE A variable is a placeholder for values that may change INTEGER VARIABLES: int potPosition; in your code. You must introduce, or “declare,” variables before you use them. Here we’re declaring a variable called potPosition of type int (integer). We will cover more types of variables in later circuits. Don’t forget that variable names are case-sensitive! 23 : circuit 1b CODE TO NOTE Serial commands can be used to send and receive data from your computer. This line of code tells the RedBoard that we SERIAL BEGIN: want to “begin” that communication with the computer, the Serial.begin(9600); that the baud rate, 9600, is the same as the one we selected same way we would say “Hi” to initiate a conversation. Notice in the monitor. This is the speed at which the two devices communicate, and it must match on both sides. ANALOG INPUT: potPosition = analogRead(A0); We use the analogRead() function to read the value on an analog pin. analogRead() takes one parameter, the analog pin you want to use, A0 in this case, and returns a number between 0 (0 volts) and 1023 (5 volts), which is then assigned to the variable potPosition. This is the line that actually prints the trimpot value to SERIAL PRINT: Serial. println(potPosition); the monitor. It takes the variable potPosition and prints whatever value it equals at that moment in the loop(). The ln at the end of println tells the monitor to print a new line at the end of each value; otherwise the values would all run together on one line. Try removing the ln to see what happens. CODING CHALLENGES CHANGING THE RANGE: Try multiplying, dividing or adding to your sensor reading so that you can change the range of the delay in your code. For example, can you multiply the sensor reading so that the delay goes from 0–2046 instead of 0–1023? ADD MORE LEDS: Add more LEDs to your circuit. Don’t forget the current-limiting resistors. You will need to declare the new pins in your code and set them all to OUTPUT . Try making individual LEDs blink at different rates by changing the range of each using multiplcation or division. 24 : circuit 1b TROUBLESHOOTING The potentiometer always reads as 0 or 1023 Make sure that your 5V, A0 and GND pins are properly connected to the three pins on your potentiometer. It is easy to misalign a wire with the actual pot pin. Make sure that you have selected the correct baud rate, No values or random 9600. Also ensure that you are on the correct serial characters in port. The same serial port you use when uploading Serial Monitor code to your board is the same serial port you use to print values to the Serial Monitor. You’ve completed Circuit 1B! Continue to circuit 1C to learn about photoresistors and analog to digital conversion. BLINKING AN LED A READING A POTENTIOMETER B READING A PHOTORESISTOR C RGB NIGHT-LIGHT D 25 : circuit 1b Circuit 1C: Photoresistor circuit, you’ll be using a photoresistor, which changes resistance based on how much light the sensor receives. Using this sensor you can make a simple night-light In circuit 1B, you got to use a potentiometer, which varies resistance that turns on when the room gets dark based on the twisting of a knob. In this and turns off when it is bright. YOU NEED LED PHOTORESISTOR 330Ω RESISTOR 10KΩ RESISTOR 7 JUMPER WIRES PHOTORESISTORS are light- need to use a voltage divider to use our sensitive, variable resistors. As photoresistor, a part that doesn’t output more light shines on the sensor’s voltage. The resistance of the photoresistor head, the resistance between its changes as it gets darker or lighter. That two terminals decreases. They’re changes or “divides” the voltage going an easy-to-use component in through the divider circuit. That divided projects that require ambient- voltage is then read in on the analog to light sensing. digital converter of the analog input. VOLTAGE DIVIDERS CONTINUED: NEW CONCEPTS 330 100k 10k resistance (rather, it reads voltage), we 330 100k Since the RedBoard can’t directly interpret 10k NEW COMPONENTS The voltage divider equation: ANALOG TO DIGITAL CONVERSION: In order to have the RedBoard sense analog signals, we must first pass them through an Analog to Digital Converter (or ADC). The six analog inputs (A0–A5) covered in the last circuit all use an ADC. These Vout=Vin • pins sample the analog signal and create R2 R1+R2 a digital signal for the microcontroller to assumes that you know three values of interpret. The resolution of this signal is the above circuit: the input voltage (Vin), based on the resolution of the ADC. In the and both resistor values (R1 and R2). If R1 case of the RedBoard, that resolution is 10- is a constant value (the resistor) and R2 bit. With a 10-bit ADC, we get 2 ^ 10 = 1024 fluctuates (the photoresistor), the amount possible values, which is why the analog of voltage measured on the Vout pin will signal can vary between 0 and 1023. also fluctuate. 26 : circuit 1c HOOKUP GUIDE READY TO START HOOKING EVERYTHING UP? Check out the circuit diagram and hookup table below to see how everything is connected. F L AT E D G E e f g h i ++ -– j 1 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 7-15V 10k d 100k c 330 b 2 RESET 12 3.3V 13 13 5V 14 14 15 15 16 16 17 17 18 18 19 19 A2 20 20 A3 21 21 A4 22 22 A5 23 23 24 24 25 25 26 26 27 27 28 28 GND VIN A0 A1 c d e f g h i j PHOTORESISTORS: The 0 33 photoresistors, like regular resistors, 0k 10 are not polarized and can be installed in k 10 CONNECTION TYPES JUMPER WIRES LED 330Ω RESISTOR (ORANGE, ORANGE, BROWN) either direction. REDBOARD CONNECTION 5V to 5V(+) D13 to J2 E25 to 5V(+) A1(-) to E2 to ON b 7 ~6 ~5 4 ~3 2 TX 1 RX 0 NEW IDEAS ++ -– 30 a ISP 29 30 ANALOG IN 29 GND SCL SDA AREF GND 13 12 ~11 ~10 ~9 8 DIGITAL (PWM~) IOREF 11 12 START SOMETHING 10 11 13 TX RX 10 POWER ++ -– a 1 RESET ++ -– GND to A0 to GND (-) E26 E27 to BREADBOARD CONNECTION E1 to GND(-) GND(-) A2(+) F2 10KΩ RESISTOR (BROWN, BLACK, ORANGE) B26 to C27 PHOTORESISTOR A26 to B25 27 : circuit 1c Open the Arduino IDE Connect the RedBoard to a USB port on your computer. Open the Sketch: File > Examples > SIK_Guide_Code-V_4 > CIRCUIT_1C-PHOTORESISTOR   Select UPLOAD to program the sketch on the RedBoard. W H AT Y O U SHOULD SEE The program stores the light level in a variable. Using an if/else statement, the variable value is compared to the threshold. If the variable is above the threshold (it’s bright), turn the LED off. If the variable is below the threshold (it’s dark), turn the LED on. Open the Serial Monitor in Arduino. The value of the photoresistor should be printed every so often. When the photoresistor value drops below the threshold, the LED should turn on (you can cover the photoresistor with your finger for testing). NEW IDEAS LIGHT LEVELS: If the room you are in is very bright or dark, you may have to change the value of the threshold variable in the code to make your night-light turn on and off. See the Troubleshooting section for instructions. PROGRAM OVERVIEW 1 Store the light level in the variable photoresistor. 2 If the value of the photoresistor is above the threshold (it’s bright), turn the LED off. 3 Otherwise, the value of the photoresistor is below the threshold (it’s dark), turn the LED on. 28 : circuit 1c CODE TO NOTE IF ELSE STATEMENTS: The if else statement lets your code react to the world by if(logic statement){ running one set of code when the logic statement in the //run if true round brackets is true and another set of code when the } logic statement is false. For example, this sketch uses an else{ if statement to turn the LED on when it is dark, and else //run if false statement to turn the LED off when it is light. } Programmers use logic statements to translate things that happen in the real world into code. Logic statements LOGICAL OPERATORS: (photoResistor < threshold) use logical operators like ‘equal to’ ==, ‘greater than’ > and ‘less than’ Port, and make sure that you select the right port. Start the Serial Monitor in Arduino. Look at the value that the photoresistor is reading in a bright room (e.g., 915). Cover the The light never turns on or always stays on photoresistor, or turn the lights off. Then look at the new value that the photoresistor is reading (e.g., 550). Set the threshold in between these two numbers (e.g., 700) so that the reading is above the threshold when the lights are on and below the threshold when the lights are off. You’ve completed Circuit 1C! Continue to circuit 1D to learn about RGB LEDs, functions and pulse-width modulation. BLINKING AN LED A 30 : circuit 1c READING A POTENTIOMETER READING A PHOTORESISTOR B C RGB NIGHT-LIGHT D Circuit 1D: RGB Night-Light In this circuit, you’ll take the night-light concept to the next level by adding an RGB LED, which is three differently colored Light-Emitting Diodes (LEDs) built into one component. RGB stands for Red, Green and Blue, and these three colors can be combined to create any color of the rainbow! 3 330Ω PHOTORESISTOR 12 JUMPER WIRES RESISTORS 10KΩ YOU NEED RESISTOR POTENTIOMETER blue — inside a normal LED housing. This RGB LED has all the internal LEDs share the same ground wire, so there are four legs in total. To turn on one color, ensure ground is connected, then power one of the legs just as you would a regular LED. Don’t forget the current-limiting resistors. If you PWM PINS: Only a few of the pins 330 small LEDs — one red, one green and one NEW IDEAS 100k RGB LED: An RGB LED is actually three 330 100k 10k NEW COMPONENTS 10k RGB LED on the RedBoard have the circuitry needed to turn on and off fast enough for PWM. These are pins 3, 5, 6, 9, 10 and 11. Each PWM pin is marked with a ~ on the board. Remember, you can only use analogWrite() on these pins. MODULATION): The digitalWrite() ON START SOMETHING RED COMMON ( GND) GREEN BLUE ANALOG OUTPUT (PULSE-WIDTH DIGITAL (PWM~) 13 TX RX form a new color. A5 A4 A3 A2 A1 ANALOG IN A0 VIN GND GND POWER 5V RESET IOREF ISP 7-15V NEW CONCEPTS 7 ~6 ~5 4 ~3 2 TX 1 RX 0 RESET 3.3V will see the colors start to blend together to SCL SDA AREF GND 13 12 ~11 ~10 ~9 8 turn on more than one color at a time, you off so that it is only on 50 percent of the command can turn pins on (5V) or off (0V), time (50% of 5V is 2.5V). By doing this, any but what if you want to output 2.5V? The voltage between 0 and 5V can be produced. analogWrite() command can output 2.5 This is what is known as Pulse-Width volts by quickly switching a pin on and Modulation (PWM). It can create many different colors on the RGB LED. 31 : circuit 1d HOOKUP GUIDE READY TO START HOOKING EVERYTHING UP? Check out the circuit diagram and hookup table below to see how everything is connected. F L AT E D G E b c d e f g h i ++ -– j 1 2 2 330 3 3 330 4 4 5 5 6 6 7 7 8 8 9 9 7-15V 100k 330 100k 10k 100k 10k 10 11 11 RESET 12 12 3.3V 13 13 5V 14 14 15 15 16 16 17 17 18 18 19 19 A2 20 20 A3 21 21 22 22 23 23 24 24 25 25 26 26 27 27 28 28 29 29 10k VIN A0 A1 A5 c d e f g h i ISP b ON A4 REMINDER 7 ~6 ~5 4 ~3 2 TX 1 RX 0 LIGHT LEVELS: If the room you are in is very bright or dark, you may have to change the value of the threshold variable. ++ -– 30 a START SOMETHING GND 13 TX RX GND ANALOG IN 30 IOREF SCL SDA AREF GND 13 12 ~11 ~10 ~9 8 DIGITAL (PWM~) 10 POWER ++ -– a 1 RESET ++ -– j 0 33 0k 10 CONNECTION TYPES k 10 JUMPER WIRES RGB LED 330Ω RESISTORS (ORANGE, ORANGE, BROWN) REDBOARD CONNECTION 5V to 5V(+) D10 to J3 E15 to 5V(+) E27 to GND (-) A5(RED) + E2 to D11 to F2 B26 to C27 PHOTORESISTOR A26 to B25 POTENTIOMETER B15 + B16 + GND (-) J2 E3 to B17 A3(GREEN) + F3 D9 to A0 to E17 to GND(-) A4(GND) + 10KΩ RESISTOR (BROWN, BLACK, ORANGE) 32 : circuit 1d GND to BREADBOARD CONNECTION E5 to E26 E4 to A1 to GND(-) A2(BLUE) F5 J5 E16 E25 to 5V(+) Open the Arduino IDE Connect the RedBoard to a USB port on your computer. Open the Sketch: File > Examples > SIK_Guide_Code-V_4 > SIK_CIRCUIT_1D-RGB NIGHT LIGHT   Select UPLOAD to program the sketch on the RedBoard. W H AT Y O U SHOULD SEE This sketch is not dissimilar from the last. It reads the value from the photoresistor, compares it to a threshold value, and turns the RGB LED on or off accordingly. This time, however, we’ve added a potentiometer back into the circuit. When you twist the trimpot, you should see the color of the RGB LED change based on the trimpot’s value. PROGRAM OVERVIEW 1 Store the light level from pin A0 in the variable photoresistor. 2 Store the potentiometer value from pin A1 in the variable potentiometer. 3 If the light level variable is above the threshold, call the function that turns the RGB LED off. 4 If the light level variable is below the threshold, call one of the color functions to turn the RGB LED on. 5 If potentiometer is between 0 and 150, turn the RGB LED on red. 6 If potentiometer is between 151 and 300, turn the RGB LED on orange. 7 If potentiometter is between 301 and 450, turn the RGB LED on yellow. 8 If potentiometer is between 451 and 600, turn the RGB LED on green. 9 If potentiometer is between 601 and 750, turn the RGB LED on cyan. 10 If potentiometer is between 751 and 900, turn the RGB LED on blue. 11 If potentiometer is greater than 900, turn the RGB LED on magenta. 33 : circuit 1d CODE TO NOTE The analogWrite() function outputs a voltage between ANALOG OUTPUT (PWM): analogWrite(RedPin, 100); 0 and 5V on a pin. The function breaks the range between 0 and 5V into 255 little steps. Note that we are not turning the LED on to full brightness (255) in this code so that the night-light is not too bright. Feel free to change these values and see what happens. NESTED IF STATEMENTS: if(logic statement){ if(logic statement){ } } A nested if statement is one or more if statements “nested” inside of another if statement. If the parent if statement is true, then the code looks at each of the nested if statements and executes any that are true. If the parent if statement is false, then none of the nested statements will execute. MORE LOGICAL OPERATORS: (potentiometer > 0 && potentiometer Port, and select the right port. You’ve completed Circuit 1D! Continue to Project 2 to explore using buzzers to make sound. BLINKING AN LED A READING A POTENTIOMETER B READING A PHOTORESISTOR C RGB NIGHT-LIGHT D 35 : circuit 1d BUZZER D I G I TA L T R U M P E T A ‘ S I M O N S AY S ’ G A M E B C PROJECT 2 In Project 2, you will venture into the world of buttons and buzzers while building your own “Simon Says” game! “Simon Says” is a game in which the LEDs flash a pattern of red, green, yellow and blue blinks, and the user must recreate the pattern using color-coded buttons before the timer runs out. NEW COMPONENTS INTRODUCED IN THIS PROJECT • BUZZER •   B U T TO N S NEW CONCEPTS INTRODUCED IN THIS PROJECT •   A R R AY S • BINARY •   D I G I TA L I N P U T S •   P U L L - U P R E S I S TO R S • FOR LOOPS • MEASURING ELAPSED TIME YOU WILL LEARN •   H OW TO M A K E TO N E S WITH A BUZZER •   H O W T O R E A D A B U T T O N U S I N G D I G I TA L I N P U T S •   H OW TO P R OG R A M A G A M E 36 : circuit 2a Circuit 2A: Buzzer In this circuit, you’ll use the RedBoard and a small buzzer to make music, and you’ll learn how to program your own songs using arrays. POTENTIOMETER NEW COMPONENTS BUZZER: The buzzer uses a small PIEZO BUZZER 4 JUMPER WIRES YOU NEED frequency on the specified pin. The frequency and duration can both be passed to the tone() function when calling it. magnetic coil to vibrate a metal disc inside a plastic housing. By pulsing electricity through the coil at different rates, different frequencies (pitches) of sound can be To turn the tone off, you need to call noTone() or pass a duration of time for it to play and then stop. Unlike PWM, tone() can be used on any digital pin. produced. Attaching a potentiometer to the output allows you to limit ARRAYS are used like variables, but they the amount of current moving can store multiple values. The simplest through the buzzer and lower array is just a list. Imagine that you want its volume. to store the frequency for each note of the C major scale. We could make seven NEW CONCEPTS variables and assign a frequency to RESET BUTTON: The RedBoard has a each one, or we could use an array and store all seven in the same list. To refer built-in reset button. This button will reset to a specific value in the array, an index the board and start the code over from the number is used. Arrays are indexed from beginning, running setup()then loop(). 0. For example, to call the first element in DIGITAL (PWM~) 13 TX RX second element, use array_name[1]; and so on. NOTE USING VA R I A B L E S USING AN A R R AY FREQUENCY[0] A5 A4 A3 A2 A1 ANALOG IN A0 VIN GND GND POWER 5V 3.3V RESET IOREF 7-15V ISP MUSICAL START SOMETHING (HZ) ON FREQUENCY RESET 7 ~6 ~5 4 ~3 2 TX 1 RX 0 SCL SDA AREF GND 13 12 ~11 ~10 ~9 8 the array, use array_name[0]; to call the A 220 A_FREQUENCY B 247 B_FREQUENCY FREQUENCY[1] TONE FUNCTION: To control the C 261 C_FREQUENCY FREQUENCY[2] D 294 D_FREQUENCY FREQUENCY[3] buzzer, you will use the tone() function. E 330 E_FREQUENCY FREQUENCY[4] F 349 F_FREQUENCY FREQUENCY[5] G 392 G_FREQUENCY FREQUENCY[6] This function is similar to PWM in that it generates a wave that is of a certain 37 : circuit 2a HOOKUP GUIDE READY TO START HOOKING EVERYTHING UP? Check out the circuit diagram and hookup table below to see how everything is connected. a b c d e f g h i ++ -– j 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 RESET ++ -– 7-15V RESET 12 3.3V 13 13 5V 14 14 15 15 16 16 17 17 18 18 19 19 A2 20 20 A3 21 21 A4 22 22 A5 23 23 24 24 25 25 26 26 27 27 28 28 potentiometer’s legs are used in these circuits. The potentiometer is acting as GND GND VIN A0 A1 ON flowing to the speaker and ISP the amount of current ANALOG IN a variable resistor, limiting DIGITAL (PWM~) IOREF 11 12 that only two of the START SOMETHING 10 11 POWER 10 13 TX RX VOLUME KNOB: Notice SCL SDA AREF GND 13 12 ~11 ~10 ~9 8 7 ~6 ~5 4 ~3 2 TX 1 RX 0 thus affecting the volume as you turn the knob. ++ -– 29 29 30 30 a b c d e f g h i j ++ -– REMEMBER! POLARITY: The buzzer is polarized. To see which leg is positive and which is negative, flip the buzzer over and look at the markings underneath. Keep track of which pin is where, as they will be hard to see once inserted into the breadboard. There is also text on the positive side of the buzzer, along with a tiny (+) symbol. REDBOARD CONNECTION CONNECTION TYPES JUMPER WIRES GND to GND(-) BUZZER H1(+) to H3(-) POTENTIOMETER 38 : circuit 2a B1 + B2 + B3 D10 to F1 BREADBOARD CONNECTION E2 to GND (-) E1 to F3 Open the Arduino IDE Connect the RedBoard to a USB port on your computer. Open the Sketch: File > Examples > SIK_Guide_Code-V_4 > SIK_CIRCUIT_2A-BUZZER   Select UPLOAD to program the sketch on the RedBoard. W H AT Y O U SHOULD SEE When the program begins, a song will play from the buzzer once. To replay the song, press the reset button on the RedBoard. Use the potentiometer to adjust the volume. PROGRAM OVERVIEW Play the first note for x number of beats using the play() function. A: (Inside the play() function): Take the note passed to the play function and compare it to 1 each letter in the notes array. When you find a note that matches, remember the index position of that note (e.g., sixth entry in the notes array). B: Get a frequency from the frequency array that has the same index as the note that matched (e.g., the sixth frequency). C: Play that frequency for the number of beats passed to the play() function. 2 Play the second note using the play() function ...and so on. 39 : circuit 2a CODE TO NOTE The char, or character, variable stores character values. For example, in this sketch, the play() function gets passed two variables: a character CHARACTER VARIABLES: void play(char note, int beats) variable that represents the mucial note we want to play and an integer variable that represents how long to play that note. A second array takes the character variable and associates a frequency value to it. This makes programming a song easier as you can just reference the character and not the exact frequency. The tone() function will pulse power to a pin at TONE FUNCTION: a specific frequency. The duration controls how tone(pin, frequency, duration); long the sound will play. tone() can be used on any digital pin. To declare an array, you must give it a name, DECLARING AN ARRAY: then either tell Arduino how many positions the array_name[array_size]; array. An array must contain all the same type of array will have or assign a list of values to the variables and be declared as such. To call one of the values in an array, simply type CALLING AN ARRAY: the name of the array and the index of the value. array_name[index_#]; Don’t forget the index starts at 0, not 1, so to call the first element, use array_name[0];. CODING CHALLENGES CHANGE THE TEMPO OF THE SONG: Experiment with the beatLength; variable to change the tempo of the song. MAKE YOUR OWN SONG: Try changing the notes to make a different song. Spaces “ ” can be used for rests in the song. 40 : circuit 2a TROUBLESHOOTING The song is too quiet or too loud Turn the potentiometer to adjust the volume. Try pressing the reset button on the RedBoard. If that No sound is playing doesn’t work, check your wiring of the buzzer. It’s easy to misalign a pin with a jumper wire or reverse the buzzer. You’ve completed Circuit 2A! Continue to circuit 2B to explore digital inputs and buttons. BUZZER D I G I TA L TRUMPET A B “ S I M O N S AY S ” G A M E C 41 : circuit 2a Circuit 2B: Digital Trumpet Learn about digital inputs and buttons as you build your own digital trumpet! Buttons are all around us, from the keys on your keyboard to the buttons on your remote control. YOU NEED POTENTIOMETER PIEZO BUZZER NEW COMPONENTS BUTTONS: Also known as momentary switches, buttons only remain in their ON state as long as they’re being actuated, or pressed. Most often momentary switches are 10 JUMPER WIRES 3 PUSH BUTTONS of as ON or OFF, TRUE or FALSE, HIGH or LOW. Almost all electronics rely on a base-2 number system to store and manipulate numbers. The heavy reliance electronics places on binary numbers means it’s important to know how the base-2 number system works. best used for intermittent user-input cases: reset DIGITAL INPUT: In circuit 1A, you button and keypad buttons. worked with digital outputs. Each of the These switches have a nice, tactile, “clicky” 14 digital pins can also be digital inputs. feedback when you press them. Digital inputs only care if something is in one of two states, 0 or 1. Digital inputs are Note that the different colors are just aesthetic. All of the buttons included great for determining if a button has been pressed or if a switch has been flipped. behave the same, no matter their color. PULL-UP RESISTORS: A pull-up NEW CONCEPTS BINARY NUMBER SYSTEM: Number resistor is a small circuit that holds the voltage HIGH (5V) on a pin until a button is pressed, pulling the voltage LOW (0V). The systems are the methods we use to most common place you will see a pull-up represent numbers. We’re most used to resistor is when working with buttons. A operating within the comfy confines of pull-up resistor keeps the button in one a base-10 number system, but there are state until it is pressed. The RedBoard has many others. The base-2 system, otherwise built-in pull-up resistors, but they can also known as binary, is common when be added to a circuit externally. This circuit dealing with computers and electronics. uses the internal pull-up resistors, covered Computers, at their lowest level, really only in more detail in the Code to Note section. have two ways to represent the state of anything: 1 or 0, which can also be thought 42 : circuit 2b HOOKUP GUIDE READY TO START HOOKING EVERYTHING UP? Check out the circuit diagram and hookup table below to see how everything is connected. b c d e f g h i ++ -– j 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 7-15V RESET 12 3.3V 13 13 5V 14 14 15 15 16 16 17 17 18 18 19 19 A2 20 20 A3 21 21 A4 22 22 A5 23 23 24 24 25 25 26 26 27 27 28 28 b c d e f g h i j A0 A1 7 ~6 ~5 4 ~3 2 TX 1 RX 0 ON 30 a VIN ISP 29 30 GND ANALOG IN 29 GND SCL SDA AREF GND 13 12 ~11 ~10 ~9 8 DIGITAL (PWM~) IOREF 11 12 START SOMETHING 10 11 13 TX RX 10 POWER ++ -– a 1 RESET ++ -– CONNECTED ++ -– BUTTONS ARE NOT POLARIZED, but they do merit a closer look. Each row of legs is connected internally. When the button is pressed, CONNECTED one row connects to the other, connecting all four pins. If the button’s legs don’t line up with the rows on the breadboard, rotate it 90 degrees. GND to JUMPER WIRES BUZZER PUSH BUTTONS POTENTIOMETER GND(-) D2 to J30 J28 to GND (-) H1(+) to D10 to E2 to F1 GND (-) E1 to D4 to J16 to J18 D3 to GND (-) J24 J22 to GND (-) F3 H3(-) D16/D18 to G16/18 B1 + B3 B2 + D22/24 to G22/24 D28/30 to G28/30 43 : circuit 2b Open the Arduino IDE Connect the RedBoard to a USB port on your computer. Open the Sketch: File > Examples > SIK_Guide_Code-V_4 > SIK_CIRCUIT_2B-DIGITAL TRUMPET   Select UPLOAD to program the sketch on the RedBoard. W H AT Y O U SHOULD SEE Different tones will play when you press different keys. Turning the potentiometer will adjust the volume. PROGRAM OVERVIEW Check to see if the first button is pressed. 1 A: If it is, play the frequency for c. B: If it isn’t, skip to the next else if statement. Check to see if the second button is pressed. 2 A: If it is, play the frequency for e. B: If it isn’t, skip to the next else if statement. Check to see if the third button is pressed. 3 A: If it is, play the frequency for g. B: If it isn’t, skip to the else statement. 4 If none of the if statements are true, turn the buzzer off. 44 : circuit 2b CODE TO NOTE To declare a standard input, use the line INTERNAL PULL-UP RESISTOR: pinMode(pin, INPUT );. If you would like to use one of the RedBoard’s built-in pull-up 20kΩ resistors, it would look like this: pinMode(pin, INPUT_ PULLUP); pinMode(pin, INPUT_PULLUP);. The advantage of external pull-ups is being able to choose a more exact value for the resistor. DIGITAL INPUT: Check to see if an input pin is reading HIGH digitalRead(pin); depending on the reading. (5V) or LOW (0V). Returns TRUE (1) or FALSE (0) This is another logical operator. The “is equal to” symbol == can be confusing. Two equals signs are the IS EQUAL TO: same as asking, “Are these two values equal to one if(digitalRead(pin) == LOW ) another?” Contrarily, one equals sign means assigning a particular value to a variable. Don’t forget to add the second equals sign if you are comparing two values. CODING CHALLENGES CHANGE THE KEY OF EACH BUTTON: Use the frequency table in the comment section at the end of the code to change the notes that each button plays. PLAY MORE THAN THREE NOTES WITH IF STATEMENTS: By using combinations of buttons, you can play up to seven notes of the scale. You can do this in a few ways. To get more practice with if statements, try adding seven if statements and using the Boolean AND && operator to represent all of the combinations of keys. PLAY MORE THAN THREE NOTES WITH BINARY MATH: You can use a clever math equation to play more than three notes with your three keys. By multiplying each key by a different number, then adding up all of these numbers, you can make a math equation that produces a different number for each combination of keys. 45 : circuit 2b TROUBLESHOOTING The buzzer is too loud or too quiet The RedBoard thinks one key is always pressed Turn the potentiometer to adjust the volume. Check your wiring. You may have GND and 5V backward if one or more buttons behave as though they’re pressed all the time. First, make sure that the wiring is correct. It is easy to misalign The buttons are a wire with a button leg. Second, make sure that you have not working declared your buttons as inputs and have enabled the internal pull-up resistors with INPUT_PULLUP. You’ve completed Circuit 2B! Continue to circuit 2C and learn how to build your own game using buttons and LEDs. BUZZER D I G I TA L TRUMPET A B 46 : circuit 2b “ S I M O N S AY S ” G A M E C pattern, which the player must remember 100k The “Simon Says” game uses LEDs to flash a 330 Circuit 2C: “Simon Says” Game and repeat using four buttons. This simple electronic game has been a classic since the late 1970s. Now you can build your own! 4 LEDS POTENTIOMETER PIEZO BUZZER 16 JUMPER WIRES 4 PUSH BUTTONS 4 330Ω NEW CONCEPTS FOR LOOPS: A for loop repeats a YOU NEED RESISTORS brackets, which prints the value of i to the Serial Monitor. section of code a set number of times. The MEASURING DURATIONS OF TIME loop works by using a counter (usually WITH MILLIS(): The RedBoard has a programmers use the letter “i” for this built-in clock that keeps accurate time. variable) that increases each loop until it You can use the millis() command to reaches a stop value. Here’s an example of see how many milliseconds have passed a simple for loop: since the RedBoard was last powered. By for (int i = 0; i < 5; i++){ Serial.print(i); } storing the time when an event happens The for loop takes three parameters in (and thus seconds) that have passed. This the brackets, separated by semicolons. The sketch uses this function to set a time limit first parameter is the start value. In this for repeating the pattern. case, integer i starts at 0. The second value is the stop condition. In this case, we stop the loop when i is no longer less than 5 (i < 5 is no longer true). The final parameter and then subtracting the current time, you can measure the number of milliseconds CUSTOM FUNCTIONS: This sketch uses several user-defined functions. These functions perform operations that are is an increment value. i++ is shorthand needed many times in the program (for for increase i by 1 each time, but you could example, reading which button is currently also increase i by different amounts. This pressed or turning all of the LEDs off). loop would repeat five times. Each time Functions are essential to make more it would run the code in between the complex programs readable and compact. 47 : circuit 2c HOOKUP GUIDE READY TO START HOOKING EVERYTHING UP? Check out the circuit diagram and hookup table below to see how everything is connected. a b c d e f g h i 1 2 2 3 4 3 5 6 6 100k 7 8 8 330 9 9 10k 13 100k 3.3V 13 5V GND 14 10k GND 15 330 16 100k 17 VIN 16 17 18 A0 18 A1 A3 21 A4 22 22 A5 23 23 21 10k 100k 24 ON A2 20 7 ~6 ~5 4 ~3 2 TX 1 RX 0 ISP 19 330 20 ANALOG IN 19 SCL SDA AREF GND 13 12 ~11 ~10 ~9 8 DIGITAL (PWM~) 15 24 25 25 26 ++ -– RESET 12 POWER 14 IOREF 11 START SOMETHING 12 10 13 TX RX 10 11 7-15V 4 10k 5 7 ++ -– j 1 RESET ++ -– 26 330 27 27 28 28 29 29 30 30 a b c d e f g h i BUZZER LEDS POTENTIOMETER PUSH BUTTONS 48 : circuit 2c GND(-) D10 to F1 D9 to D7 to J13 D6 to J18 D5 to D3 to J25 D2 to J30 E2 to J16 to GND(-) J10 to GND(-) H1(+) to H7+ to B1 + J22 to GND(-) D8 to D4 to GND(-) J28 to E1 to J12 J24 F3 GND(-) H3(-) H13+ to H8– B2 + H14– H19+ to H20– B3 G10/12 D16/18 to G16/18 D22/24 to G22/24 D28/30 to G28/30 J26 to J7 J19 D10/12 to J8 to 330Ω RESISTOR ++ -– j GND to JUMPER WIRES F L AT E D G E GND(-) GND(-) J14 to GND(-) J20 to GND(-) H25+ to H26– Open the Arduino IDE Connect the RedBoard to a USB port on your computer. Open the Sketch: File > Examples > SIK_Guide_Code-V_4 > SIK_CIRCUIT_2C-SIMON SAYS   Select UPLOAD to program the sketch on the RedBoard. W H AT Y O U SHOULD SEE The circuit will flash all of the LEDs and play a melody. After a few seconds, it will flash the first light in the pattern. If you repeat the pattern correctly by pressing the corresponding colored button, then the game will move to the next round and add another color to the pattern sequence. If you make a mistake, the loss melody will play. If you get to round 10, the win melody will play. Press any button to start a new game. PROGRAM OVERVIEW Check if a new game is starting. If it is, play the start sequence. Reset the counter that keeps track of 1 rounds, and randomly generate a sequence of numbers from 0 to 3 that controls which LEDs the user will have to remember. The game works in rounds that progress from 0 to 10. Each round the game will flash LEDs in a pattern, 2 and then the player has to recreate the pattern by pressing the button(s) that match the LED(s). In the first round, one LED will flash, and the player will have to press one button. In the eighth round, eight LEDs will flash, and the player will have to press eight buttons. 3 A loop is used to flash LEDs from the sequence until you have flashed the number of LEDs that matches the round number (1 for round 1, 2 for round 2, etc.). 49 : circuit 2c Start a timer, and wait for the player to press a button. The player has 1.5 seconds to press the correct button. 4 A: If the time limit runs out before a button is pressed, the player loses. B: If the player presses the wrong button, the player loses. C: If the player presses the right button, move on to the next number in the sequence. D: Repeat this process until the player has lost or correctly repeated the sequence for this round. 5 If the player repeats the entire sequence for that round, increase the round number by one (this will add 6 Keep incrementing the round until the player loses or finishes 10 rounds. If the player finishes 10 rounds, one extra item to the end of the pattern). Then go back to step 3. play the winning sequence. CODE TO NOTE ELAPSED TIME: millis(); The millis() function returns the number of milliseconds that have passed since the RedBoard was last turned on. The name for these variables comes from Boolean logic. BOOLEAN VARIABLES: boolean variable_ name; The boolean variable type only has two values: 1 or 0 (also known as HIGH or LOW, ON or OFF, TRUE or FALSE). Using Boolean variables helps save memory on your microcontroller if you only need to know if something is true or false. Space in your microcontroller’s memory is reserved when a variable is declared. How much memory is reserved depends on the type of variable. STORING PIN NUMBERS IN ARRAYS: int led[ ] = {3,5,7,9}; Sometimes you will want to cycle through all of the LEDs or buttons connected to a project. You can do this by storing a sequence of pin numbers in an array. The advantage of having pins in an array instead of a sequence of variables is that you can use a loop to easily cycle through each pin. FUNCTIONS TO NOTE flashLED(#LED to flash); 50 : circuit 2c This turns one of the four LEDs on and plays the tone associated with it. 0 = Red, 1 = Yellow, 2 = Green, 3 = Blue. FUNCTIONS TO NOTE allLEDoff(); buttonCheck(); Turns all four LEDs off. Uses digitalRead() to check which button is pressed. Returns 0, 1, 2 or 3 if one of the buttons is pressed. Returns 4 if no button is pressed. Flashes the LEDs and plays tones in a sequence. Resets the round startSequence(); counter and generates a new random sequence for the user to remember. winSequence(); loseSequence(); Plays a sequence of tones, turns all of the LEDs on, and then waits for the player to press a button. If a button is pressed, restarts the game. Plays a sequence of tones, turns all of the LEDs on, and then waits for the player to press a button. If a button is pressed, restarts the game. CODING CHALLENGES CHANGE THE DIFFICULTY OF THE GAME: Change the difficulty of the game by changing how fast the player has to press each button or by increasing or decreasing the number of rounds needed to win. Note that if you increase the number of rounds to be larger than 16, you will need to change the size of the array (it is set at the top of the code in a line that looks like this: int buttonSequence[16]; ). CHANGE THE SOUND EFFECTS: Try changing the sequence of notes that plays when you start, win or lose the game. 2-PLAYER MODE: Try changing the code so that two players can play head-to-head. 51 : circuit 2c TROUBLESHOOTING One of the LEDs isn’t lighting up The buzzer is too loud or too quiet Make sure your LED is oriented in the right direction. If the LED still doesn’t work, try wiggling the resistor and the wires that connect to the LED. Turn the potentiometer to adjust the volume. Carefully check your wiring for each button. One leg of the One of the buttons isn’t button should connect to a pin on the RedBoard; the other leg working should connect to the ground rail on the breadboard. Make sure they are declared correctly. None of the buttons or LEDs are working Make sure you don’t have 5V and GND mixed up. Double check that you have a GND connection from the RedBoard to the GND rail on the breadboard. Jumper wires unfortunately can go “bad” from getting bent too much. The copper wire inside can break, leaving an open Still not working? connection in your circuit. If you are certain that your circuit is wired correctly and that your code is error-free and uploaded, but you are still encountering issues, try replacing one or more of the jumper wires for the component that is not working. You’ve completed Project 2! Continue to Project 3 to explore using servos and sensors. BUZZER D I G I TA L TRUMPET A B 52 : circuit 2c “ S I M O N S AY S ” G A M E C SERVO MOTORS D I S TA N C E S E N S O R A B MOTION ALARM C PROJECT 3 Tired of your cat walking all over the kitchen counter? How about the dog getting into the garbage? Need a way to stop your younger sibling from sneaking into your bedroom? Learn how to protect against all of these annoyances as you build a multipurpose motion alarm. The alarm detects distance and motion using an ultrasonic distance sensor, and creates motion using a servo motor. NEW COMPONENTS INTRODUCED IN THIS PROJECT •   S E RV O M OTO R •   U L T R A S O N I C D I S TA N C E S E N S O R NEW CONCEPTS INTRODUCED IN THIS PROJECT • PWM DUTY CYCLE • ARDUINO LIBRARIES • OBJECTS AND METHODS •   D I G I TA L S E N S O R S •   D ATA S H E E T S • SERVO MECHANISMS YOU WILL LEARN •   H OW TO CO N T R O L A S E RV O M OTO R •   H O W T O U S E A N U L T R A S O N I C D I S TA N C E S E N S O R •   H OW TO M OV E O BJ E C T S U S I N G SERVO MECHANISMS 53 : circuit 3a Circuit 3A: Servo Motors In this circuit, you will learn how to wire a servo and control it with code. Servo motors can be told to move to a specific position and stay there. Low-cost servo motors were originally used to steer RC airplanes and cars, but they have become popular for any project where precise movement is needed. YOU NEED POTENTIOMETER SERVO 8 JUMPER WIRES SCISSORS (NOT INCLUDED) NEW COMPONENTS SERVO MOTORS: Regular DC motors have two wires. When you hook the wires up to power, the motor spins around and around. Servo motors, on the other hand, have three wires: one for power, one for ground and one for signal. When you send the right signal through the signal wire, the servo will move to a specific angle and stay there. Common servos rotate over a range of about 0° to 180°. The signal that is sent is ATTACHING YOUR SERVO: A strip of adhesive Dual LockTM fastening tape is included in your kit. Cut two pieces of it to temporarily affix your servo to your baseplate. a PWM signal, the same used to control the NEW CONCEPTS RGB LED in Project 1. DUTY CYCLE: Pulse-Width Modulation Included with your servo motor you will find a variety of motor mounts that connect to the shaft of your servo. You may choose to attach any mount you wish for this circuit. It will serve as a visual aid, making it easier to see the servo spin. The mounts will also be used at the end of this project. 54 : circuit 3a (PWM) is a great way to generate servo control signals. The length of time a PWM signal is on is referred to as the duty cycle. Duty cycle is measured in percentage. Thus a duty cycle of 50 percent means the signal is on 50 percent of the time. The variation in the duty cycle is what tells the servo which position to go to in its rotation. ARDUINO LIBRARIES: Writing code creating a servo object, like this: that sends precise PWM signals to the Servo myServo; servo would be time consuming and would require a lot more knowledge about the servo. Luckily, the Arduino IDE has hundreds of built-in and user-submitted containers of code called libraries. One of Objects look a lot like variables, but they can do much more. Objects can store values, and they can have their own functions, which are called methods. the built-in libraries, the Servo Library, The most used method that a servo object allows us to control a servo with just a few has is .write(): lines of code! To use one of the built-in Arduino libraries, all you have to do is “include” a link to its header file. A header file is a smaller code file that contains definitions for all the functions used in that library. By adding myServo.write(90); The write method takes one parameter, a number from 0 to 180, and moves the servo arm to the specified position (in this case, degree 90). a link to the header file in your code, you Why would we want to go to the trouble of are enabling your code to use all of those making an object and a method instead of library functions. To use the Servo Library, just sending a servo control signal directly you would add the following line to the top over a pin? First, the servo object does the of your sketch. work of translating our desired position #include into a signal the servo can read. Second, OBJECTS AND METHODS: To use the and control more than one servo. using objects makes it easy for us to add Servo Library, you will have to start by SERVO BASICS: Servo motor connectors are polarized, but there is no place to attach them directly. Instead, connect three jumper wires to the female 3-pin header on the servo. This will make it so you can connect the servo to the breadboard. The servo wires are color coded to make hookup simple. GND CONTROL 5V+ 55 : circuit 3a HOOKUP GUIDE READY TO START HOOKING EVERYTHING UP? Check out the circuit diagram and hookup table below to see how everything is connected. b c d e f g h i ++ -– j 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 7-15V RESET 12 3.3V 13 13 5V 14 14 15 15 16 16 17 17 18 18 19 19 A2 20 20 A3 21 21 A4 22 22 A5 23 23 24 24 25 25 26 26 27 27 28 28 b c d e f g h i POTENTIOMETER SERVO LEADS 56 : circuit 3a A1 A0 to E1 to 7 ~6 ~5 4 ~3 2 TX 1 RX 0 ++ -– REDBOARD CONNECTION CONNECTION TYPES JUMPER WIRES j A0 ON 30 a VIN ISP 29 30 GND ANALOG IN 29 GND SCL SDA AREF GND 13 12 ~11 ~10 ~9 8 DIGITAL (PWM~) IOREF 11 12 START SOMETHING 10 11 13 TX RX 10 POWER ++ -– a 1 RESET ++ -– E2 5V to 5V (+) B1 + B2+ BREADBOARD CONNECTION 5V(+) E3 to GND to GND(–) GND (-) B3 WHITE WIRE to D9 RED WIRE to 5V(+) BLACK WIRE to GND(–) Open the Arduino IDE Connect the RedBoard to a USB port on your computer. Open the Sketch: File > Examples >SIK_Guide_Code-V_4 > SIK_CIRCUIT_3A-SERVO   Select UPLOAD to program the sketch on the RedBoard. W H AT Y O U SHOULD SEE Turning the potentiometer will cause the servo arm to turn. The servo will mimic the movement of the potentiometer, twisting in the same clockwise or counterclockwise direction. If you’ve attached a servo mount to the arm as shown, this movement will be easier to see. PROGRAM OVERVIEW 1 Read the value of the potentiometer. 2 Convert the potentiometer value (0–1023) to an angle (20–160). 3 Tell the servo to go to this angle. CODE TO NOTE The #include command adds a library to your INCLUDING LIBRARIES: Arduino program. After you include a library, #include you can use the commands in the library in your program. This line adds the built-in Servo Library. The Servo command creates a new servo object CREATING SERVO OBJECTS: and assigns a name to it, myServo in this case. If Servo myServo; you make more than one servo object, you will need to give them different names. 57 : circuit 3a CODE TO NOTE The .attach(); method tells the servo object to which pin the signal wire is SERVO ATTACH: attached. It will send position signals myServo.attach(9); to this pin. In this sketch, pin 9 is used. Remember to only use digital pins that are capable of PWM. As shown in previous circuits, the analog pin values on your microcontroller vary from 0 to 1023. But what if we want those values to control a servo motor that only RANGE MAPPING: accepts a value from 0 to 180? The map() map(potPosition,0,1023,20,160); function takes a range of values and outputs a different range that can contain more or fewer values than the original. In this case, we are taking the range 0–1023 and mapping it to the range 20–160. The .write(); method moves the servo SERVO WRITE: myServo.write(90); to a specified angle. In this example, the servo is being told to go to angle 90. CODING CHALLENGES REVERSE THE SERVO DIRECTION: Try making the servo move in the opposite direction of the potentiometer. CHANGE THE RANGE: Try altering the map function so that moving the potentiometer a lot only moves the servo a little or vice versa. SWAP IN A DIFFERENT SENSOR: Try swapping a light sensor in for the potentiometer. Then you can make a dial that reads how much light is present! 58 : circuit 3a TROUBLESHOOTING The servo doesn’t move Check the wiring on your servo. Make sure the red wire on the servo cord is connected to 5V, the black wire is connected to GND and the white signal wire is connected to digital pin 9. Although these servos are supposed to move from 0 to 180 The servo is twitching degrees, sometimes sending them to the extremes of their range causes them to twitch (the servo is trying to move farther than it can). Make sure you aren’t telling the servo to move outside of the 20–160 degree range. You’ve completed Circuit 3A! Continue to circuit 3B to learn about using distance sensors. SERVO MOTORS A D I S TA N C E S E N S O R B MOTION ALARM C 59 : circuit 3a Circuit 3B: Distance Sensor Distance sensors are amazing tools with all kinds of uses. They can sense the presence of an object, they can be used 10k 100k 330 in experiments to calculate speed and acceleration, and they can be used in robotics to avoid obstacles. This circuit will walk you through the basics of using an ultrasonic distance sensor, which measures distance using sound waves! TJP16 527BH 2 165 2 VCC DISTANCE SENSOR T Trig RESISTORS Echo 3 330Ω RGB LED GND YOU NEED 10 JUMPER WIRES R NEW COMPONENTS the datasheet for the distance sensor. In ULTRASONIC DISTANCE SENSOR: Distance sensors work by sending pulses of it, you can find the equation the program needs to interpret the distance. View the datasheet at http://sfe.io/HCSR04. light or sound out from a transmitter, then timing how long it takes for the signals to ELSE IF STATEMENTS: In the night- bounce off an object and return to a receiver light circuit, you used an if/else statement (just like sonar). Some sensors use infrared to run one set of code when a logic light, some use lasers, and some, like the statement was true, and another when HC-SR04 included in your kit, use ultrasonic it was false. What if you wanted to have sound (sound so high-pitched that you can’t more than two options? Else if statements hear it). let you run as many logical tests as you TJP16527BH2 want in one statement. For example, in the code for this circuit, there is an if statement that flows like this: 1.  If the distance is less than 10, make GND Echo Trig T VCC 1652 R the RGB LED red. 2.  Else if the distance is more than NEW CONCEPTS DATASHEETS: When working with electronics, datasheets are your best 10 but less than 20, make the RGB LED yellow. 3.  Else make the RGB LED green. friend. Datasheets contain all the relevant To have four or five colors for different information needed for a part. In this distances, add more else if statements. circuit, we are calculating distance based on the time it takes sound waves to be transmitted, bounce off an object and then be received. But, how can we tell distance from that information? The answer lies in 60 : circuit 3b Else if statements are different from nested if statements in that only one of the statements above can be true, whereas multiple nested if statements could be true. HOOKUP GUIDE READY TO START HOOKING EVERYTHING UP? Check out the circuit diagram and hookup table below to see how everything is connected. T a b c e f g h i j 1 2 2 VCC 3 4 Trig 4 5 Echo 6 GND 1652 3 ++ -– 7-15V 5 6 7 T J P 1 6 5 2 7 B H 2 7 8 9 8 9 13 5V 14 14 15 15 16 16 17 17 18 18 19 19 A2 20 20 A3 21 21 A4 22 22 23 23 24 24 25 25 26 26 27 27 28 28 29 29 j ++ -– POWER (5V) TRIGGER PULSE INPUT: ECHO PULSE OUTPUT: GROUND (0V) REDBOARD CONNECTION CONNECTION TYPES 330Ω RESISTORS (ORANGE, ORANGE, BROWN) D I S TA N C E S E N S O R 5V GND to GND (-) D6 to J22 D11 to E4 E6 to GND(–) A25(RED) + E22 to F22 A3(VCC) + E24 to A24(GND) + E23 to A4(TRIG) + Trig Echo GND BREADBOARD CONNECTION D3 to D12 to R RGB LED 5V to VCC 1652 F L AT S I D E JUMPER WIRES when connecting your circuit. 10k i polarized. Take note of the pin labels 10k h POLARITY: The distance sensor is 100k g A5 7 ~6 ~5 4 ~3 2 TX 1 RX 0 100k 10k f 330 e 330 100k d A1 ON c A0 ISP b VIN ANALOG IN 30 a GND 330 R 30 GND SCL SDA AREF GND 13 12 ~11 ~10 ~9 8 DIGITAL (PWM~) 3.3V 13 T RESET 12 START SOMETHING IOREF 11 12 POWER 10 11 13 TX RX 10 ++ -– d 1 RESET ++ -– J25 E5 D5 to E3 to J23 5V (+) GND(–) A23(GREEN) + F23 A5(ECHO) + E25 to A22(BLUE) F25 A6(GND) 61 : circuit 3b Open the Arduino IDE Connect the RedBoard to a USB port on your computer. Open the Sketch: File > Examples > SIK_Guide_Code-V_4 > CIRCUIT_3B-DISTANCE SENSOR   Select UPLOAD to program the sketch on the RedBoard. W H AT Y O U SHOULD SEE Move your hand or a large, flat object closer and farther away from the distance sensor. As the object approaches, the light will change from green to yellow to red. Open the Arduino Serial Monitor to see the distance being read from the sensor. PROGRAM OVERVIEW Check what distance the sensor is reading. 1: If the distance is less than 10 inches, make the RGB LED red. 2: If the distance is between 10 and 20 inches, make the RGB LED yellow. 3: If the distance value is not equal to the fist two conditions, make the RGB LED green. TROUBLESHOOTING WARNING: HVAC systems in offices and schools have been known to interfere with the performance of the ultrasonic distance sensor. If you are experiencing sporadic behavior from your circuit, check your surroundings. If there are numerous air ducts in the room you are using, try moving to a different room that does not have ducts. The airflow from these ducts can interfere with the waves sent from the sensor, creating noise and resulting in bad readings. 62 : circuit 3b CODE TO NOTE The float variable, short for floating-point number, is similar to an integer except it can FLOAT VARIABLES: float echoTime; represent numbers that contain a decimal point. Floats are good for representing values that need to be more precise than an integer. Floats allow us to measure precise distances such as 9.33 inches instead of just 9 inches. ELSE IF STATEMENT: if(logic statement){ //run if first is true } else if(second logic statement){ //run if second is true } else{ //run if neither is true } Else if statements let you combine more than one logic statement. Arduino will test each logic statement in order; if one is true it will run the code in that section and then skip all of the other sections of code in the remaining statements. This function tells the distance sensor to send out an ultrasonic wave form, measures the time it takes USER-DEFINED FUNCTION: to bounce back to the sensor, and then calculates getDistance(); the distance based on the speed of sound. This calculation is based off information found in the distance sensor’s datasheet. CODING CHALLENGES CHANGE THE LIMITS OF THE DISTANCE SENSOR: Try editing the values in the logic statements so that the RGB LED changes color at different distances. CHANGE THE UNITS OF THE DISTANCE SENSOR: Try editing the code so that the distance sensor outputs a different unit of length, such as centimeters or feet. ADD A FOURTH COLOR: Try adding another else if statement so that there are four different colors instead of three. 63 : circuit 3b TROUBLESHOOTING The RGB LED colors aren’t working or a color is missing Check the connection for the wire and resistor connected to each leg of the LED. Ensure the RGB LED is inserted in the correct orientation. Open up the Serial Monitor on your computer. You The distance sensor doesn’t should see a stream of distances being printed in the seem to work monitor. If they are all reading 0 or jumping around, then check the wiring on your sensor. Ultrasonic noise pollution will interfere with your distance sensor readings. If you aim two distance The distance sensor still doesn’t work sensors at each other, they will confuse each other. Some air-conditioning systems may also emit noises in the ultrasonic range. Try pointing your sensor away from the other distance sensors or changing to a different location. You’ve completed Circuit 3B! Continue to circuit 3C to explore building mechanisms that interact with your circuits. SERVO MOTORS A 64 : circuit 3b D I S TA N C E S E N S O R B MOTION ALARM C Circuit 3C: Motion Alarm Time to take your distance sensor project to the next level. Let’s imagine you want to stop your cat from prowling around your countertop. This circuit uses light, sound and motion to scare away your cat when it is detected by the distance sensor. Using a servo motor, you can add a moving pop-up to animate your alarm. 3 330Ω RGB LED RESISTORS PIEZO BUZZER 15 JUMPER WIRES YOU NEED SERVO TJP16 T VCC (NOT INCLUDED) 527BH 2 DISTANCE 165 SENSOR 2 Trig PAPER SCISSORS Echo MARKERS/PEN GND TAPE PAPER CLIP NEEDLE-NOSE PLIERS 330 100k 10k R NEW CONCEPTS ASSEMBLY MECHANISMS: This circuit gets really If you have opted for the extra materials, fun when you start to use your servo to use the following instructions to create the animate the world around you. To do moving pop-up for your motion alarm. this, you’ll need to connect your servo to some physical mechanisms. Tape and hot glue are easy ways to connect things to your servo. You can also loop a paper clip through the small holes in the servo arm to serve as a linkage. 1. Attach the servo mount of your choice. The motor mounts also come with screws to secure the mount to the motor. Once you are finished with this circuit, you may choose to add a screw to make for a more robust mechanism. It is recommended you upload your code and test the mechanism before screwing it down. 2. Use needle-nose pliers to bend the paper clip straight. Bend about 1 inch of the paper clip 90 degrees. Then bend the other end so it’s about 1/8 inch long. Repeat this bend once more, making a hook shape. You should now have a linkage rod that looks something like this: Linkage rods are found on many RC airplanes, which use servo motors to control the ailerons, elevators and rudder. 65 : circuit 3c 3. Attach the hook end of the linkage rod to the end hole on your servo mount. The motor should be reattached to the baseplate with Dual Lock. 4. Cut out the pop-up image of your choice. We chose this public domain menacing cat image (http://sfe.io/cat). The image you choose should be about 2.5 inches x 2.5 inches and can be drawn or printed. Leave a rectangular strip of paper under the image that is about 2 inches long. 5. Fold along the bottom of the image. Tape the bottom of the pop-up to the underside of the breadboard baseplate on the same side to which the servo is connected. 6. Tape the free end of the rod to the back of your pop-up image, near the center. 7. Once you have the rest of the circuit built and the code uploaded, you can fine-tune your moving pop-up and make any necessary adjustments. Remember to wait until these adjustments have been made before you screw the servo mount onto the motor. 66 : circuit 3c HOOKUP GUIDE READY TO START HOOKING EVERYTHING UP? Check out the circuit diagram and hookup table below to see how everything is connected. T a b d e f g h i ++ -– j 2 3VCC 3 4Trig 4 1652 1 2 5Echo 7-15V 5 6 7 7 T J P 1 6 5 2 7 B H 2 6GND 8 9 11 9 10 IOREF 5V 14 14 15 15 16 16 17 17 18 18 19 19 A2 20 20 A3 21 21 A4 22 22 A5 23 23 24 24 25 25 26 26 27 27 28 28 j ++ -– 10k i 10k h 100k g 100k 10k f 330 e 7 ~6 ~5 4 ~3 2 TX 1 RX 0 330 100k d A1 330 c A0 ON 30 b VIN ISP 29 30 GND ANALOG IN 29 GND DIGITAL (PWM~) 13 START SOMETHING 3.3V 13 POWER RESET 12 R 11 12 a SCL SDA AREF GND 13 12 ~11 ~10 ~9 8 8 13 TX RX 10 ++ -– c 1 RESET ++ -– F L AT S I D E JUMPER WIRES RGB LED 330Ω RESISTORS (ORANGE, ORANGE, BROWN) D I S TA N C E S E N S O R PIEZO BUZZER SERVO LEADS 5V to 5V GND to GND (-) D6 to J22 D11 to E4 E3 to 5V (+) A25(RED) + E22 to A24(GND)+ F22 A3(VCC)+ F14 (+)+ E6 to E23 to A4(TRIG)+ D3 to D12 to GND(–) A5(ECHO)+ E5 E24 to A23(GREEN)+ F23 J25 E25 to D5 to D10 to GND(–) J23 J14 J16 to GND(–) A22(BLUE) F25 A6(GND) F16(-) WHITE WIRE to D9 RED WIRE to 5V(+) BLACK WIRE to GND(–) 67 : circuit 3c Open the Arduino IDE Connect the RedBoard to a USB port on your computer.   Open the Sketch: File > Examples > SIK_Guide_Code-V_4 > SIK_CIRCUIT_3C-MOTION ALARM   Select Upload to program the sketch on the RedBoard. W H AT Y O U SHOULD SEE The RGB LED will behave as in your last circuit. It will be green when objects are far, yellow when they are midrange and red when they are close. When an object is close, the buzzer will also beep, and the servo will rotate back and forth. If you decided to attach a pop-up, it will move back and forth. PROGRAM OVERVIEW Check what distance the sensor is reading. 1: If the distance is less than 10 inches, make the RGB LED red. Then make the servo rotate back and forth and make the buzzer beep. 2: If the distance is between 10 and 20 inches, make the RGB LED yellow. 3: If the distance value is not equal to the fist two conditions, make the RGB LED green. CODE TO NOTE CONSTANTS: const int trigPin = 11; 68 : circuit 3c Constants are variables that have been marked as “read-only” and cannot have their value changed as the program progresses. Constants are great for declaring pin number variables that will not change throughout the program. CODE TO NOTE In circuit 2A, you made songs using a buzzer and the tone() function, but you gave the function three parameters: a pin NO TONE number, a frequency and a duration. You can leave out the third FUNCTION: noTone(pin_number); parameter, and the tone will play until you change it or turn it off. noTone() turns off a pin that has been activated with the tone() command. CODING CHALLENGES CHANGE THE SERVO BEHAVIOR: Try changing the way your servo behaves when the distance sensor is triggered. CHANGE THE ALARM SETTINGS: Try altering the code so the alarm goes off from much farther or closer distances. ADD A SECOND MECHANISM: Time to use your imagination! Try your hand at making different objects move with your servo motor. Don’t have a cat? Make an interactive pop-up story, room alarm, treat dispenser or automatic fish feeder. TROUBLESHOOTING The RGB LED colors aren’t Check the connection for the wire and resistor connected to working or a color is each leg of the LED. Ensure the RGB LED is inserted in the missing correct orientation. Open up the Serial Monitor on your computer. You should The distance sensor see a stream of distances being printed in the monitor. If doesn’t seem to work they are all reading 0 or jumping around, check the wiring on your sensor. Ultrasonic noise pollution will interfere with your distance sensor readings. If you aim two distance The distance sensor still doesn’t work sensors at each other, they will confuse each other. Some air-conditioning systems may also emit noises in the ultrasonic range. Try pointing your sensor away from the other distance sensors or moving to a different location. 69 : circuit 3c TROUBLESHOOTING Make sure all of your servo wires are connected. Be sure that the black wire is connected to the negative The servo doesn’t work rail and the red wire is connected to the positive rail. Make sure you are using a digital pin that is capable of PWM. The two lines of code that pass angles to the servo The pop-up is moving too much motor are myservo.write(45); and myservo. or not enough write(135);. Try changing these angle values to fine-tune your mechanism. You’ve completed Circuit 3C! Continue to Project 4 to learn how to use an LCD in your circuits. SERVO MOTORS A 70 : circuit 3c D I S TA N C E SENSOR B MOTION ALARM C LCD “HELLO, WORLD!” T E M P E R AT U R E S E N S O R A “DIY WHO AM I?” GAME B C PROJECT 4 Printing data to the Arduino Serial Monitor is a great way to see data from the RedBoard. But, what if you want to make your project mobile and see sensor values away from your computer? This project will show you how to do exactly that. You’ll learn about Liquid Crystal Displays (LCDs) and how to print things like sensor data and strings of words to the display. NEW COMPONENTS INTRODUCED IN THIS PROJECT •   L I Q U I D C R Y S TA L D I S P L A Y ( L C D ) •   T M P 3 6 D I G I TA L T E M P E R AT U R E SENSOR •   4 X A A B AT T E R Y H O L D E R NEW CONCEPTS INTRODUCED IN THIS PROJECT • CONTRAST • PIXELS • ALGORITHMS •   B U T TO N D E B O U N C E • STRINGS • POINTERS YOU WILL LEARN •   H OW TO P R I N T S I M P L E M E S SAG E S TO A N L C D •   H O W T O U S E A T E M P E R AT U R E SENSOR •   H O W T O P R I N T S E N S O R D ATA T O AN LCD •   H OW TO M A K E A N I N T E R AC T I V E G A M E T H AT I N C O R P O R AT E S T H E LCD 71 : circuit 4a Circuit 4A: LCD “Hello, World!” Printing “Hello, world!” is usually the first thing that programming tutorials will have you do in a new language. This guide starts by blinking an LED, but now we’re going to print out real text using a Liquid Crystal Display (LCD). YOU NEED LCD DISPLAY POTENTIOMETER NEW COMPONENTS CHARACTER LIQUID CRYSTAL DISPLAY (LCD): Designed to show a grid of letters, numbers and other special characters, LCDs are great for printing data and showing values. When current is applied to this special kind of crystal, it turns opaque. This is used in a lot of calculators, watches and simple displays. Adding an LCD to your project will make it 16 JUMPER WIRES a potentiometer, the contrast can be adjusted. As you rotate the knob on the potentiometer, you should notice that the screen will get brighter or darker and that the characters become more visible or less visible. The contrast of LCDs is highly dependent on factors such as temperature and the voltage used to power them. Thus, external contrast knobs are needed for displays that cannot automatically account for temperature and voltage changes. super portable and allow you to integrate up to 32 characters (16x2) of information. PIXELS: If you look closely at the characters on the LCD, you will notice that they are actually made up of lots of little squares. These little squares are called pixels. The size of displays is often represented in pixels. Pixels make up character space, which is the number of pixels in which a character can exist. NEW CONCEPTS CONTRAST: Pin 3 on the LCD controls the contrast and brightness of the LCD. Using a simple voltage divider with 72 : circuit 4a Here is a capital letter B as created in pixels. The character space in this example is 6 pixels x 8 pixels. HOOKUP GUIDE READY TO START HOOKING EVERYTHING UP? Check out the circuit diagram and hookup table below to see how everything is connected. b c d e f g h i ++ -– j 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 7-15V RESET 12 3.3V 13 13 5V 14 14 15 15 16 16 17 17 18 18 19 19 A2 20 20 A3 21 21 A4 22 22 A5 23 23 24 24 25 25 26 26 27 27 28 28 29 29 30 30 d e 5V to JUMPER WIRES L C D D I S P L AY POTENTIOMETER f g h i 5V j A0 A1 ON c VIN ISP b GND ANALOG IN a GND SCL SDA AREF GND 13 12 ~11 ~10 ~9 8 DIGITAL (PWM~) IOREF 11 12 START SOMETHING 10 11 13 TX RX 10 POWER ++ -– a 1 RESET ++ -– 7 ~6 ~5 4 ~3 2 TX 1 RX 0 KNOW YOUR LCD PINS 1 Ground 2 VDD(5V) 3 Pin3 Contrast adjust (0–5V) 4 Register Select 5 Read/Write Select 6 Enable 7 Data lines d0 (not used) 8 Data lines d1 (not used) 9 Data lines d2 (not used) 10 Data lines d3 (not used) 11 Data lines d4 (4-bit data transfer) 12 Data lines d5 (4-bit data transfer) 13 Data lines d6 (4-bit data transfer) 14 Data lines d7 (4-bit data transfer) 15 Backlight power (5V) 16 Backlight Ground (GND) ++ -– GND to GND (-) D10 to E26 D11 to E25 E30 to GND (-) E29 to E15 to GND (-) E9 to 5V(+) E17 D8 to D12 to E28 E20 E19 to E8 to D9 to E27 D13 to E18 GND (-) GND (-) E16 to E10 to 5V(+) 5V(+) A15-A30 (pin 1 on A15) A8 + A9 + A10 73 : circuit 4a Open the Arduino IDE Connect the RedBoard to a USB port on your computer. Open the Sketch: File > Examples > SIK_Guide_Code-V_4 > CIRCUIT_4A-LCD HELLO WORLD   Select UPLOAD to program the sketch on the RedBoard. W H AT Y O U SHOULD SEE The LCD screen will show “Hello, world!” and on the row below a counter will count every second that passes. Adjusting the potentiometer will change the contrast on the LCD screen. PROGRAM OVERVIEW 1 Import the LCD library. 2 Make an LCD object called “lcd” that will be controlled using pins 8, 9, 10, 11, 12 and 13. 3 “Begin” the LCD. This sets the dimensions of the LCD that you are working with (16 x 2). It needs to be called before any other commands from the LCD library are used. 4 Clear the display. 5 Set the cursor to the top left corner lcd.setCursor(0,0); then print “Hello, world!" 6 Move the cursor to the first space of the lower line lcd.setCursor(0,1); then print the number of seconds that have passed since the RedBoard was last reset. 74 : circuit 4a CODE TO NOTE LCD LIBRARY: Includes the LiquidCrystal library in your #include program. As with servos, you need to create an LCD LCD LIBRARY INSTANCE: object and give it a name (you can make LiquidCrystal LCD_name(RS_pin, enable_pin, d4, d5, d6, d7); more than one). The numbers in the brackets are pins on the RedBoard that connect to specific pins on the LCD. This line initializes the LCD object and tells LCD BEGIN: the program the LCD’s dimensions. In this lcd.begin(16, 2); case it is 2 rows of 16 characters each. LCD CLEAR: This method clears all the pixels on the lcd.clear(); display. Moves the cursor to a point on the 16x2 grid LCD CURSOR: of characters. Text that you write to the LCD lcd.setCursor(0,0); will start from the cursor. This line is starting back at position (0,0). LCD PRINT: Prints a string of characters to the LCD lcd.print(“Hello, world!”); starting at the cursor position. CODING CHALLENGES CHANGE THE MESSAGE: Try changing the code to display another message. SHOW HOURS, MINUTES AND SECONDS: Try adding some code so that the display shows the hours, minutes and seconds that have passed since the RedBoard was last reset. COUNT BUTTON PRESSES: By adding a button to the circuit, you can count the number of times the button was pressed or have the button change what displays. 75 : circuit 4a TROUBLESHOOTING Adjust the contrast by twisting the potentiometer. Try both The screen is blank or directions until you see characters display. Do not twist flickering the potentiometer past its stopping points. Also, check the potentiometer, and make sure it's wired correctly. Not working at all Double check the circuit’s wiring. There are a lot of wires in this circuit, and it’s easy to mix up one or two. If you see 16 rectangles (like “ ”) on the first row, it may be due to the jumper wires being loose on the breadboard. This is Rectangles in first row normal and can happen with other LCDs wired in parallel with a microcontroller. Make sure that the wires are fully inserted into the breadboard, then try pressing the reset button and adjusting the contrast using the potentiometer. Jumper wires unfortunately can go “bad” from getting bent too much. The copper wire inside can break, leaving an open Still not working? connection in your circuit. If you’re certain that your circuit is wired correctly and that your code is error-free and uploaded but you are still encountering issues, try replacing one or more of the jumper wires for the component that is not working. You’ve completed Circuit 4A! Continue to circuit 4B to learn about using temperature sensors. LCD “HELLO, WORLD” A 76 : circuit 4a T E M P E R AT U R E S E N S O R B “DIY WHO AM I” GAME C Circuit 4B: Temperature Sensor Want to create a DIY environmental monitor or weather station? You can use a small, low-cost sensor like the TMP36 to make devices that track and respond to temperature. In this activity you will also use the LCD screen to display sensor readings, a common use for LCDs in electronics projects. TMP LCD DISPLAY POTENTIOMETER TEMPERATURE SENSOR NEW COMPONENTS TMP36 TEMPERATURE SENSOR: This temperature sensor has three legs. One connects to 5V, one to ground, and the voltage output from the third leg varies 19 JUMPER WIRES YOU NEED voltage = analogRead(A0) * 0.004882814; The number we are multiplying by comes from dividing 5V by the number of samples the analog pin can read (1024), so we get: 5 / 1024 = 0.004882814. proportionally to changes in temperature. By doing some simple math with this The second formula takes that 0–5V value voltage, we can measure temperature in and calculates degrees Celsius: degrees Celsius or Fahrenheit. degreesC = (voltage - 0.5) * 100.0; TMP The reason 0.5V is subtracted from the calculated voltage is because there is a 0.5V offset, mentioned on page 8 of the TMP36 NEW CONCEPTS ALGORITHMS: An algorithm is a process used in order to achieve a desired result. datasheet found here: http://sfe.io/TMP36. It’s then multiplied by 100 to get a value that matches temperature. Often, the information needed to create The last formula takes the Celsius an algorithm lives in the part’s datasheet. temperature and converts it to a This sketch uses a few formulas to turn Fahrenheit temperature using the standard a voltage value into a temperature conversion formula: value, making them all part of the larger degreesF = degreesC * (9.0/5.0) + 32.0; temperature-retrieving algorithm. The first formula takes the voltage read on analog Together, these three formulas make up the pin 0 and multiplies it to get a voltage value algorithm that converts voltage to degrees from 0V–5V: Fahrenheit. 77 : circuit 4b HOOKUP GUIDE READY TO START HOOKING EVERYTHING UP? Check out the circuit diagram and hookup table below to see how everything is connected. TMP b c d e f g h i j 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 ++ -– 7-15V RESET 12 3.3V 13 13 5V 14 14 15 15 16 16 17 17 18 18 19 19 A2 20 20 A3 21 21 A4 22 22 A5 23 23 24 24 25 25 26 26 27 27 28 28 b c d e f g h i j A0 A1 ON 30 a VIN ISP 29 30 GND ANALOG IN 29 GND SCL SDA AREF GND 13 12 ~11 ~10 ~9 8 DIGITAL (PWM~) IOREF 11 12 START SOMETHING 10 11 13 TX RX 10 POWER ++ -– a 1 RESET ++ -– 7 ~6 ~5 4 ~3 2 TX 1 RX 0 HEADS UP! Double check ++ -– the polarity of the TMP36 temperature sensor before powering the RedBoard. It can V+ GND 5V to D10 to JUMPER WIRES LCD SCREEN TMP36 SENSOR POTENTIOMETER 78 : circuit 4b A0 to become very hot if it is inserted TMP SIGNAL 5V GND to E26 GND(-) D8 to E28 D9 to E25 D12 to E20 D13 to GND(-) E29 to 5V(+) D11 to E2 E30 to backward! E16 to 5V(+) E15 to E10 to 5V(+) E1 to GND(-) GND(-) A15-A30 (pin 1 on A15) A1 (GND) + A2 (SIG) + A8 + A10 A9 + A3(5V) E9 to E3 to E17 5V(+) E27 E19 to E8 to E18 GND(-) GND(-) Open the Arduino IDE Connect the RedBoard to a USB port on your computer.   Open the Sketch: File > Examples > SIK_Guide_Code-V_4 > SIK_CIRCUIT_4B-TEMPERATURE SENSOR   Select UPLOAD to program the sketch on the RedBoard. W H AT Y O U SHOULD SEE The LCD will show the temperature in Celsius and Fahrenheit. The temperature readings will update every second. An easy way to see the temperature change is to press your finger to the sensor. PROGRAM OVERVIEW 1 Get the analog value from the TMP36 and convert it back to a voltage between 0 and 5V. 2 Calculate the degrees Celsius from this voltage. 3 Calculate the degrees Fahrenheit from this voltage. 4 Clear the LCD. 5 Print the degrees C with a label on the first row. 6 Print the degrees F with a label on the second row. 7 Wait for a second before taking the next reading. 79 : circuit 4b CODE TO NOTE Many of the sensors that you will use with your microcontroller work by changing a voltage in some predictable way in response to a property of the world (like temperature, light or magnetic fields). VOLTAGE CONVERSION ALGORITHMS Often, you will need to build an algorithm that converts these voltages to the desired value and units. The temperature sensor is a great example of this code. We use three equations to convert a voltage value into degrees in C and F. voltage = analogRead(A0) * 0.004882814; degreesC = (voltage - 0.5) * 100.0; degreesF = degreesC * (9.0/5.0) + 32.0; CODING CHALLENGES DISPLAY THE TEMPERATURE IN DEGREES KELVIN: Try adding an equation so that the temperature is displayed in degrees Kelvin. (You will have to look up the formula for converting from degrees Celsius or Fahrenheit to Kelvin.) DISPLAY A BAR GRAPH: By changing the code you can display the temperature as a bar graph instead of a number. DISPLAY VALUES FROM ANOTHER SENSOR: You can swap out the TMP36 for a potentiometer, photoresistor or other sensor and display the new set of values. ADD AN RGB LED: Add an RGB LED that changes color based on the temperature. 80 : circuit 4b TROUBLESHOOTING Make sure that you wired the temperature sensor correctly. Sensor is The temperature sensor can get warm to the touch if it is wired heating up incorrectly. Disconnect power from your microcontroller, rewire the circuit, and connect it back to your computer. Temperature Try pinching the sensor with your fingers to heat it up or pressing value is a bag of ice against it to cool it down. Also, make sure that the unchanging wires are connected properly to the temperature sensor. Values not printing to screen If you see text but no temperature values, there could be an error in your code. If you see no text at all, adjust the LCD contrast. You’ve completed Circuit 4B! Continue to circuit 4C to learn how to make a “DIY Who Am I?” game. LCD “HELLO, WORLD” A T E M P E R AT U R E S E N S O R B “DIY WHO AM I?” GAME C 81 : circuit 4b Circuit 4C: “DIY Who Am I?” Game “DIY Who Am I?” is based on the popular Hedbanz game or HeadsUp! app. It’s a fun party game in which a player holds an LCD screen to his/her forehead, and other players give hints to help the player with the LCD guess the word on the screen. YOU NEED LCD DISPLAY POTENTIOMETER AA BATTERY HOLDER PUSH BUTTON DUAL LOCK TAPE PIEZO BUZZER 20 JUMPER WIRES 4 AA BATTERIES SCISSORS (NOT INCLUDED) NEW COMPONENTS 4XAA BATTERY HOLDER: Included in This simple addition will prevent a word from getting skipped when you press the button for the game. your kit is a 4-cell AA battery holder. The 5-inch cable is For a more complex example of button terminated with debouncing, in the Arduino IDE open File > a standard barrel Examples > 02.Digital > Debounce. jack connector. STRINGS: Strings are used to print words The connector mates with the barrel jack on the RedBoard, allowing you to easily make your project battery powered. NEW CONCEPTS BUTTON DEBOUNCE: When working with momentary buttons, it is usually necessary to add button debouncing to your code. This is because the code that is meant to execute when the button is pressed may execute faster than you can press and release the button (microcontrollers are fast!). The simplest and even sentences to an LCD or the Serial Monitor. Strings are actually just an array of characters with a null character at the end to let the program know where the end of the string is. ARRAY OF STRINGS: In circuit 2A you used an array of characters to represent musical notes. In this program, you’ll want to make an array of strings. Strings use multiple characters to make words, so you’ll need to use a little trick to put them in an array. The trick is to use a pointer. When you declare your array, you’ll use an asterisk (*) after the char data type, as follows: way to debounce a button is to add a small delay to the end of your code. This sketch adds a 500 millisecond delay at the end of loop() to account for this. 82 : circuit 4c const char* arrayOfStrings = {“Feynman” “Sagan”, “Tyson”, “Nye”}; POINTERS: As an advanced programming topic, pointers can be difficult to understand at first. For now, think of pointers as a variable that “points” to the value contained in a certain address in memory. In this sketch, the char* variable points to arrayOfStrings address and returns the character values to create a list of strings. BATTERY HOLDER ASSEMBLY Batteries are polarized. They have a positive end and a negative end. The battery holder has images indicating which end goes in which orientation for each cell. To attach the battery holder to the breadboard baseplate, first cut two strips of Dual Lock that are roughly 1 inch x 1 inch each, or 2.5cm x 2.5cm. Remove the adhesive backing, and attach one piece to the back of the battery holder. Adhere the second piece to the bottom of the breadboard baseplate (directly in the middle is recommended, as this will come into play in Project 5). Last, press the battery holder to the baseplate so that the two pieces of Dual Lock snap together. Insert the batteries into the holder. Remember that batteries are polarized. Remove the pack before building the circuit, so it doesn’t slide around. STOP! Disconnect the battery pack from power while building your circuit. Working on your circuit while connected to a power source risks damaging your components. 83 : circuit 4c HOOKUP GUIDE READY TO START HOOKING EVERYTHING UP? Check out the circuit diagram and hookup table below to see how everything is connected. b c d e f g h i ++ -– j 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 7-15V RESET 12 3.3V 13 13 5V 14 14 15 15 16 16 17 17 18 18 19 19 A2 20 20 A3 21 21 A4 22 22 A5 23 23 24 24 25 25 26 26 27 27 28 28 GND VIN A0 A1 b c d e f g h 5V to JUMPER WIRES PUSH BUTTON POTENTIOMETER BUZZER 84 : circuit 4c j 5V GND to D10 to E26 D6 to J6 E19 to GND(-) E8 to LCD SCREEN i D2 to G6(+) to G1/G3 A9 to A10 G8(–) E25 J1 E16 to E10 to A15-A30 (pin 1 on A15) A8 to GND(-) D11 to GND(-) D1/D3 to ON ++ -– 30 a 7 ~6 ~5 4 ~3 2 TX 1 RX 0 ISP 29 30 ANALOG IN 29 GND SCL SDA AREF GND 13 12 ~11 ~10 ~9 8 DIGITAL (PWM~) IOREF 11 12 START SOMETHING 10 11 13 TX RX 10 POWER ++ -– a 1 RESET ++ -– D8 to E28 D9 to D12 to E20 D13 to E30 to 5V(+) 5V(+) GND(-) E15 to J8 to E29 to GND(-) GND(-) E27 E18 5V(+) E9 to J3 to E17 GND(-) Open the Arduino IDE Connect the RedBoard to a USB port on your computer. Open the Sketch: File > Examples > SIK_Guide_Code-V_4 > SIK_CIRCUIT_4C-DIY WHO AM I   Select UPLOAD to program the sketch on the RedBoard. W H AT Y O U SHOULD SEE The game begins with the category of words, then runs through a short countdown. When the first round starts, the word to be guessed is displayed at top left, and a countdown starts in the bottom right. Each time the button is pressed (before the timer expires) a new word is displayed. If you win or lose, a short song will play. PROGRAM OVERVIEW 1 Generate a random order for the words to be displayed. 2 Show the starting countdown on the LCD. Start a loop that will run 25 times (there are 25 words total). For each round: A: Print the round number and the word to be guessed. B: Display a countdown timer in the lower right-hand corner 3 of the screen that counts down the time limit for each round. C: If the time limit runs out, play the losing song, print “Game Over” and show the player’s final score. D: If the player presses the button before the time limit is up, advance to the next word. 4 If the player gets through all 25 words, play the winning song and print “YOU WIN!” 85 : circuit 4c CODE TO NOTE ARRAY OF STRINGS: Makes an array of strings. The strings are stored const char* array_name [array_ length] = as constants, so they can’t be changed once the program starts. {“string1”, “string2”...}; ROUNDING FUNCTION: This math function rounds a number up or down to round(value_to_round); the nearest whole number. RANDOM FUNCTION: This function takes a set of numbers and generates random(min, max); a pseudo-random number from that set. BUTTON DEBOUNCE: delay(500); USER FUN This 500 millisecond delay at the end of the loop adds button debounce so that erroneous button presses are not detected by the RedBoard. FUNCTIONS TO NOTE CTIONS Makes an array that is a random ordering of the generateRandomOrder(); numbers from 1–25. This is used to display words for the game in a random order. showStartSequence(); gameOver(); winner(); 86 : circuit 4c Shows the category of words on the LCD, then displays a countdown before the game starts. Plays a sound and shows the text “Game Over” along with the player’s final score. Shows the text “YOU WIN!” and plays a winning sound. CODING CHALLENGES CHANGE THE TIME LIMIT: Changing the time limit variable will change the difficulty of the game. CHANGE THE WORDS IN THE WORD LIST: Try changing the categories and words. The number of words in your words array must match the value of the variable arraySize . CHANGE THE WINNING AND LOSING SONGS: By changing the tones in the winner() and gameover() functions you can change which song plays at the end of the game. TROUBLESHOOTING Adjust the contrast by twisting the potentiometer. If it’s The screen is blank or incorrectly adjusted, you won’t be able to read the text. flickering Also, check the potentiometer to make sure it’s connected correctly. No sound is coming from the buzzer The button doesn't work or words are getting skipped before they are guessed Check the wiring to the buzzer and the polarity. Make sure you are using the correct pin as defined in your code. You may add a potentiometer volume knob if you desire. If the button isn’t working, check your wiring. If words are being skipped when the button is pressed, increase the debounce delay found at the end of the loop. It should be 500 milliseconds by default. Increasing this number by tiny increments will help with this problem. You’ve completed Circuit 4C! Continue to Project 5 to learn how to build your first robot! LCD “HELLO, WORLD” A T E M P E R AT U R E S E N S O R B “DIY WHO AM I?”GAME C 87 : circuit 4c MOTOR BASICS R E M O T E- C O N T R O L L E D R O B O T AUTONOMOUS ROBOT A B C PROJECT 5 Ah, robots. One of the most iconic and exciting electronics applications. In this project, you will learn all about DC motors and motor drivers by building your own robot! You’ll first learn motor control basics. Then you’ll control a tethered robot by sending it commands over serial. Last, you will unleash your robot by removing the tether and making it autonomous! By adding a distance sensor, the robot can learn how to avoid obstacles. 88 : circuit 5a NEW COMPONENTS INTRODUCED IN THIS PROJECT •   T B 6 6 1 2 F N G M OTO R D R I V E R •   S W I TC H •   DC G E A R M OTO R • WHEEL NEW CONCEPTS INTRODUCED IN THIS PROJECT •   I N P U T V O L TA G E •   I N T E G R AT E D C I R C U I T S •   H - B R I DG E M OTO R D R I V E R • ASCII CHARACTERS • CONVERTING STRINGS •   AU TO N O M O U S V E H I C L E S YOU WILL LEARN •   H OW TO CO N T R O L A M OTO R U S I N G A M OTO R D R I V E R •   H OW TO S E N D S E R I A L CO M M A N D S T O C R E AT E A R E M O T E - C O N T R O L L E D ROBOT •   H O W T O B U I L D A R O B O T T H AT U S E S S E N S O R S TO R E AC T TO I T S ENVIRONMENT Circuit 5A: Motor Basics In this circuit, you will learn the basic concepts behind motor control. Motors require a lot of current, so you can’t drive them directly from a digital pin on the RedBoard. Instead, you’ll use what is known as a motor controller or motor driver board to power and spin the motor B11 B12 PWMB PWMA A12 A11 ST BY accordingly. GND MOT DRI OR VER B02 B01 GEAR MOTOR YOU NEED 16 HOOKUP WIRES SWITCH GND A02 VM VCC GND A01 MOTOR DRIVER NEW COMPONENTS SWITCHES are components that control side of the motor. The included wheels just so happen to fit on the plastic axles. the open-ness or closed-ness of an electric TB6612FNG MOTOR DRIVER: If you circuit. Just like the momentary switch the direction of current through buttons used in earlier circuits, a motor by swapping the positive and this type of switch can only negative leads, the motor will spin in exist in one of two states: open the opposite direction. Motor controllers or closed. However, a switch is different in VM PWMA that it will stay in the position it was last in VCC A12 until it is switched again. GND A11 A01 ST BY A02 B11 THE MOTORS in your Inventor’s Kit have two main parts: a small DC motor that spins quickly and a plastic gearbox that gears down the output from the hobby motor so that it is slower but stronger, allowing it to move your robot. The motors B02 B12 B01 PWMB GND MOTOR DRIVER GND contain a set of switches (called an H-bridge) that lets you easily control the direction of one or more motors. The TB6612FNG Motor Driver takes commands for each motor over three wires (two wires control direction, and one controls speed), and then uses these signals to control the current through two wires attached to your motor. NEW CONCEPTS VOLTAGE IN (VIN): This circuit utilizes have a clever design allowing you to attach the VIN pin found with the other RedBoard things that you want to spin fast (like a power pins. The VIN pin outputs a voltage small fan or flag) to the hobby motor, and that varies based on whatever voltage the things that you want to be strong (like a RedBoard is powered with. If the RedBoard wheel) to the plastic axle sticking out the is powered through the USB port, then the 89 : circuit 5a voltage on VIN will be about 4.6–5V. However, if you power the RedBoard through the barrel jack (highlighted in the picture), the VIN pin will reflect that voltage. For example, if you were to power the barrel jack with 9V, the voltage out on VIN would also be 9V. Notice that the voltage range listed on the RedBoard near the barrel jack is 7–15V. This means that the input voltage should always be at or above 7V or should be at 7 ~6 ~5 4 ~3 2 TX 1 RX 0 SCL SDA AREF GND 13 12 ~11 ~10 ~9 8 or below 15V. Never exceed this range. DIGITAL (PWM~) 13 TX RX INTEGRATED CIRCUITS (ICS) AND BREAKOUT BOARDS: An Integrated Circuit (IC) is a collection of electronic ONcomponents — resistors, transistors, capacitors, etc. — all stuffed into a tiny chip and connected together to achieve START SOMETHING a common goal. They come in all sorts of flavors, shapes and sizes. The chip that powers ISP the RedBoard, the ATmega328, is an IC. The chip on the motor driver, the A5 A4 A3 A2 ANALOG IN A1 VIN 5V Integrated circuits are often too A0 GND POWER GND 3.3V RESET IOREF TB6612FNG, is another IC. small to work with by hand. To make working with ICs easier and to make them breadboard-compatible, they are often added to a breakout board, which is a printed circuit board that connects all the IC’s tiny legs to larger ones that fit in a breadboard. The motor driver board in your kit is an example of a breakout board. The guts of an integrated circuit, visible after removing the top. 90 : circuit 5a Once you’re finished with this project, removing the motor driver from the breadboard can be difficult due to its numerous legs. To make this easier, use the included screwdriver as a lever to gently pry it out. Be careful not to bend the legs as you remove it. The motors are polarized. However, motors are unique in that they will still work when the two connections are reversed. They will just spin in the opposite direction when hooked up backward. To keep things simple, always think of the red wire as positive ( + ) and the black wire as negative ( - ). MEET YOUR MOTOR CONTROLLER. The TB6612FNG Motor Driver may look complicated, but it’s easy to use. Three pins on the right (PWMA, A12 and A11) control the two pins on the left (A01 and A02). The same is true for channel B. Motors require more current, which is why the VIN voltage is needed. Most ICs have polarity and usually have a polarity marking in one of the corners. The motor driver is no exception. Be sure to insert the motor driver as indicated in the circuit diagrams. The motor driver pins are explained in the table on the next page. 91 : circuit 5a VM VCC GND A01 A02 B02 B01 GND VM PWMA VCC A12 GND A11 A01 ST BY A02 B11 B02 B12 B01 GND MOTOR DRIVER PWMB GND PIN LABEL FUNCTION POWER/INPUT/ OUTPUT VM Motor Voltage Power VCC Logic Voltage Power PWMA AIN2 AIN1 STBY BIN1 BIN2 PWMB GND NOTES This is where you provide power for the motors (2.2V to 13.5V) This is the voltage to power the chip and talk to the microcontroller (2.7V to 5.5V) Common Ground for both motor GND Ground Power voltage and logic voltage (all GND pins are connected) Allows the H-bridges to work STBY Standby Input when high (has a pull-down resistor, so it must actively be pulled high) AIN1/BIN1 AIN2/BIN2 PWMA/ PWMB A01/B01 A02/B02 92 : circuit 5a Input 1 for channels A/B Input 2 for channels A/B PWM input for channels A/B Output 1 for channels A/B Output 2 for channels A/B Input Input Input Output Output One of the two inputs that determine the direction One of the two inputs that determine the direction PWM input that controls the speed One of the two outputs to connect the motor One of the two outputs to connect the motor HOOKUP GUIDE READY TO START HOOKING EVERYTHING UP? Check out the circuit diagram and hookup table below to see how everything is connected. a b c d e f g h i VM PWMA 1 2 VCC A12 2 3 GND A11 3 4 A01 ST BY 4 5 A02 B11 5 6 B02 B12 6 7 B01 PWMB 7 8 GND GND 8 MOTOR DRIVER 9 7-15V SCL SDA AREF GND 13 12 ~11 ~10 ~9 8 9 RESET 12 3.3V 13 13 5V 14 14 15 15 16 16 17 17 18 18 19 19 A2 20 20 A3 21 21 A4 22 22 A5 23 23 24 24 25 25 26 26 27 27 28 28 b c d e f g i j 5V to 5V D9 to J6 D13 to J4 to MOTOR DRIVER SWITCH D10 to D7 to GND (-) 5V (+) A4(RED +) C1-C8 to F25 + 7 ~6 ~5 4 ~3 2 TX 1 RX 0 ++ -– GND to J3 GND (-) to MOTOR A1 REDBOARD CONNECTION CONNECTION TYPES JUMPER WIRES h A0 ON 30 a VIN ISP 29 30 GND ANALOG IN 29 GND DIGITAL (PWM~) IOREF 11 12 START SOMETHING 10 11 13 TX RX 10 POWER ++ -– ++ -– j 1 RESET ++ -– I26 to BREADBOARD CONNECTION GND (-) J7 D11 to I27 A2 to VIN to J1 5V (+) to 5V (+) A1 D8 to D12 to J5 J2 5V (+) A3 to GND (-) GND (-) A5(BLACK -) G1-G8 (VM on C1, PWMA on G1) F26 + F27 93 : circuit 5a Open the Arduino IDE Connect the RedBoard to a USB port on your computer. Open the Sketch: File > Examples > SIK_Guide_Code-V_4 > CIRCUIT_5A-MOTOR BASICS   Select UPLOAD to program the sketch on the RedBoard. W H AT Y O U SHOULD SEE Flip the switch. The motor will spin at the speed set by the motor speed variable (default is 0). Open the Serial Monitor, type any number from 30 to 255 or -30 to -255 , and then press Enter. Changes in speed will be hard to notice. Send 0 to stop the motor. PROGRAM OVERVIEW 1 Check to see if a command has been sent through the Serial Monitor. If a command has been sent, then set the motor speed to the number that was sent over the Serial Monitor. Check to see if the switch is ON or OFF. 2 A: If the switch is ON, drive the motor at the motor speed. B: If the switch is OFF, stop the motor. PARSING INTEGERS: Serial.parseInt(); CODE TO NOTE .parseInt() receives integer numbers from the Serial Monitor. It returns the value of the number that it receives, so you can use it like a variable. This command checks how many bytes of data are being SERIAL AVAILABLE: sent to the RedBoard. If it is greater than 0, then a message Serial.available(); has been sent. It can be used in an if statement to run code only when a command has been received. 94 : circuit 5a CODING CHALLENGES MAKE THE SWITCH CHANGE DIRECTIONS: Change the code so that the position of the switch changes the direction of the motor instead YOU of turning it on and off. NEED REPLACE THE SWITCH WITH A BUTTON: Try wiring a button into the circuit instead of the sliding switch. Now the motor only turns on when you push the button. REPLACE THE SWITCH WITH A SENSOR: Try changing the code so that the motor is activated by another sensor, like the photoresistor. TROUBLESHOOTING Check the wiring to the motor driver. There are a lot of connections, Motor not and it’s easy to mix one of them up with another. Double check spinning the polarity of the motor driver. All the text should face the same direction as everything else. Switch not Make sure that you are hooked up to the middle pin and one side pin working on the switch, and not both side pins. Jumper wires unfortunately can go “bad” from getting bent too much. The copper wire inside can break, leaving an open connection Still not in your circuit. If you are certain that your circuit is wired correctly working? and that your code is error-free and uploaded but you are still encountering issues, try replacing one or more of the jumper wires for the component that is not working. You’ve completed Circuit 5A! Continue to circuit 5B to construct a remote-controlled robot. MOTOR BASICS A REMOTE-CONTROLLED ROBOT B AUTONOMOUS ROBOT C 95 : circuit 5a B11 B12 PWMB PWMA A12 A11 H810 6 2 WHEELS GND MOT DRI OR VER B02 B01 In this circuit, you’ll control two motors and build your own remote-controlled roving robot! You will also learn how to read information from a serial command so that you can use the Serial Monitor to tell the robot in what direction to move and how far to move. 2 GEAR MOTORS SWITCH 16 JUMPER WIRES GND A02 VM VCC GND MOTOR DRIVER A01 YOU NEED ST BY Circuit 5B: RemoteControlled Robot DUAL LOCK TAPE BINDER CLIP SCISSORS (NOT INCL
BOK-14263 价格&库存

很抱歉,暂时无法提供与“BOK-14263”相匹配的价格&库存,您可以联系我们找货

免费人工找货