Arduino Tutorial Bundle .:Arduino Experimentation Kit:. (ARDX)
by oomlout in Circuits > Electronics
194144 Views, 575 Favorites, 0 Comments
Arduino Tutorial Bundle .:Arduino Experimentation Kit:. (ARDX)
Interested in making neat projects with an Arduino but not sure where to start?
Here's an easy to follow guide on how to connect & use a bevy of electronic components.
(shameless plug)
Interested in doing it all?
Complete kits with components to make every circuit, a printed guide and breadboard layout sheets can be purchased from.
oomlout.co.uk (in the UK)
or
adafruit.com (USA & International Shipping)
or
Floris.cc (in Holland)
Lets get started!
(A PDF Version of this guide can be downloaded below)
Jump to a specific copmonent
'''CIRC-01''' - Getting Started - (Blinking LED)
'''CIRC-02''' - Multiple LEDs - (8 LED Fun)
'''CIRC-03''' - Spin Motor Spin - (Transistor & Motor)
'''CIRC-04''' - A Single Servo - (Servos)
'''CIRC-05''' - 8 More LEDs - (74HC595 Shift Register)
'''CIRC-06''' - Music - (Piezo Element)
'''CIRC-07''' - Button Pressing - (Push Buttons)
'''CIRC-08''' - Twisting - (Potentiometers)
'''CIRC-09''' - Light - (Photo Resistors)
'''CIRC-10''' - Temperature - (TMP36 Precision Temperature Sensor)
'''CIRC-11''' - Larger Loads - (Relays)
(at oomlout we like to make everything we do open source, we have yet to properly document the files that have gone into this product however the development files can be looked through at http://www.oomlout.com/ARDX/ or if you can't find a file send us a message and we'll send it your way)
.: Installing the Software :.
Before we go any further you'll need to download and install the Arduino IDE (Integrated Development Environment), this is the program we use to write programs for the Arduino.
Step- 1 - Download the IDE
Step-2- Unzip the software
Step 2 - Unzip the Software
Step- 1 - Download the IDE
- The Arduino IDE is available for all major operating systems. Head over to http://arduino.cc/en/Main/Software and download the appropriate version.
Step-2- Unzip the software
- Unzip the program. (we recommend placing it in c:\Program Files\)
- Goto C:\Program Files\Arduino-00**
- Right click on Arduino.exe the goto "Send To > Desktop"
- Plug your Arduino board into a free USB port using an A-B USB cable
- Wait for a box to pop up
- In the add new hardware dialog box click "skip searching the internet"
- Choose "install from a specific location"
- Choose the location "C:\Program Files\Arduino-00**\drivers\FTDI_USB_Drivers\
- FINISHED
Step 2 - Unzip the Software
- Do this by double clicking
- Move the folder to "//Applications/"
- Open //Applications/arduino-00**/
- Command click Arduino
- Make alias
- Drag the alias to the Desktop
- Goto //Applications/arduino00**/drivers
- Double click and install FTDIUSBSerialDriver_V2_2_9_Intel.dmg
- Plug your Arduino in
.: a Few Basics :.
Before we get started there are two areas where brushing up may be helpful. Here is a quick review of a few electronic components and of C programming.
(you can skip this step if you like, as most of it can be picked up along the way)
Arduino Holder
While it is easy to prototype circuits with an Arduino and a breadboard beside it we find it is difficult to latter move. To combat this we use a piece of laser cut acrylic, which you attach the Arduino and Breadboard to. This is included in the full kits, or if you'd like to make your own, the design files can be found here (on Thingiverse).
Electronic Components
Here is a quick summary of each of the components we will use
The Arduino is programmed in a C like language. Full details can be found in the online reference.
http://arduino.cc/en/Reference/HomePage
(you can skip this step if you like, as most of it can be picked up along the way)
Arduino Holder
While it is easy to prototype circuits with an Arduino and a breadboard beside it we find it is difficult to latter move. To combat this we use a piece of laser cut acrylic, which you attach the Arduino and Breadboard to. This is included in the full kits, or if you'd like to make your own, the design files can be found here (on Thingiverse).
Electronic Components
Here is a quick summary of each of the components we will use
- LED (Light Emitting Diode) - Emits a light when a small current is passed through it. They tend to look like miniature light bulbs. You need to keep in mind that they are polarized and will only work in one direction (the longer lead indicates the Cathode or positive lead). For more details: http://tinyurl.com/zhpyv
- Diode - The electronic equivalent of a one way valve. Allowing current to flow in one direction but not the other. Usually identifiable as they are a cylinder with wires out either end and an off centre line indicating polarity. For more details: http://www.tinyurl.com/ysz57b
- Resistor - Restricts the amount of current that can flow through a circuit. Also a cylinder with wires out either end. The resistance value is displayed using a color coding system. For more details: http://www.tinyurl.com/cmeqw5
- Transistor - Uses a small current to switch or amplify a much larger current. They come in a variety of different packages. For more details: http://tinyurl.com/eazkn
- Hobby Servo - A small motor, gearbox and control circuitry. It takes a timed pulse and converts it into an angular position. For more details: http://tinyurl.com/4zo4he
- DC Motor - A little motor which of course spins when a current is passed through it. For more details: http://tinyurl.com/d826yh
- Piezo Element - Will emit a click when it is pulsed, if you send it a stream of pulses it will emit a tone. For more details: http://tinyurl.com/38crmu
- Integrated Circuit - Packages any range of complicated electronics inside an easy to use case. For more details: http://tinyurl.com/87k4d
- Pushbutton - Completes a circuit when pressed: For more details: http://tinyurl.com/cmts7d
- Potentiometer (Variable Resistor) - Produces a variable resistance dependant on the angular position of the shaft. For more details: http://tinyurl.com/28pbhd
- Photo-Resistor - Produces a variable resistance dependant on the amount of incident light. For more details: http://tinyurl.com/c2wdkw
The Arduino is programmed in a C like language. Full details can be found in the online reference.
http://arduino.cc/en/Reference/HomePage
.:Getting Started:. (Blinking LED) - CIRC01
What We're Doing:
LEDs (light emitting diodes) are used in all sorts of clever things which is why we have included them in this intro. We will start off with something very simple, turning one on and off, repeatedly, producing a pleasant blinking effect. To get started grab the parts listed below, pin the layout sheet to your breadboard and then plug everything in. Once the circuit is assembled you'll need to upload the program. To do this plug the Arduino board into your USB port. Then select the proper port in Tools > Serial Port > (the comm port of your Arduino). Next upload the program by going to File > Upload to I/O Board (ctrl+U). Finally bask in the glory and possibility that controlling lights offers.
If you are having trouble uploading, a full trouble shooting guide can be found here:
(you can also download the breadboard layout sheet from the bottom of this step)
The Parts:
- CIRC-01 (Getting Started) Breadboard Sheet (x1)
- 2 Pin Header (x4)
- 10mm LED (x1)
- 560 Ohm Resistor (green-blue-brown) (x1)
- wire
The Circuit and Plugging Everything In:
A Small Video of Everything Being Plugged in
The Code:
goto the Arduino IDE (program) and go file > examples > digital > Blink or copy the code below and paste it into an empty sketch file
/* * Blink * * The basic Arduino example. Turns on an LED on for one second, * then off for one second, and so on... We use pin 13 because, * depending on your Arduino board, it has either a built-in LED * or a built-in resistor so that you need only an LED. * * http://www.arduino.cc/en/Tutorial/Blink */int ledPin = 13; // LED connected to digital pin 13void setup() // run once, when the sketch starts{ pinMode(ledPin, OUTPUT); // sets the digital pin as output}void loop() // run over and over again{ digitalWrite(ledPin, HIGH); // sets the LED on delay(1000); // waits for a second digitalWrite(ledPin, LOW); // sets the LED off delay(1000); // waits for a second}
Not Working?
- LED Not Lighting Up - LEDs will only work in one direction. Try taking it out and twisting it 180 degrees. (no need to worry, installing it backwards does no permanent harm)
- Program Not Uploading - This happens sometimes, the most likely cause is a confused serial port, you can change this in tools>serial port>
- Still No Success? - A broken circuit is no fun, send us an e-mail and we will get back to you as soon as we can. help@oomlout.com
Making it Better:
Changing the pin:
The LED is connected to pin 13 but we can use any of the Arduino's pins. To change it take the wire plugged into pin 13 and move it to a pin of your choice (from 0-13) (you can also use analog 0-5 analog 0 is 14...)
Then in the code change the line:
int ledPin = 13; -> int ledPin = newpin;
Then upload the sketch: (ctrl-u)
Change the Blink Time:
Unhappy with one second on one second off?
In the code change the lines:
digitalWrite(ledPin, HIGH); delay(time on); //(seconds * 1000) digitalWrite(ledPin, LOW); delay(time off); //(seconds * 1000)
Control the Brightness:
Along with digital (on/off) control the Arduino can control some pins in an analog (brightness) fashion. (more details on this in later circuits). To play around with it.
Change the LED to pin 9: (also change the wire)
ledPin = 13; -> int ledPin = 9;Replace the code inside the { }'s of loop() with this:
analogWrite(ledPin, new number);(new number) = any number between 0 and 255.
0 = off, 255 = on, in between = different brightness
Fading:
We will use another included example program. To open go to.
File > Sketchbook > Examples > Analog > Fade
Then upload to your board and watch as the LED fades in and then out.
Links:
Looking for more details or perhaps the concepts explained in another way, the internet has loads of Arduino references here are a few for this circuit
- Lady Ada's Blink Tutorial (loads of extra detail on why everything is working as it is) - http://www.ladyada.net/learn/arduino/lesson1.html
- The official Arduino.cc Blink Tutorial - http://www.arduino.cc/en/Tutorial/Blink
- Make Magazines excellent Arduino 101 Series on Blink - http://blog.makezine.com/archive/2009/02/howto_tuesday_arduino_101_blink_an_led.html
Downloads
.:8 LED Fun:. (Multiple LEDs) - CIRC02
What We're Doing:
We have caused one LED to blink, now its time to up the stakes. Lets connect eight. We'll also have an opportunity to stretch the Arduino a bit by creating various lighting sequences. This circuit is also a nice setup to experiment with writing your own programs and getting a feel for how the Arduino works.
Along with controlling the LEDs we start looking into a few simple programming methods to keep your programs small.
for() loops - used when you want to run a piece of code several times.
arrays[] - used to make managing variables easier (its a group of variables)
(you can also download the breadboard layout sheet from the bottom of this step)
The Parts:
- CIRC-02 Breadboard sheet
- 2 Pin Header (x4)
- 5mm Green LED (x8)
- 560 ohm Resistor (green-blue-brown) (x8)
The Circuit and Plugging Everything In:
A Small Video of Everything Being Plugged in
The Code:
/* --------------------------------------------------------- * | Arduino Experimentation Kit Example Code | * | CIRC-02 .: 8 LED Fun :. (Multiple LEDs) | * --------------------------------------------------------- * * A few Simple LED animations * * For more information on this circuit http://tinyurl.com/d2hrud * *///LED Pin Variablesint ledPins[] = {2,3,4,5,6,7,8,9}; //An array to hold the pin each LED is connected to //i.e. LED #0 is connected to pin 2, LED #1, 3 and so on //to address an array use ledPins[0] this would equal 2 //and ledPins[7] would equal 9/* * setup() - this function runs once when you turn your Arduino on * We the three control pins to outputs */void setup(){ //Set each pin connected to an LED to output mode (pulling high (on) or low (off) for(int i = 0; i < 8; i++){ //this is a loop and will repeat eight times pinMode(ledPins[i],OUTPUT); //we use this to set each LED pin to output } //the code this replaces is below /* (commented code will not run) * these are the lines replaced by the for loop above they do exactly the * same thing the one above just uses less typing pinMode(ledPins[0],OUTPUT); pinMode(ledPins[1],OUTPUT); pinMode(ledPins[2],OUTPUT); pinMode(ledPins[3],OUTPUT); pinMode(ledPins[4],OUTPUT); pinMode(ledPins[5],OUTPUT); pinMode(ledPins[6],OUTPUT); pinMode(ledPins[7],OUTPUT); (end of commented code)*/}/* * loop() - this function will start after setup finishes and then repeat * we call a function called oneAfterAnother(). if you would like a different behaviour * uncomment (delete the two slashes) one of the other lines */void loop() // run over and over again{ oneAfterAnotherNoLoop(); //this will turn on each LED one by one then turn each off //oneAfterAnotherLoop(); //does the same as oneAfterAnotherNoLoop but with much less typing //oneOnAtATime(); //this will turn one LED on then turn the next one on turning the //former off (one LED will look like it is scrolling along the line //inAndOut(); //lights the two middle LEDs then moves them out then back in again}/* * oneAfterAnotherNoLoop() - Will light one LED then delay for delayTime then light * the next LED until all LEDs are on it will then turn them off one after another * * this does it without using a loop which makes for a lot of typing. * oneOnAtATimeLoop() does exactly the same thing with less typing */void oneAfterAnotherNoLoop(){ int delayTime = 100; //the time (in milliseconds) to pause between LEDs //make smaller for quicker switching and larger for slower digitalWrite(ledPins[0], HIGH); //Turns on LED #0 (connected to pin 2) delay(delayTime); //waits delayTime milliseconds digitalWrite(ledPins[1], HIGH); //Turns on LED #1 (connected to pin 3) delay(delayTime); //waits delayTime milliseconds digitalWrite(ledPins[2], HIGH); //Turns on LED #2 (connected to pin 4) delay(delayTime); //waits delayTime milliseconds digitalWrite(ledPins[3], HIGH); //Turns on LED #3 (connected to pin 5) delay(delayTime); //waits delayTime milliseconds digitalWrite(ledPins[4], HIGH); //Turns on LED #4 (connected to pin 6) delay(delayTime); //waits delayTime milliseconds digitalWrite(ledPins[5], HIGH); //Turns on LED #5 (connected to pin 7) delay(delayTime); //waits delayTime milliseconds digitalWrite(ledPins[6], HIGH); //Turns on LED #6 (connected to pin 8) delay(delayTime); //waits delayTime milliseconds digitalWrite(ledPins[7], HIGH); //Turns on LED #7 (connected to pin 9) delay(delayTime); //waits delayTime milliseconds //Turns Each LED Off digitalWrite(ledPins[7], LOW); //Turns on LED #0 (connected to pin 2) delay(delayTime); //waits delayTime milliseconds digitalWrite(ledPins[6], LOW); //Turns on LED #1 (connected to pin 3) delay(delayTime); //waits delayTime milliseconds digitalWrite(ledPins[5], LOW); //Turns on LED #2 (connected to pin 4) delay(delayTime); //waits delayTime milliseconds digitalWrite(ledPins[4], LOW); //Turns on LED #3 (connected to pin 5) delay(delayTime); //waits delayTime milliseconds digitalWrite(ledPins[3], LOW); //Turns on LED #4 (connected to pin 6) delay(delayTime); //waits delayTime milliseconds digitalWrite(ledPins[2], LOW); //Turns on LED #5 (connected to pin 7) delay(delayTime); //waits delayTime milliseconds digitalWrite(ledPins[1], LOW); //Turns on LED #6 (connected to pin 8) delay(delayTime); //waits delayTime milliseconds digitalWrite(ledPins[0], LOW); //Turns on LED #7 (connected to pin 9) delay(delayTime); //waits delayTime milliseconds }/* * oneAfterAnotherLoop() - Will light one LED then delay for delayTime then light * the next LED until all LEDs are on it will then turn them off one after another * * this does it using a loop which makes for a lot less typing. * than oneOnAtATimeNoLoop() does exactly the same thing with less typing */void oneAfterAnotherLoop(){ int delayTime = 100; //the time (in milliseconds) to pause between LEDs //make smaller for quicker switching and larger for slower//Turn Each LED on one after another for(int i = 0; i <= 7; i++){ digitalWrite(ledPins[i], HIGH); //Turns on LED #i each time this runs i delay(delayTime); //gets one added to it so this will repeat } //8 times the first time i will = 0 the final //time i will equal 7;//Turn Each LED off one after another for(int i = 7; i >= 0; i--){ //same as above but rather than starting at 0 and counting up //we start at seven and count down digitalWrite(ledPins[i], LOW); //Turns off LED #i each time this runs i delay(delayTime); //gets one subtracted from it so this will repeat } //8 times the first time i will = 7 the final //time i will equal 0; }/* * oneOnAtATime() - Will light one LED then the next turning off all the others */void oneOnAtATime(){ int delayTime = 100; //the time (in milliseconds) to pause between LEDs //make smaller for quicker switching and larger for slower for(int i = 0; i <= 7; i++){ int offLED = i - 1; //Calculate which LED was turned on last time through if(i == 0) { //for i = 1 to 7 this is i minus 1 (i.e. if i = 2 we will offLED = 7; //turn on LED 2 and off LED 1) } //however if i = 0 we don't want to turn of led -1 (doesn't exist) //instead we turn off LED 7, (looping around) digitalWrite(ledPins[i], HIGH); //turn on LED #i digitalWrite(ledPins[offLED], LOW); //turn off the LED we turned on last time delay(delayTime); }}/* * inAndOut() - This will turn on the two middle LEDs then the next two out * making an in and out look */void inAndOut(){ int delayTime = 100; //the time (in milliseconds) to pause between LEDs //make smaller for quicker switching and larger for slower //runs the LEDs out from the middle for(int i = 0; i <= 3; i++){ int offLED = i - 1; //Calculate which LED was turned on last time through if(i == 0) { //for i = 1 to 7 this is i minus 1 (i.e. if i = 2 we will offLED = 3; //turn on LED 2 and off LED 1) } //however if i = 0 we don't want to turn of led -1 (doesn't exist) //instead we turn off LED 7, (looping around) int onLED1 = 3 - i; //this is the first LED to go on ie. LED #3 when i = 0 and LED #0 when i = 3 int onLED2 = 4 + i; //this is the first LED to go on ie. LED #4 when i = 0 and LED #7 when i = 3 int offLED1 = 3 - offLED; //turns off the LED we turned on last time int offLED2 = 4 + offLED; //turns off the LED we turned on last time digitalWrite(ledPins[onLED1], HIGH); digitalWrite(ledPins[onLED2], HIGH); digitalWrite(ledPins[offLED1], LOW); digitalWrite(ledPins[offLED2], LOW); delay(delayTime); } //runs the LEDs into the middle for(int i = 3; i >= 0; i--){ int offLED = i + 1; //Calculate which LED was turned on last time through if(i == 3) { //for i = 1 to 7 this is i minus 1 (i.e. if i = 2 we will offLED = 0; //turn on LED 2 and off LED 1) } //however if i = 0 we don't want to turn of led -1 (doesn't exist) //instead we turn off LED 7, (looping around) int onLED1 = 3 - i; //this is the first LED to go on ie. LED #3 when i = 0 and LED #0 when i = 3 int onLED2 = 4 + i; //this is the first LED to go on ie. LED #4 when i = 0 and LED #7 when i = 3 int offLED1 = 3 - offLED; //turns off the LED we turned on last time int offLED2 = 4 + offLED; //turns off the LED we turned on last time digitalWrite(ledPins[onLED1], HIGH); digitalWrite(ledPins[onLED2], HIGH); digitalWrite(ledPins[offLED1], LOW); digitalWrite(ledPins[offLED2], LOW); delay(delayTime); }}
Not Working?
- Some LEDs Fail to Light - It is easy to insert an LED backwards. Check the LEDs that aren't working and ensure they the right way around.
- Operating out of sequence - With eight wires it's easy to cross a couple. Double check that the first LED is plugged into pin 2 and each pin there after.
- Starting Afresh - Its easy to accidentally misplace a wire without noticing. Pulling everything out and starting with a fresh slate is often easier than trying to track down the problem.
Making it Better:
Switching to Loops:
in the loop() function there are 4 lines. The last three all start with a '//' this means the line is treated as a comment (not run). To switch the program to use loops change the void loop() code to:
//oneAfterAnotherNoLoop(); oneAfterAnotherLoop(); //oneOnAtATime(); //inAndOut();Upload the program, and notice that nothing has changed. You can take a look at the two functions, each does the same thing, but use different approaches (hint the second one uses a for loop)
Extra Animations:
Tired of this animation? Then try the other two sample animations. Uncomment their lines and upload the program to your board and enjoy the new light animations. (delete the slashes in front of row 3 and then 4)
Testing out your own Animations:
Jump into the included code and start changing things. The main point is to turn an LED on use digitalWrite(pinNumber, HIGH); then to turn it off use digitalWrite(pinNumber, LOW); . Type away, regardless of what you change you won't break anything.
Downloads
.:Spin Motor Spin:. (Transistor & Motor) - CIRC03
What We're Doing:
The Arduino's pins are great for directly controlling small electric items like LEDs. However, when dealing with larger items (like a toy motor or washing machine), an external transistor is required. A transistor is incredibly useful. It switches a lot of current using a much smaller current. A transistor has 3 pins. For a negative type (NPN) transistor you connect your load to collector and the emitter to ground. Then when a small current flows from base to the emitter a current will flow through the transistor and your motor will spin (this happens when we set our Arduino pin HIGH). There are literally thousands of different types of transistors, allowing every situation to be perfectly matched. We have chosen a P2N2222AG a rather common general purpose transistor. The important factors in our case are that its maximum voltage (40 v) and its maximum current (600 milliamp) are both high enough for our toy motor (full details can be found on its datasheet http://tinyurl.com/o2cm93 )
note: the transistor we use has a in order: Base Collector Emitter pinout (differing from some other popular transistors)
(The 1N4001 diode is acting as a flyback diode for details on why its there visit: http://tinyurl.com/b559mx)
(you can also download the breadboard layout sheet from the bottom of this step)
The Parts:
- CIRC-03 Breadboard sheet
- 2 Pin Header (x4)
- Transistor (P2N2222AG) (TO92) (x1)
- 2.2k ohm Resistor (red-red-red) (x1)
- Toy Motor (x1)
- Diode (1N4001) (x1)
The Circuit and Plugging Everything In:
A Small Video of Everything Being Plugged in
The Code: - http://tinyurl.com/dagyrb
int motorPin = 9; //pin the motor is connected to void setup() //runs once{ pinMode(motorPin, OUTPUT); }void loop() // run over and over again{ motorOnThenOff(); //motorOnThenOffWithSpeed(); //motorAcceleration();}/* * motorOnThenOff() - turns motor on then off * (notice this code is identical to the code we used for * the blinking LED) */void motorOnThenOff(){ int onTime = 2500; //on time int offTime = 1000; //off time digitalWrite(motorPin, HIGH); // turns the motor On delay(onTime); // waits for onTime milliseconds digitalWrite(motorPin, LOW); // turns the motor Off delay(offTime);// waits for offTime milliseconds}void motorOnThenOffWithSpeed(){ int onSpeed = 200;// a number between //0 (stopped) and 255 (full speed) int onTime = 2500; int offSpeed = 50;// a number between //0 (stopped) and 255 (full speed) int offTime = 1000; analogWrite(motorPin, onSpeed); // turns the motor On delay(onTime); // waits for onTime milliseconds analogWrite(motorPin, offSpeed); // turns the motor Off delay(offTime); // waits for offTime milliseconds}void motorAcceleration(){ int delayTime = 50; //time between each speed step for(int i = 0; i < 256; i++){ //goes through each speed from 0 to 255 analogWrite(motorPin, i); //sets the new speed delay(delayTime);// waits for delayTime milliseconds } for(int i = 255; i >= 0; i--){ //goes through each speed from 255 to 0 analogWrite(motorPin, i); //sets the new speed delay(delayTime);//waits for delayTime milliseconds }}
Not Working?
- Motor Not Spinning? - If you sourced your own transistor, double check with the data sheet that the pinout is compatible with a P2N2222A (many are reversed)
- Still No Luck? - If you sourced your own motor, double check that it will work with 5 volts and that it does not draw too much power.
- Still Not Working? - Sometimes the Arduino board will disconnect from the computer. Try un-plugging and then re-plugging it into your USB port.
Making it Better:
Controlling Speed:
We played with the Arduino's ability to control the brightness of an LED earlier now we will use the same feature to control the speed of our motor. The arduino does this using something called Pulse Width Modulation (PWM). This relies on the Arduino's ability to operate really really fast. Rather than directly controlling the voltage coming from the pin the Arduino will switch the pin on and off very quickly. In the computer world this is going from 0 to 5 volts many times a second, but in the human world we see it as a voltage. For example if the Arduino is PWM'ing at 50% we see the light dimmed 50% because our eyes are not quick enough to see it flashing on and off. The same feature works with transistors. Don't believe me? Try it out.
In the loop() section change it to this
// motorOnThenOff(); motorOnThenOffWithSpeed(); //motorAcceleration();Then upload the programme. You can change the speeds by changing the variables onSpeed and offSpeed
Accelerating and decelerating:
Why stop at two speeds, why not accelerate and decelerate the motor. To do this simply change the loop() code to read
// motorOnThenOff();// motorOnThenOffWithSpeed(); motorAcceleration();Then upload the program and watch as your motor slowly accelerates up to full speed then slows down again. If you would like to change the speed of acceleration change the variable delayTime (larger means a longer acceleration time)
Downloads
.:A Single Servo:. (Servos) - CIRC04
What We're Doing:
Spinning a motor is good fun but when it comes to projects where motion control is required they tend to leave us wanting more. The answer? Hobby servos. They are mass produced, widely available and cost anything from a couple of dollars to hundreds. Inside is a small gearbox (to make the movement more powerful) and some electronics (to make it easier to control). A standard servo is positionable from 0 to 180 degrees. Positioning is controlled through a timed pulse, between 1.25 milliseconds (0 degrees) and 1.75 milliseconds (180 degrees) (1.5 milliseconds for 90 degrees). Timing varies between manufacturer. If the pulse is sent every 25-50 milliseconds the servo will run smoothly. One of the great features of the Arduino is it has a software library that allows you to control two servos (connected to pin 9 or 10) using a single line of code.
(you can also download the breadboard layout sheet from the bottom of this step)
The Parts:
- CIRC-04 Breadboard Sheet
- 2 Pin Header (x4)
- 3 Pin Header (x1)
- Mini Servo (x1)
- Wire
The Circuit and Plugging Everything In:
A Small Video of Everything Being Plugged in
The Code: - File > Sketchbook > Examples > Library-Servo > Sweep
// Sweep// by BARRAGAN <http://barraganstudio.com> #include <Servo.h> Servo myservo; // create servo object to control a servoint pos = 0; // variable to store the servo position void setup() { myservo.attach(9); // attaches the servo on pin 9 to the servo object }void loop() { for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees { // in steps of 1 degree myservo.write(pos); // tell servo to go to position in variable 'pos' delay(15); // waits 15ms for the servo to reach the position } for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees { myservo.write(pos); // tell servo to go to position in variable 'pos' delay(15); // waits 15ms for the servo to reach the position }}
Not Working?
- Servo Not Twisting? - Even with colored wires it is still shockingly easy to plug a servo in backwards. This might be the case.
- Still not Working - A mistake we made a time or two was simply forgetting to connect the power (red and brown wires) to +5 volts and ground.
- Frustration? - Shoot us an e-mail, this circuit is both simple and complex at the same time. We want to hear about problems you have so we can address them in future editions.
Making it Better:
Potentiometer Control:
We have yet to experiment with inputs but if you would like to read ahead, there is an example program File > Sketchbook > Examples > Library-Servo > Knob###. This uses a potentiometer (CIRC08) to control the servo. You can find instructions online here: http://tinyurl.com/dymsk2
Self Timing:
While it is easy to control a servo using the Arduino's included library sometimes it is fun to figure out how to program something yourself. Try it. We're controlling the pulse directly so you could use this method to control servos on any of the Arduino's 20 available pins (you need to highly optimize this code before doing that).
int servoPin = 9;void setup(){ pinMode(servoPin,OUTPUT);}void loop() { int pulseTime = 2100; //(the number of microseconds //to pause for (1500 90 degrees // 900 0 degrees 2100 180 degrees) digitalWrite(servoPin, HIGH); delayMicroseconds(pulseTime); digitalWrite(servoPin, LOW); delay(25);}Great Ideas:
Servos can be used to do all sorts of great things, here are a few of our favorites.
Xmas Hit Counter
http://tinyurl.com/37djhq
Open Source Robotic Arm (uses a servo controller as well as the Arduino)
http://tinyurl.com/ckm3wd
Servo Walker
http://tinyurl.com/da5jfe
Downloads
.:8 More Leds:. (74HC595 Shift Register) - CIRC05
What We're Doing:
Time to start playing with chips. Or integrated circuits (ICs) as they like to be called. The external packaging of a chip can be very deceptive for example the chip on the Arduino board (a micro controller) and the one we will use in this circuit (a shift register) look very similar but are in fact rather different, for example the price of the Atmega chip on the arduino board is a few dollars while the 74hc595 is a couple dozen cents. It's a good introductory chip, and once your comfortable playing around with it and its datasheet (available online http://tinyurl.com/pr42xe ) the world of chips will be your oyster. The shift register (also called a serial to parallel converter), will give you an additional 8 outputs (to control LEDs and the like) using only three arduino pins. They can also be linked together to give you a nearly unlimited number of outputs using the same four pins. To use it you clock in the data and then latch lock it in (latch it). To do this you set the data pin to either HIGH or LOW, pulse the clock, then set the data pin again and pulse the clock repeating until you have shifted out 8 bits of data. Then you pulse the latch and the 8 bits are transferred to the shift registers pins. It sounds complicated but is really simple once you get the hang of it.
(for a more in depth look at how a shift register works visit: http://tinyurl.com/56uvv7 )
(you can also download the breadboard layout sheet from the bottom of this step)
The Parts:
- CIRC-05 Breadboard sheet
- 2 Pin Header (x40
- Shift Register (74HC595) (x1)
- 560 ohm Resistor (green-blue-brown) (x8)
- 5mm Red LED (x8)
- Wire
The Circuit and Plugging Everything In:
A Small Video of Everything Being Plugged in
The Code: - http://tinyurl.com/cv4fjt
/* --------------------------------------------------------- * | Arduino Experimentation Kit Example Code | * | CIRC-05 .: 8 More LEDs :. (74HC595 Shift Register) | * --------------------------------------------------------- * * We have already controlled 8 LEDs however this does it in a slightly * different manner. Rather than using 8 pins we will use just three * and an additional chip. * * For more information on this circuit http://tinyurl.com/111111/ * *///Pin Definitions//The 74HC595 using a protocol called SPI (for more details http://www.arduino.cc/en/Tutorial/ShiftOut)//Which has three pinsint data = 2; int clock = 3;int latch = 4;//Used for single LED manipulationint ledState = 0;const int ON = HIGH;const int OFF = LOW; /* * setup() - this function runs once when you turn your Arduino on * We set the three control pins to outputs */void setup(){ pinMode(data, OUTPUT); pinMode(clock, OUTPUT); pinMode(latch, OUTPUT); }/* * loop() - this function will start after setup finishes and then repeat * we set which LEDs we want on then call a routine which sends the states to the 74HC595 */void loop() // run over and over again{ int delayTime = 100; //the number of milliseconds to delay between LED updates for(int i = 0; i < 256; i++){ updateLEDs(i); delay(delayTime); }}/* * updateLEDs() - sends the LED states set in ledStates to the 74HC595 * sequence */void updateLEDs(int value){ digitalWrite(latch, LOW); //Pulls the chips latch low shiftOut(data, clock, MSBFIRST, value); //Shifts out the 8 bits to the shift register digitalWrite(latch, HIGH); //Pulls the latch high displaying the data}/* * updateLEDsLong() - sends the LED states set in ledStates to the 74HC595 * sequence. Same as updateLEDs except the shifting out is done in software * so you can see what is happening. */ void updateLEDsLong(int value){ digitalWrite(latch, LOW); //Pulls the chips latch low for(int i = 0; i < 8; i++){ //Will repeat 8 times (once for each bit) int bit = value & B10000000; //We use a "bitmask" to select only the eighth //bit in our number (the one we are addressing this time through value = value << 1; //we move our number up one bit value so next time bit 7 will be //bit 8 and we will do our math on it if(bit == 128){digitalWrite(data, HIGH);} //if bit 8 is set then set our data pin high else{digitalWrite(data, LOW);} //if bit 8 is unset then set the data pin low digitalWrite(clock, HIGH); //the next three lines pulse the clock pin delay(1); digitalWrite(clock, LOW); } digitalWrite(latch, HIGH); //pulls the latch high shifting our data into being displayed}//These are used in the bitwise math that we use to change individual LEDs//For more details http://en.wikipedia.org/wiki/Bitwise_operationint bits[] = {B00000001, B00000010, B00000100, B00001000, B00010000, B00100000, B01000000, B10000000};int masks[] = {B11111110, B11111101, B11111011, B11110111, B11101111, B11011111, B10111111, B01111111};/* * changeLED(int led, int state) - changes an individual LED * LEDs are 0 to 7 and state is either 0 - OFF or 1 - ON */ void changeLED(int led, int state){ ledState = ledState & masks[led]; //clears ledState of the bit we are addressing if(state == ON){ledState = ledState | bits[led];} //if the bit is on we will add it to ledState updateLEDs(ledState); //send the new LED state to the shift register }And upload this will cause the lights to light up one after another and then off in a similar manner. Check the code and wikipedia to see how it works, or shoot us an e-mail if you have questions.
More Animations:
Now things get more interesting. If you look back to the code from CIRC02 (8 LED Fun) you see we change the LEDs using digitalWrite(led, state), this is the same format as the routine we wrote changeLED(led, state). You can use the animations you wrote for CIRC02 by copying the code into this sketch and changing all the digitalWrite()'s to changeLED()'s. Powerful? Very. (you'll also need to change a few other things but follow the compile errors and it works itself out)
.:Music:. - (Pieze Element) - CIRC06
What We're Doing:
To this point we have controlled light, motion, and electrons, Lets tackle sound next. But sound is an analog phenomena, how will our digital Arduino cope? We will once again rely on its incredible speed which will let it mimic analog behavior. To do this, we will attach a piezo element to one of the Arduino's digital pins. A piezo element makes a clicking sound each time it is pulsed with current. If we pulse it at the right frequency (for example 440 times a second to make the note middle A) these clicks will run together to produce notes. Lets get to experimenting with it and get your Arduino playing 'Twinkle Twinkle Little Star'.
(you can also download the breadboard layout sheet from the bottom of this step)
The Parts:
- CIRC-06 Breadboard Sheet
- 2 Pin Header (x4)
- Piezo Element (x1)
- Wire
The Circuit and Plugging Everything In:
A Small Video of Everything Being Plugged in
The Code: - File > Sketchbook > Examples > Digital > Melody
/* Melody * (cleft) 2005 D. Cuartielles for K3 * * This example uses a piezo speaker to play melodies. It sends * a square wave of the appropriate frequency to the piezo, * generating the corresponding tone. * * The calculation of the tones is made following the * mathematical operation: * * timeHigh = period / 2 = 1 / (2 * toneFrequency) * * where the different tones are described as in the table: * * note frequency period timeHigh * c 261 Hz 3830 1915 * d 294 Hz 3400 1700 * e 329 Hz 3038 1519 * f 349 Hz 2864 1432 * g 392 Hz 2550 1275 * a 440 Hz 2272 1136 * b 493 Hz 2028 1014 * C 523 Hz 1912 956 * * http://www.arduino.cc/en/Tutorial/Melody */ int speakerPin = 9;int length = 15; // the number of noteschar notes[] = "ccggaagffeeddc "; // a space represents a restint beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };int tempo = 300;void playTone(int tone, int duration) { for (long i = 0; i < duration * 1000L; i += tone * 2) { digitalWrite(speakerPin, HIGH); delayMicroseconds(tone); digitalWrite(speakerPin, LOW); delayMicroseconds(tone); }}void playNote(char note, int duration) { char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' }; int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 }; // play the tone corresponding to the note name for (int i = 0; i < 8; i++) { if (names[i] == note) { playTone(tones[i], duration); } }}void setup() { pinMode(speakerPin, OUTPUT);}void loop() { for (int i = 0; i < length; i++) { if (notes[i] == ' ') { delay(beats[i] * tempo); // rest } else { playNote(notes[i], beats[i] * tempo); } // pause between notes delay(tempo / 2); }}
Not Working?
- No Sound - Given the size and shape of the piezo element it is easy to miss the right holes on the breadboard. Try double checking its placement.
- Can't Think While the Melody is Playing. - Just pull up the piezo element whilst you think, upload your program then plug it back in.
- Tired of Twinkle Twinkle Little Star? - The code is written so you can easily add your own songs, check out the code below to get started.
Making it Better:
Playing with the speed:
The timing for each note is calculated based on variables, as such we can tweak the sound of each note or the timing. To change the speed of the melody you need to change only one line.
int tempo = 300; ---> int tempo = (new #)Change it to a larger number to slow the melody down, or a smaller number to speed it up.
Tuning the notes:
If you are worried about the notes being a little out of tune this can be fixed as well. The notes have been calculated based on a formula in the comment block at the top of the program. But to tune individual notes just adjust their values in the tones[] array up or down until they sound right. (each note is matched by its name in the names[] (array ie. c = 1915 )
char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };Composing your own melodies:
The program is pre-set to play 'Twinkle Twinkle Little Star' however the way it is programmed makes changing the song easy. Each song is defined in one int and two arrays, the int length defines the number of notes, the first array notes[] defines each note, and the second beats[] defines how long each note is played. Some Examples:
Twinkle Twinkle Little Star
int length = 15; char notes[] = "ccggaagffeeddc "; int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };Happy Birthday (first line)
int length = 13; char notes[] = "ccdcfeccdcgf "; int beats[] = {1,1,1,1,1,2,1,1,1,1,1,2,4};
Downloads
.:Button Pressing:. (Pushbuttons) - CIRC07
What We're Doing:
Up to this point we have focused entirely on outputs, time to get our Arduino to listen, watch and feel. We'll start with a simple pushbutton. Wiring up the pushbutton is simple. There is one component, the pull up resistor, that might seem out of place. This is included because an Arduino doesn't sense the same way we do (ie button pressed, button unpressed). Instead it looks at the voltage on the pin and decides whether it is HIGH or LOW. The button is set up to pull the Arduino's pin LOW when it is pressed, however, when the button is unpressed the voltage of the pin will float (causing occasional errors). To get the Arduino to reliably read the pin as HIGH when the button is unpressed, we add the pull up resistor.
(note: the first example program uses only one of the two buttons)
(you can also download the breadboard layout sheet from the bottom of this step)
The Parts:
- CIRC-07 Breadboard Sheet
- 2 Pin Header (x4)
- Pushbutton (x2)
- 10k ohm Resistor (brown-black-red) (x2)
- 560 ohm Resistor (green-blue-brown) (x2)
- 5mm Red LED (x1)
The Circuit and Plugging Everything In:
A Small Video of Everything Being Plugged in
The Code: - File > Sketchbook > Examples > Digital > Button
/* * Button * by DojoDave <http://www.0j0.org> * * Turns on and off a light emitting diode(LED) connected to digital * pin 13, when pressing a pushbutton attached to pin 7. * * http://www.arduino.cc/en/Tutorial/Button */ int ledPin = 13; // choose the pin for the LEDint inputPin = 2; // choose the input pin (for a pushbutton)int val = 0; // variable for reading the pin statusvoid setup() { pinMode(ledPin, OUTPUT); // declare LED as output pinMode(inputPin, INPUT); // declare pushbutton as input}void loop(){ val = digitalRead(inputPin); // read input value if (val == HIGH) { // check if the input is HIGH digitalWrite(ledPin, LOW); // turn LED OFF } else { digitalWrite(ledPin, HIGH); // turn LED ON }}
Not Working?
- Light Not Turning On - The pushbutton is square and because of this it is easy to put it in the wrong way. Give it a 90 degree twist and see if it starts working.
- Light Not Fading - A bit of a silly mistake we constantly made, when you switch from simple on off to fading remember to move the LED wire from pin 13 to pin 9
- Underwhelmed? - No worries these circuits are all super stripped down to make playing with the components easy, but once you throw them together the sky is the limit.
Making it Better:
On button off button:
The initial example may be a little underwhelming (ie. I don't really need an Arduino to do this), lets make it a little more complicated. One button will turn the LED on the other will turn the LED off. Change the code to.
int ledPin = 13; // choose the pin for the LEDint inputPin1 = 3; // button 1int inputPin2 = 2; // button 2void setup() { pinMode(ledPin, OUTPUT); // declare LED as output pinMode(inputPin1, INPUT); // make button 1 an input pinMode(inputPin2, INPUT); // make button 2 an input}void loop(){ if (digitalRead(inputPin1) == LOW) { digitalWrite(ledPin, LOW); // turn LED OFF } else if (digitalRead(inputPin2) == LOW) { digitalWrite(ledPin, HIGH); // turn LED ON }}Upload the program to your board, and start toggling the LED on and off.
Fading up and down:
Lets use the buttons to control an analog signal. To do this you will need to change the wire connecting the LED from pin 13 to pin 9, also change this in code.
int ledPin = 13; ----> int ledPin = 9;Next change the loop() code to read.
int value = 0;void loop(){ if (digitalRead(inputPin1) == LOW) { value--; } else if (digitalRead(inputPin2) == LOW) { value++; } value = constrain(value, 0, 255); analogWrite(ledPin, value); delay(10);}Changing Fade Speed:
If you would like the LED to fade faster or slower, there is only one line of code that needs changing;
delay(10); ----> delay(new #);To fade faster make the number smaller, slower requires a larger number.
.:Twisting:. (Potentiometers) - CIRC08
What We're Doing:
Along with the digital pins the Arduino has it also has 6 pins which can be used for analog input. These inputs take a voltage (from 0 to 5 volts) and convert it to a digital number between 0 (0 volts) and 1024 (5 volts) (10 bits of resolution). A very useful device that exploits these inputs is a potentiometer (also called a variable resistor). When it is connected with 5 volts across its outer pins the middle pin will read some value between 0 and 5 volts dependent on the angle to which it is turned (ie. 2.5 volts in the middle). We can then use the returned values as a variable in our program.
(you can also download the breadboard layout sheet from the bottom of this step)
The Parts:
- CIRC-08 Breadboard Sheet
- 2 Pin Header (x4)
- Potentiometer (10k ohm) (x1)
- 5mm Green LED (x1)
- 560 ohm Resistor (green-blue-brown) (x1)
- Wire
The Circuit and Plugging Everything In:
A Small Video of Everything Being Plugged in
The Code: - File > Sketchbook > Examples > Analog > AnalogInput
/* * AnalogInput * by DojoDave <http://www.0j0.org> * * Turns on and off a light emitting diode(LED) connected to digital * pin 13. The amount of time the LED will be on and off depends on * the value obtained by analogRead(). In the easiest case we connect * a potentiometer to analog pin 2. * * http://www.arduino.cc/en/Tutorial/AnalogInput */int potPin = 2; // select the input pin for the potentiometerint ledPin = 13; // select the pin for the LEDint val = 0; // variable to store the value coming from the sensorvoid setup() { pinMode(ledPin, OUTPUT); // declare the ledPin as an OUTPUT}void loop() { val = analogRead(potPin); // read the value from the sensor digitalWrite(ledPin, HIGH); // turn the ledPin on delay(val); // stop the program for some time digitalWrite(ledPin, LOW); // turn the ledPin off delay(val); // stop the program for some time}
Not Working?
- Sporadically Working -This is most likely due to a slightly dodgy connection with the potentiometer's pins. This can usually be conquered by taping the potentiometer down.
- The Control is Backward - There are two ways to fix this, either switch the red and black wires connected to the potentiometer, or turn the potentiometer around. (sorry sometimes the factory ships us a backwards potentiometer)
- Still Backward - You can try operating the circuit upside down. Sometimes this helps.
Making it Better:
Threshold Switching:
Sometimes you will want to switch an output when a value exceeds a certain threshold. To do this with a potentiometer change the loop() code to.
void loop() { int threshold = 512; if(analogRead(potPin) > threshold){ digitalWrite(ledPin, HIGH);} else{ digitalWrite(ledPin, LOW);}}This will cause the LED to turn on when the value is above 512 (about halfway), you can adjust the sensitivity by changing the threshold value.
Fading:
Lets control the brightness of an LED directly from the potentiometer. To do this we need to first change the pin the LED is connected to. Move the wire from pin 13 to pin 9 and change one line in the code.
int ledPin = 13; ----> int ledPin = 9;Then change the loop code to.
void loop() { int value = analogRead(potPin) / 4; analogWrite(ledPin, value); }Upload the code and watch as your LED fades in relation to your potentiometer spinning. (Note: the reason we divide the value by 4 is the analogRead() function returns a value from 0 to 1024 (10 bits), and analogWrite() takes a value from 0 to 255 (8 bits) )
Controlling a Servo:
This is a really neat example and brings a couple of circuits together. Wire up the servo like you did in CIRC-04, then open the example program Knob (File > Sketchbook > Examples > Library-Servo > Knob ), then change one line of code.
int potpin = 0; ----> int potpin = 2;Upload to your Arduino and then watch as the servo shaft turns as you turn the potentiometer.
Downloads
.:Light:. (Photo Resistors) - CIRC09
What We're Doing:
Whilst getting input from a potentiometer can be useful for human controlled experiments, what do we use when we want an environmentally controlled experiment? We use exactly the same principles but instead of a potentiometer (twist based resistance) we use a photo resistor (light based resistance). The Arduino cannot directly sense resistance (it senses voltage) so we set up a voltage divider ( http://tinyurl.com/2sunta ). The exact voltage at the sensing pin is calculable, but for our purposes (just sensing relative light) we can experiment with the values and see what works for us. A low value will occur when the sensor is well lit while a high value will occur when it is in darkness.
(you can also download the breadboard layout sheet from the bottom of this step)
The Parts:
- CIRC-09 Breadboard Sheet
- 2 Pin Header (x4)
- Photo-Resistor (x1)
- 5mm Green LED (x1)
- 10k ohm Resistor (brown-black-orange) (x1)
- 560 ohm Resistor (green-blue-brown) (x1)
- Wire
The Circuit and Plugging Everything In:
A Small Video of Everything Being Plugged in
The Code: - http://tinyurl.com/crdum6''
/* * A simple programme that will change the * intensity of an LED based on the amount of * light incident on the photo resistor. * *///PhotoResistor Pinint lightPin = 0; //the analog pin the //photoresistor is //connected to //the photoresistor is not //calibrated to any units so //this is simply a raw sensor value (relative light)//LED Pinint ledPin = 9;//the pin the LED is connected to //we are controlling brightness so //we use one of the PWM (pulse //width modulation pins)void setup(){ pinMode(ledPin, OUTPUT); //sets the led pin to //output} /* * loop() - this function will start after setup * finishes and then repeat */void loop(){ int lightLevel = analogRead(lightPin); //Read the // lightlevel lightLevel = map(lightLevel, 0, 900, 0, 255); //adjust the value 0 to 900 to lightLevel = constrain(lightLevel, 0, 255); //make sure the value is betwween 0 and 255 analogWrite(ledPin, lightLevel); //write the value}
Not Working?
- LED is Remaining Dark - This is a mistake we continue to make time and time again, if only they could make an LED that worked both ways. Pull it up and give it a twist.
- It Isn't Responding to Changes in Light. - Given that the spacing of the wires on the photo-resistor is not standad, it is easy to misplace it. Double check its in the right place
- Still not quite working? - You may be in a room which is either too bright or dark. Try turning the lights on or off to see if this helps. Or if you have a flashlight near by give that a try.
Making it Better:
Reverse the response:
Perhaps you would like the opposite response. Don't worry we can easily reverse this response just change.
analogWrite(ledPin, lightLevel); ----> analogWrite(ledPin, 255 - lightLevel);Upload and watch the response change.
Night light:
Rather than controlling the brightness of the LED in response to light, lets instead turn it on or off based on a threshold value. Change the loop() code with.
void loop(){ int threshold = 300; if(analogRead(lightPin) > threshold){ digitalWrite(ledPin, HIGH); }else{ digitalWrite(ledPin, LOW); }}
Light controlled servo:
Lets use our newly found light sensing skills to control a servo (and at the same time engage in a little bit of Arduino code hacking). Wire up a servo connected to pin 9 (like in CIRC-04). Then open the Knob example program (the same one we used in CIRC-08) File > Sketchbook > Examples > Library-Servo > Knob. Upload the code to your board and watch as it works unmodified.
Using the full range of your servo:
You'll notice that the servo will only operate over a limited portion of its range. This is because with the voltage dividing circuit we use the voltage on analog pin 0 will not range from 0 to 5 volts but instead between two lesser values (these values will change based on your setup). To fix this play with the val = map(val, 0, 1023, 0, 179); line. For hints on what to do visit http://arduino.cc/en/Reference/Map .
.:Temperature:. (TMP36 Precision Temperature Sensor) - CIRC10
What We're Doing:
What's the next phenomena we will measure with our Arduino? Temperature. To do this we'll use a rather complicated IC (integrated circuit) hidden in a package identical to our P2N2222AG transistors. It has three pins ground, signal and +5 volts, and is easy to use. It outputs 10 millivolts per degree centigrade on the signal pin (to allow measuring temperatures below freezing there is a 500 mV offset eg. 25 degrees C = 750 mV, 0degrees C = 500mV). To convert this from the digital value to degrees we will use some of the Arduino's maths abilities. Then to display it we'll use one of the IDE's rather powerful features, the debug window. We'll output the value over a serial connection to display on the screen. Let's get to it.
One extra note, this circuit uses the Arduino IDE's serial monitor. To open this, first upload the program then click the button which looks like a square with an antennae.
The TMP36 Ddatasheet:
http://tinyurl.com/plbx38
(you can also download the breadboard layout sheet from the bottom of this step)
The Parts:
- CIRC-10 Breadboard Sheet
- 2 Pin Header (x4)
- Temperature Sensor (TMP36) (x1)
- Wire
The Circuit and Plugging Everything In:
A Small Video of Everything Being Plugged in
The Code: - http://tinyurl.com/dfj8rs
/* --------------------------------------------- * | Arduino Experimentation Kit Example Code | * | CIRC-10 .: Temperature :. | * --------------------------------------------- * * A simple program to output the current temperature * to the IDE's debug window * For more details on this circuit: * http://tinyurl.com/c89tvd *///TMP36 Pin Variablesint temperaturePin = 0;//the analog pin the TMP36's //Vout pin is connected to //the resolution is //10 mV / degree centigrade //(500 mV offset) to make //negative temperatures an optionvoid setup(){ Serial.begin(9600); //Start the serial connection //with the copmuter //to view the result open the //serial monitor //last button beneath the file //bar (looks like a box with an //antenae)} void loop() // run over and over again{ float temperature = getVoltage(temperaturePin); //getting the voltage reading from the //temperature sensortemperature = (temperature - .5) * 100;//converting from 10 mv //per degree wit 500 mV offset to //degrees ((volatge - 500mV) times 100) Serial.println(temperature); //printing the result delay(1000); //waiting a second}/* * getVoltage() - returns the voltage on the analog input * defined by pin */float getVoltage(int pin){ return (analogRead(pin) * .004882814);//converting from a 0 //to 1024 digital range // to 0 to 5 volts //(each 1 reading equals ~ 5 millivolts}
Not Working?
- Nothing Seems to Happen - This program has no outward indication it is working. To see the results you must open the Arduino IDE's serial monitor.
- Gibberish is Displayed - This happens because the serial monitor is receiving data at a different speed than expected. To fix this, click the pull-down box that reads "*** baud" and change it to "9600 baud".
- Temperature Value is Unchanging. - Try pinching the sensor with your fingers to heat it up or pressing a bag of ice against it to cool it down.
Making it Better:
Outputting voltage:
This is a simple matter of changing one line. Our sensor outputs 10mv per degree centigrade so to get voltage we simply display the result of getVoltage().
delete the line temperature = (temperature - .5) * 100;
Outputting degrees Fahrenheit:
Again this is a simple change requiring only math. to go degrees C ----> degrees F we use the formula.
( F = C * 1.8) + 32 )
add the line
temperature = (((temperature - .5) * 100)*1.8) + 32; before Serial.println(temperature);More informative output:
Lets add a message to the serial output to make what is appearing in the Serial Monitor more informative. To do this first revert to the original code then change:
Serial.println(temperature); ----> Serial.print(temperature); Serial.println(" degrees centigrade");The change to the first line means when we next output it will appear on the same line, then we add the informative text and a new line.
Changing the serial speed:
If you ever wish to output a lot of data over the serial line time is of the essence. We are currently transmitting at 9600 baud but much faster speeds are possible. To change this change the line:
Serial.begin(9600); ----> Serial.begin(115200);Upload the sketch turn on the serial monitor, then change the speed from 9600 baud to 115200 baud in the pull down menu. You are now transmitting data 12 times faster.
Downloads
.:Larger Loads:. (Relays) - CIRC11
What We're Doing:
The final circuit is a bit of a test. We combine what we learned about using transistors in CIRC03 to control a relay. A relay is an electrically controlled mechanical switch. Inside the little plastic box is an electromagnet that, when energized, causes a switch to trip (often with a very satisfying clicking sound). You can buy relays that vary in size from a quarter of the size of the one in this kit up to as big as a fridge, each capable of switching a certain amount of current. They are immensely fun because there is an element of the physical to them. While all the silicon we've played with to this point is fun sometimes you just want to wire up a hundred switches to control something magnificent. Relays give you the ability to dream it up then control it with your Arduino. Now to using todays technology to control the past. (The 1N4001 diode is acting as a flyback diode for details on why its there visit: http://tinyurl.com/b559mx)
(you can also download the breadboard layout sheet from the bottom of this step)
The Parts:
- CIRC-11 Breadboard Sheet
- 2 Pin Header (x4)
- Transistor (P2N2222AG) (x1)
- Relay (DPDT) (x1)
- 2.2k ohm Resistor (red-red-red) (x1)
- 560 ohm Resistor (red-red-red) (x2)
- 5mm Red LED (x1)
- 5mm Green LED (x1)
- Diode (1n4001) (x1)
The Circuit and Plugging Everything In:
A Small Video of Everything Being Plugged in
The Code: - File > Sketchbook > Examples > Digital > Blink
/* * Blink * * The basic Arduino example. Turns on an LED on for one second, * then off for one second, and so on... We use pin 13 because, * depending on your Arduino board, it has either a built-in LED * or a built-in resistor so that you need only an LED. * * http://www.arduino.cc/en/Tutorial/Blink */int ledPin = 2; // *********** CHANGE TO PIN 2 ************void setup() // run once, when the sketch starts{ pinMode(ledPin, OUTPUT); // sets the digital pin as output}void loop() // run over and over again{ digitalWrite(ledPin, HIGH); // sets the LED on delay(1000); // waits for a second digitalWrite(ledPin, LOW); // sets the LED off delay(1000); // waits for a second}
Not Working?
- Nothing Happens - The example code uses pin 13 and we have the relay connected to pin 2. Make sure you made this change in the code.
- No Clicking Sound - The transistor or coil portion of the circuit isn't quite working. Check the transistor is plugged in the right way.
- Not Quite Working - The included relays are designed to be soldered rather than used in a breadboard. As such you may need to press it in to ensure it works. (and it may pop out occasionally)
Making it Better:
Controlling a Motor
In CIRC-03 we controlled a motor using a transistor. However if you want to control a larger motor a relay is a good option. To do this simply remove the red LED, and connect the motor in its place (remember to bypass the 560 Ohm resistor)
Controlling Motor Direction
A bit of a complicated improvement to finish. To control the direction of spin of a DC motor we must be able to reverse the direction of current flow through it. To do this manually we reverse the leads. To do it electrically we require something called an h-bridge. This can be done using a DPDT relay to control the motor's direction, wire up the circuit below (DPDT Relay H-Bridge).
It looks complicated but can be accomplished using only a few extra wires. Give it a try.