http://sites.schaltungen.at/arduino-uno-r3/anleitung-tutorial/ladyada Ladyada's Learn Arduino - Lesson #0Wels, am 2017-02-08BITTE nützen Sie doch rechts OBEN das Suchfeld [ ] [ Diese Site durchsuchen]DIN A3 oder DIN A4 quer ausdrucken
*******************************************************************************I** DIN A4 ausdrucken siehe http://sites.schaltungen.at/drucker/sites-prenninger
********************************************************I* 015_b_PrennIng-a_arduino.uno.r3-anleitung.tutorial-ladyada (xx Seiten)_1a.pdfUntergeordnete Seiten (12):
704_d_ARDUINO-x_LadyAdas learn-arduino lesson-#0_1a.pdf
https://www.arduino.cc/en/Tutorial/HomePage http://www.ladyada.net/learn/arduino/ Starter Pack for Arduino (Includes Arduino Uno R3)https://www.adafruit.com/products/68It includes:
http://www.ladyada.net/learn/arduino/lesson4.html
Lady Ada Tutorial Lesson Plan
Follow these lessons for happiness and prosperity. Intro
Starting
Arduino Ethernet+SD
Buy stuff Für jeden, des sich ganz langsam an die Basics herantasten möchte, kann ich die deutsche Übersetzung des Lady Ada Tutorials empfehlen. http://www.ladyada.net/learn/arduino/index.html http://www.arduino.cc/playground/uploads/Main/arduino_notebook_v1-1.pdf
Intro Introduction
So, I get two or three emails a day, all basically asking the same thing: "Where can I learn about electronics?" In general, most of these people have seen some of my projects and want to be able to build similar things. Unfortunately, I have never been able to point them to a good site that really takes the reader through a solid introduction to microcontrollers and basic electronics. UNTIL NOW!!!
Goes well with: Arduino Starter Pack and a nice Merlot
I designed this tutorial course to accompany the Arduino starter pack sold at the Adafruit webshop. The pack contains all the components you need (minus any tools) for the lessons
Tools
Here are some recommended tools:
If you need to get any soldering done, you may also want....
Share and Enjoy!
All of the content in the Arduino Tutorial is CC 2.5 Share-Alike Attrib.
You can use the text and pictures all you want, providing you do all the hosting, and indicate the attribution like: "This tutorial is by Limor Fried and from http://www.ladyada.net/learn/arduino". Thanks! Love it? Hate it? See a mistake? Post it to the forums!
Credits and other links
To some extent, the structure of the material borrows from:
The impressively good "What's a microcontroller?" book (& now PDF) by Parallax. It's for BASIC Stamps but is still a good read even if you don't plan to use Stamps.
"Spooky Arduino" - Todbot's excellent (if fast-paced!) class on Arduino projects for Halloween.
Starting Goes well with: Arduino Starter Pack and a nice Merlot
I designed this tutorial course to accompany the Arduino starter pack sold at the Adafruit webshop. The pack contains all the components you need (minus any tools) for lessons 0-10. If people like this system, I will add another pack for another half-dozen lessons, numbers 11+
Tools are not included in the starter pack, but you probably have a few of these tools kicking around the house. Ask a friend if you can borrow them?
If you need to get any soldering done, you may also want....
You'll want to solder up your protoshield and 9V battery holder. The protoshield instructions are here. Some older kits came with the 9V holder and plug not connected. The 9V instructions follow! Learn how to solder by looking here, if you don't know how. Start by unscrewing the plastic cover from the barrel plug Thread the barrel cover onto the red and black wires so that the round part is near the pack itself, see the image below Use a pair of pliers (or your fingernails) to make little hooks out of the ends of the red and black wires.
Place the 2.1mm barrel plug in a vise or 3rd hand tool to keep it steady. Hook the red wire onto the middle tab and the black wire to the outer tab as shown. Then bend the hooks over all the way so that the wires can't come loose while you solder Solder both hooks to the tabs with a touch of solder. Make sure you heat the black wire tab well as its large enough that it may take a moment for the solder to melt onto the tab well. Sometimes the plug doesn't have a little tab, instead there is a cyclindrical tab in the center. In that case, poke the red wire inside the cylinder and solder it there, you don't need to crimp it. The black wire sill still go on the larger outer tab
Make sure the soldering is neat, the two wires should not be poking out.
Gently pull the red wire towards the black wire and bend over the tabs so that they hold the two wires together. Don't crimp them too tightly or the tab can/will cut into the red wire. Just make sure its snug. Now screw the plug cover on to protect the connector You should probably use your multimeter to test continuity between the inner conductor and the outer conductor to make sure they are not shorted. A tutorial on how to do this is here.
Lesson 0
https://learn.adafruit.com/ladyadas-learn-arduino-lesson-number-0 Lesson 1 Introduction Ah yes, it is finally time to make your Arduino do something! We're going to start with the classic hello world! of electronics, a blinking light.
This lesson will basically get you up and running using the Arduino software and uploading a sketch to the Arduino board. Once you've completed this step we can continue to the really exciting stuff, which is when we start writing our own sketches! These instructions mostly show Windows software. Except when indicated, the software (should be) identical on all platforms. Linux will be added once I figure out how to get it working (yay)
Do you have everything you need?
Not much is needed for this lesson, just a USB cable and an Arduino.If you have an older Arduino you may also need an LED. Any LED is fine as long as it looks sorta like the photo, with a plastic bulb and two legs Make sure you've gone through Lesson 0 first!
Download the Software
The first thing to do is download the Arduino software.
Go to the Arduino Software Download page and grab the right file for your OS. As of Sept 2007 the version is 009 but you should use whatever is most recent. The packages are quite large, 30-50 MB so it may take a while to finish
Unpack and Install
Extract the package onto the Desktop
Startup!
Double click the Arduino software icon
To open up the workspace
I think I get the red error text shown because I already have Arduino installed. Either way, it isn't a problem if you do or don't see it.
Select chip
The first step is to configure the Arduino software for the correct chip. Almost all Arduinos use the ATmega168, but there's a chance you have an ATmega8. Look for the chip on the Arduino that looks like this:
If the text says ATMEGA8-16P then you have an atmega8 chip. If the text says ATMEGA168-20P then you have an atmega168 chip. If it says "ATMEGA328P-20P" you have an atmega328p chip
Make sure the correct chip is selected (this picture is really old, will be fixed soon). This preference is saved so you only have to set it once, the program will remember next time it's run.
Select port
Next, its time to configure the Serial Port (also known as the COM Port). Go back to lesson 0 to remind yourself of which port it is. On a PC it will probably be something like COM3 or COM4. On a Mac it will be something like tty.usbserial-xxxxx
This preference is saved so you only have to set it once, the program will remember next time it's run.
However, if you have multiple Arduino's, they may be assigned difference COM ports. So every time you plug in a new Arduino, double check that the correct port is selected.
Open blink sketch
Sketches are little scripts that you can send to the Arduino to tell it how to act. Let's open up an Example Sketch. Go to the File menu -> Sketchbook -> Examples -> Digital -> Blink
The window should now look like this, with a bunch of text in the formerly empty white space and the tab Blink above it
Verify / Compile
The first step to getting a Sketch ready for transfer over to the arduino is to Verify/Compile it. That means check it over for mistakes (sort of like editing) and then translate it into an application that is compatible with the Arduino hardware.
After a few seconds, you should see the message Done compiling. in the Status Bar and Binary Sketch Size: in the Notification area. This means the sketch was well-written and is ready for uploading to the Arduino board!
Reset (NG only)
To tell the Arduino that it should prepare itself for a new Sketch upload, you must reset the board.
Diecimila Arduino's have built-in auto-reset capability, so you don't need to do anything.
Older Arduinos, such as NG, must be manually reset before uploading a sketch. To do that simply press the black button on the right hand side of the board, shown here.
Upload
Now it's time to upload. Make sure the Arduino is plugged in, the green light is on and the correct Serial Port is selected. If you have an NG Arduino, press the Reset Button now, just before you select the Upload menu item. Select Upload to I/O Board from the File menu
After a few seconds you should get this screen, with the message Done uploading. in the status bar.
If you get the following error message "avrdude: stk500_getsync(): not in sync: resp=0x00" that means that the Arduino is not responding
Then check the following:
If you get the following error message: It means you dont have a serial port selected, go back and verify that the correct driver is installed (lesson 0) and that you have the correct serial port selected in the menu. If you get the following error Expected signature for ATMEGA
Then you have either the incorrect chip selected in the Tools menu or the wrong bootloader burned onto the chip If you get the following error: can't open device "COM10": The system cannot find the file specified (under Windows, COM port value may vary)
It means that you have too many COM ports (maybe you've got 9 Arduinos?)
You should make sure that the port is numbered as low as possible.
You can use a program like FTClean to clear out old COM ports you aren't using anymore.
Once you've cleaned out the ports, you'll have to reinstall the driver again (see lesson 0). Select the USB device in the Device Manager, right click and select Properties
Then click Advanced... and in the next window change the COM port to something like COM4 or COM5.
Don't forget to select the new port name in the Arduino software.
The lower port names may say (in use) but as long as the other USB devices aren't plugged in, it shouldn't be a problem. This is a little riskier than just using FTClean...
Video of all steps
Here is a video showing the timing of the steps described so far.
Insert LED (NG Arduinos)
Some older Arduinos don't have a built in LED, its easy to tell if yours does or not If you have a Diecimila or other Arduino with a built in LED you will see a translucent part as shown
If you have an NG rev C or other Arduino without an LED, the translucent part will not be there, and instead you will see two silver dots
If you don't have an LED, you'll need to add your own. Any LED will do, as long as it has two legs and kinda looks like the one shown here.
LEDs are directional components. That means if you put it in backwards it will not work!
To help you put the LED in right, the LED factory cuts the legs at different lengths. The longer leg goes in the hole marked 13 and the shorter one goes in the hole marked GND
Watch!
If you have a Diecimila Arduino, the upload process is quite fast, just start the Upload from the software.
The board will automatically reset itself, transfer the sketch and start the sketch. The little translucent LED will start blinking Lesson 2 Introduction
OK you've gotten your Arduino set up and also figured out how to use the software to send sketches to the board. Next step is to start writing your own sketches. We'll start off easy by just modifying something that already works. To start we will venture deep into the Blink sketch, looking at each line and trying to understand what its doing. Then we will start hacking the sketch!
Blinkie
Start up the Arduino software and open the Blink example sketch, as you did in Lesson 1.
The sketch itself is in the text input area of the Arduino software. Sketches are written in text, just like a document. When you select Compile/Verify from the menu, the Arduino software looks over the document and translates it to Arduino-machine-language - which is not human-readable but is easy for the Arduino to understand. Sketches themselves are written in C, which is a programming language that is very popular and powerful. It takes a bit of getting used to but we will go through these examples slowly.
Comments
Lets examine this sketch in detail starting with the first section:
This is a comment, it is text that is not used by the Arduino, its only there to help humans like us understand whats going on. You can tell if something is a comment because there is a /* at the beginning and a */ at the end. Anything between the /* and */ is ignored by the Arduino.
In this example the person who wrote the comment decided to make it look pretty and add *'s down the side but this isn't necessary.
Variables
Lets look at the next line:
This is the first line of actual instruction code. It is also extremely unlike English (or any other human language).
The first part we can easily understand is the part to the right, which is also a comment. Turns out if you want to make a small comment, you can use // as well as /* */. // is often used for short, one line comments.
The rest of the line, the stuff before the //, is what is called a statement, which is basically like a computerized sentence. Much like human sentances end with a . (period), all computer sentences end with a ; (semicolon) OK all we have left is the statement itself, which turns out to be a sentence telling the computer that we would like it to create a box named ledPin and to put the number 13 in that box. If you remember your math, you may recall that the box is also known as variable.
The first part of this sentence is int, which is short for integer which is a fancy way of saying whole number
Procedures
Lets move on to the next section void setup() // run once, when the sketch starts{ pinMode(ledPin, OUTPUT); // sets the digital pin as output}
OK we've got two comments, each starting with //. We understand comments already so lets skip that.
To better understand procedures, lets use an analogy to the kinds of procedures we're used to clean cat wash the cat(dirty cat) // a procedure for washing the cat{ turn on the shower. find the cat. grab the cat. put cat under shower. wait 3 minutes. // wait for cat to get clean. release cat.}
This is a procedure for washing the cat. The name of the procedure is wash the cat, it uses a dirty cat as the input and returns a clean cat upon success. There are two brackets, an open bracket { and a closed bracket }, thats are used to indicate the beginning and end of the procedure. Inside the procedure are a bunch of statements, indicating the correct procedure for washing a cat. If you perform all of the statements then you should be able to turn a dirty cat into a clean cat.
Looking again at the procedure, we see that it is named setup and it has no input values and it returns void. Now you're probably asking yourself "what is void?" Well thats a computer-scientist way of saying nothing. That is, this procedure doesnt return anything. (That doesnt mean it doesn't do anything, just that it doesn't have a tangible number or whatever, to show when its complete) void setup() // run once, when the sketch starts There is one statment in this procedure, pinMode(ledPin, OUTPUT); // sets the digital pin as output We'll return to this statement in detail later, suffice to say it is a way of telling the Arduino what we would like to do with one of the physical pins on the main processor chip.
Procedure calls
We're onto the next bunch of text. 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}
Using our now well-honed technique we recognize that the text to the right is all comments. We also recognize another procedure, this one called loop which also has no inputs or output. This procedure has multiple statements, one after the other. We're going to skip the first statement for now and go straight to statement #2.
The second and fourth statements are the same, and have something to do with a delay.
This statement is very similar to the "wait 3 minutes." command in our cat-washing procedure.
This statement says "Dear Arduino. Stop what you're doing for a short amount of time. Thanks!" Basically, we want the Arduino to take a break but don't quite know how to do it, lucky for us, someone else wrote a procedure called delay which we can call upon to do the work for us. Kind of like if we need to do our taxes and we dont know how, we call upon an accountant to do it for us, giving them the paperwork input and getting tax return as the result.
This means that somewhere out there, there's a procedure something like this: void delay(number of milliseconds) { "Dear Arduino. Stop what you're doing for (number of milliseconds) amount of time. Thanks!" } Turns out this delay procedure works pretty well, and all we have to do is tell it how many milliseconds (1/1000th of a second) to wait and it will do the job for us.
Returning to the first statment, we see that it is also a procedure call. This time for some procedure called digitalWrite. We'll also skip this one in detail for a bit, except to explain that its turning a pin on the Arduino chip on and off, and that pin is powering the LED so in essence its turning the LED on and off.
Special Procedures - Setup() and Loop()
I do want to mention quickly here that the two procedures we've mentioned so far are extra-special in that when the Arduino first wakes up after being reset, it always does whats in the setup procedure first. Then it does whatever is in the loop procedure over and over and over...forever! Or at least until you turn it off.
Modifying the example
Now that we've analyzed the entire programit's time to make some changes.
In your Arduino software, change the number in the delay procedure calls to 500 (from 1000) as shown void loop() // run over and over again{ digitalWrite(ledPin, HIGH); // sets the LED on delay(500); // waits for a second digitalWrite(ledPin, LOW); // sets the LED off delay(500); // waits for a second} If you try to save the sketch, you'll get the warning that it's read-only.
Not a big deal, you can save it under a new name, such as MyBlink
Compile/Verify the sketch and Upload it, using your Lesson 1 techniques.
Once the Arduino has been updated with the new sketch you should see a faster-blinking light than before If the LED is not blinking faster, check:
Exercises
Now it time for you to make modifications to the sketch and experiment with different delay values
Wrap up
Congrats, you have finished the second lesson!
In this lesson you examined the Blink sketch in detail, and learned a bit of the language used to talk to the Arduino. You also learned how to modify a sketch, and practiced uploading sketches to the Arduino some more. Lesson 3
a
Introduction
You've started modifying sketches, and played a bit with the onboard LED (or if you have an NG, an LED you added).
The next step is to start adding onto the hardware component of the Arduino. We will do this by adding a solderless breadboard to our setup, connecting up new parts with wire.
Get your gear
Say hello to the solderless breadboard!
Solderless breadboards are an important tool in your quest for electronics mastery.
They allow you to make quick circuits, test out ideas before making a more permanent Printed Circuit Board. They're also inexpensive and reusable.. You can pick on up at any hobby shop or electronics supply store. They often look like this
Basically, a chunk of plastic with a bunch of holes. However, something special is going on inside the breadboard! Although you can't see it, inside the breadboard are many strips of metal that connect the rows and columns together. The metal strips are springy so that when you poke a wire into the hole, the clips grab onto it.
In the images above you can see how there are two kinds of metal strips.
There are short ones that connect 5 row holes at a time, and then there are very long ones that connect 25 (or more!) column holes at a time. The long columns are called rails and the short strips are called rows. Breadboards are almost always made so that they have two sets of 5-hole rows and on either side there are a pair of rails. For example the breadboard on the left has 30 row pairs and 2 sets of double rails on either side. The one on the right is quite small, it has only 17 row pairs and no rails.
In this lesson, we will show pictures of both the tiny breadboard on a protoshield and also using a 'standard' breadboard without a shield. However, after this lesson, you'll be more on your own to figure out how to connect up the standard breadboard, OK? Warning!
Distressing as it may sound, solderless breadboards can be very flakey, especially as they age.
If you're having problems with your circuit, it could be that the little metal clips on the inside aren't working well. Try poking it with your finger, or moving it to a different section.
Say hello to wires!
To use the breadboard, you'll need jumper wires. These are basically 22 gauge solid-core (not stranded) wires that are cut down and have the insulation pulled off. You can use a fingernail or, best of all, a real wirestripper tool to remove the insulation, just takes a few tries and then its really easy. Heres how to do it with just diagonal cutters...Cut the wire first, using wire cutters Nick the insulation, then pull it off. To connect rows together, just stick the wire ends without insulation into the square holes! Now is a good time to practice making jumpers, go forth and make a few 3" long jumpers!
Say hello to the resistor!
The resistor is the most basic and also most common electronic part. An electronic gadget, such as an mp3 player has easily a thousand resistors inside of it!
Resistors have one job to do, and that is to resist the flow of electricity (otherwise known as current).
That's why they're called resistors. By resisting current they control where and how fast it flows.
Thin pipes let less water through (high resistance), thick pipes let a lot of water through (low resistance).
Wth a fire hydrant, you want low resistance. With a water fountain, you'd want high resistance. If you mixed up the two pipe sizes, you wouldnt be able to put out a fire and you'd hurt yourself while trying to get a drink.
Resistance is measured in ohms, often written as the symbol Ω. The bigger the resistance value (in ohms) the more it fights.
Most resistors you'll see range between 1 ohm and 1 megaohm (1.0 MΩ).
Since the resistive element is inside a ceramic casing, its not possible to tell the resistance of a resistor just by looking at it.
You'll have to read it by looking at the colored stripes on the body of the resistor.
This is known as the resistor color code, and its a real pain when you first start electronics.
Eventually you'll get really good at telling the value of a resistor just by glance but to start off you'll want to use a reference chart.
(Or you can use a multimeter to measure the resistance accurately) Remember: Just because the stripes are in a certain order doesn't mean the resistor has a direction! Resistors are the same forward and backwards, it doesnt matter which way they are used. Quick quiz!
Note on Wattages....
In all these examples, we use 1/4W resistors.
Unless otherwise noted you can use 1/16 W or 1/2W or whatever you can get your hands on. Higher wattage resistors are larger and usually more expensive, but sometimes your local hobby shop will only have 1/2W.
Say hello to the LED!
We've had some time with the LED already, but lets get to know her a little better.
The word LED stands for Light Emitting Diode. The light-emitting part, well, that makes sense.
We've used the LED to make a blinking light in lessons 1 and 2. The LED component turns current into light, much like any sort of light bulb. But what is this mysterious diode? A diode is basically a one-way street for current. Imagine such a one-way street with a traffic policeman in front. If you want to turn onto the street the wrong way, he will not let you. Likewise the diode simply does not let current go through it the wrong way. Current in a diode can only flow from the positive side to the negative side. If you recall from lesson 1, Arduino NG users had to make sure that they inserted the LED in the right way. If you place the LED in backwards it won't work. Diecimila Arduino users already have the LED (a very very small one) soldered onto the circuit board the right way.
As we mentioned before, its easy to figure out which side of an LED is positive and which one is negative. The positive leg is slightly longer and if you look inside, the chunk of metal is larger on the negaive side.
Light up my breadboard
We're going to now use the breadboard to light up an LED. You will need a breadboard, an LED and a 1.0K ohm resistor (brown black red gold).
If you have a protoshield, make sure its assembled first.
Then, place the tiny breadboard on top. You can remove the backing to stick it on (which is permanent) or you can just use double-sided tape. If you have a regular breadboard you'll need 2 jumper wires as well. Important Note! While LEDs will not work when placed backwards, you don't have to worry about whether it will be damaged: as long as there is a series resistor of at least 100 ohms next to it, the LED will survive the experience!
However, using an LED without a series resistor is a sure-fire way to kill it! (You'll see a bright flash and it may turn dark)
Place the resistor and LED as shown. Make sure the longer leg of the LED is to the right, connected to the resistor. The resistor doesn't have a direction, so it doesnt matter which way it goes in.
If you're using a standard breadboard, you'll need to use wires to reach the Arduino. Run one wire (red) to the 5V socket on the Arduino. Run the other wire (black) to one of the GND sockets on the Arduino. The colors aren't essential but they will help you remember what the wires are connected to! Plug in the Arduino, you should see the LED light up. If not, check the following:
Scheming schematic
Hooray, you just built your first circuit! Its quite simple but still worth explaining.
The positive pin of the LED is connected to the positive terminal of the battery, then the negative pin is connected to a resistor which goes to the negative terminal of the battery. The battery is supplying the current that flows through the LED, making it light up. The positive terminal is called power (as thats where current flows from) and the negative terminal is called ground, as it is where current flows to.
Lets say you want to "save" this design and send it to a friend to check out and build for herself...one way you could do that is to take a good photo.
But a better way is to draw a wiring diagram. Then it wouldn't matter if your camera wasn't very good. A wiring diagram is also known as a schematic.
Schematics are the standard method for people to trade information about circuits. Being able to read and write schematics is a key skill! Here is a schematic for a really big project, a Roland TB-303 synthesizer clone Each electronic component has a schematic symbol, which is a simplified drawing of the part. For resistors the symbol looks like this:
And the symbol for LED's look like this:
You can see that the resistor symbol is symmetric, just like resistors themselves.
The LED symbol, however, has an arrow thing going on. This is the direction in which current flows. The little arrows that are coming out of the symbol indicate that this is a diode that emits light. Power and ground also have symbols:
The only thing we need to do now is indicate how the LED and resistor are hooked up and show the 5V and ground connections.
Next to symbols, we often write important information like what the resistor value is, what color and size the LED should be, and the voltage associated with the power supply.
For practice, try drawing your own schematic on a piece of paper.
A Quick Rewiring...
We're going to make a very small modification to our wired up circuit
In our new schematic, instead of connecting the resistor to +5V power, we'll connect it to ground. You will notice that, in fact, the LED has gone out. That is because it is no longer connected to a power source and current is not flowing. By connecting the resistor to +5V or ground, you can turn the LED on and off. If you were very fast at it, you could make the LED blink! Hmm....
Re-visiting an old friend
Start up the Arduino software again and open up the MyBlink sketch from lesson 2. If you left it with delay times of 10ms, you may want to modify it so its back to 500ms on and 500ms off. Upload the sketch to your Arduino. Now change your breadboard wiring so that it matches this schematic.
That is, instead of connecting the resistor to 5V or ground, connect it to the Arduino pin socket labeled 13. If you have an NG Arduino, you'll need to remove the old LED you used, if its still in the socket. You should see the LED turn on and off. If you have a Diecimila Arduino, both the on-board LED and the wired LED will blink in unison. Lets look at that code again void loop() // run over and over again{ digitalWrite(ledPin, HIGH); // sets the LED on delay(500); // waits for a second digitalWrite(ledPin, LOW); // sets the LED off delay(500); // waits for a second}
We didn't quite explain what digitalWrite does, but now it should be clear: the digitalWrite procedure connects the pin indicated by the first input (ledPin) to either the +5V power supply or to ground depending on the second input (HIGH or LOW)
A new pin
Now change the wiring so that the resistor is connected up to pin socket #12
The LED isn't be blinking anymore! Lets fix it! int ledPin = 13; // LED connected to digital pin 13 This is the line of code that indicates which pin is connected to the LED. Change it so that it is now connected to pin 12 int ledPin = 12; // LED connected to digital pin 12 now!
Re-compile and verify the sketch, then send it over the the Arduino. The LED should now be blinking again. Note that if you have a Diecimila Arduino you will not see any blinking on the on-board LED. Thats because its connected to pin 13 only! Exercises!
Adding a green LED...
OK sure you've had plenty of practice messing around with LEDs. It's time to go full color! Find a red, green and blue LED. If you have the Arduino Starter Pack they will be the three clear LEDs. You can't tell which one is which until they are lit so just build the circuit and then rearrange them if needed.
In this schematic we will have three LEDs connected to three different pins: #10, #11 and #12. Go back to your sketch and change it so it looks like this: int redPin = 12; // Red LED connected to digital pin 12int greenPin = 11; // Green LED connected to digital pin 11void setup() // run once, when the sketch starts{ pinMode(redPin, OUTPUT); // sets the digital pin as output pinMode(greenPin, OUTPUT); // sets the digital pin as output}void loop() // run over and over again{ digitalWrite(redPin, HIGH); // sets the Red LED on digitalWrite(greenPin, HIGH); // sets the Green LED on delay(500); // waits for half a second digitalWrite(redPin, LOW); // sets the Red LED off digitalWrite(greenPin, LOW); // sets the Green LED off delay(500); // waits for half a second} You can just copy and paste this text into your Arduino software window. Quick quizWhat does this sketch do? Compile and upload the sketch to test your hypothesis. Highlight the text below to see the answer Lesson 4
a
Introduction
Ah, Arduino, I remember when you were just crawling around and blinking LEDs.
Now you're ready to learn how to speak! In this lesson we'll learn how to use the Serial Library to communicate from the Arduino board back to the computer over the USB port. Then we'll learn how to manipulate numbers and data.
For this lesson we won't be using the shield, so simply remove it (keeping the mood light LEDs on it you'd like).
The shield doesn't contain any programs or data, it is just our way of connecing up the LEDs and resistors. We'll use the shield again but for now, we can examine the RX and TX LEDs on the main Arduino board which will help you with debugging
What is a Library?
Libraries are great places, and not yet illegal in the United States! If you ever need to learn how to do something, like say fix a motorcycle, you can go to your local library and take out a book. Sure you could buy the book but the library is nice because as a resource you can get the book whenever you need it, keeping your house uncluttered. Software Libraries are very similar. We already studied what a procedure is, in lesson 3: a procedure is a list of things to do. A library is a big collection of procedures, where all the procedures are related! If you, say, want to control a motor, you may want to find a Motor Control Library: a collection of procedures that have already been written for you that you can use without having to do the dirty work of learning the nuances of motors. The library we will be using is the Serial Library, which allows the Arduino to send data back to the computer:
What is Serial?
Serial may sound like a tasty breakfast food, but its actually quite different. The word serial means "one after the other." For example, a serial killer doesn't stop with one murder, but stabs many people one after the other. Serial data transfer is when we transfer data one bit at a time, one right after the other. Information is passed back & forth between the computer and Arduino by, essentially, setting a pin high or low. Just like we used that technique to turn an LED on and off, we can also send data. One side sets the pin and the other reads it. It's a little like Morse code, where you can use dits and dahs to send messages by telegram. In this case, instead of a long cable, its only a few feet.
(Now, people who are all geeked-out will probably get angry at this point because I'm simplifying things. Well guess what, its an Arduino tutorial, not a OSI Physical Network Architecture tutorial.)
Bits & Bytes
Now is a good time to review how data is measured. For example, we measure weight with "ounces" and "pounds" (or grams and kilograms) and distances with "inches," "feet," and "miles" (or centimeters, meters and kilometers). Information has its own system of measurements:
A single bit is either a zero or a one.
An interesting thing to note is while 1000 grams is a kilogram, nearly all computer systems consider 1024 bytes to be a kilobyte. That is, a 1.0 Kilobyte file on your computer is 1024 bytes:
Quick quiz!
If your hard disk is 200 Gigabytes, how many bytes is that? Use a calculator with lots of digits!
Hard drive makers are quite sneaky, you'll notice that they define GB as being 1000 MB, and 1 MB = 1000 KB, etc. Given this fact, how many bytes can you really store in your 200GB drive?
How much less storage do you get thanks to the marketing guy who came up with this trick?
A familiar friend?
We've actually used the Serial communications capability already quite a bit...that's how we send sketches to the Arduino! When you Compile/Verify what you're really doing is turning the sketch into binary data (ones and zeros). When you Upload it to the Arduino, the bits are shoved out one at a time through the USB cable to the Arduino where they are stored in the main chip.
Next time you upload a sketch, look carefully at the two LEDs near the USB connector, they'll blink when data is being transmitted. One blinks when the Arduino is receiving data (RX) and one blinks when the Arduino is transmitting data (TX)
Time for our first sketch
Enough chatting amongst ourselves, its time to get the Arduino talking.
Our first sketch is going to be the hello world! program. When it starts up, it will say "hello world!" Create a New Sketch... and save it as HelloWorld
Into the new sketch, copy and paste the following source code, then save it /* * Hello World! * * This is the Hello World! for Arduino. * It shows how to send data to the computer */void setup() // run once, when the sketch starts{ Serial.begin(9600); // set up Serial library at 9600 bps Serial.println("Hello world!"); // prints hello with ending line break }void loop() // run over and over again{ // do nothing!}
OK first thing to notice is that there's nothing in the loop procedure! We've gutted it...and put some stuff into the setup procedure.
Even if we have nothing in the setup or loop procedures, the Arduino requires them to be there. That way it knows you really mean to do nothing, as opposed to forgetting to include them! The first line of code in the setup procedure is this one: Serial.begin(9600); // set up Serial library at 9600 bps
We definately see that there is a Serial thing going on, and it looks like there is a procedure call as well. This is a library procedure call. The library is called Serial and inside the library is a procedure called begin.
If there's no library name, it means that the procedure is in the 'default' collection of procedures we use. For example, delay() is so common, the designers of the Arduino software didn't bother putting it into a library.
So there's some mystery procedure that's called begin, well it's not too tough to figure out what it might do. It's the procedure that gets the Serial stuff ready. But what's the 9600 about? OK so Serial.begin sets up the Arduino with the transfer rate we want, in this case 9600 bits per second. Lets move on to the next line. Serial.println("Hello world!"); // prints hello with ending line break This line also uses the Serial library, this time it's calling a procedure called println which is just a shorthand for "print line". Note that the 6th letter in println is the letter L not the number 1. This time the input is a quotation, the line of text we would like it to print. We use two "'s (double quotes) to indicate the beginning and end of a line of text. Quick quiz!
Good, now compile the sketch and upload it to your Arduino....
And then...nothing???
It looks like not much is going on here. Somewhat disappointing since we had so much fun with blinking colored lights before. The trick here is that while you can see blinking lights quite easily, seeing serial data requires a monitor, which like your display monitor will show us what data is being transfered. Lucky for us, there's a serial monitor built into the Arduino software!
I'm not quite sure what the icon means, but regardless if you click that button you will replace the black Program Notification area with a Serial Monitor.
So...click it!
Hello...world?
What happens next is, sadly, quite dependent on which kind of Arduino you have
In the very common case of having a Diecimila Arduino, the serial monitor will auto-reset the Arduino. The sketch will start up a couple of seconds later Otherwise, the Arduino does not reset itself. Either way, once you've switched to the serial monitor, press the reset button. If you have an NG Arduino you'll have to wait 7 seconds for the sketch to start.
Voila! It is our sketch!
Baud rate match up!
If you ever find that you're getting a whole lot of gibberish instead of proper text, make sure that you have the correct baud rate selected in the drop down menu of the Serial Monitor. Note that this communication baud rate is indepedent of the upload process, which is fixed at 19200 bps. Next, try pressing the reset button a few times to make more Hello Worlds! appear. If you have an NG, this may be a bit annoying but do it anyways.
Each time you reset the Arduino, it performs the setup procedure, and prints out Hello again.
If you look closely at the Arduino, you will also see the little TX LED blink just as it prints out this message. That's your indication that data was sent.
What's Send do?
When you println you are sending data from the Arduino to the computer. The Send button (and the text input next to it) are used to send data to the Arduino. We aren't going to be using it in this lesson so don't be surprised that it doesn't do anything when you click it!
10 PRINT HELLO
20 GOTO 10 Our next sketch will be a minor modification of this one. Instead of printing out Hello World just once, we'd like it to print it out over and over and over again. Quick quiz!
Perform this modification and then compile and upload the new hyper-hello sketch. Then start up the serial monitor. You will see Hello World! scroll by super fast!
Quick quiz!
Make the Arduino chill out a little by adding a one second delay to the sketch, so that it only prints out Hello World once a second. /* * Hello World! * * This is the Hello World! for Arduino. * It shows how to send data to the computer */void setup() // run once, when the sketch starts{ Serial.begin(9600); // set up Serial library at 9600 bps}void loop() // run over and over again{ Serial.println("Hello world!"); // prints hello with ending line break delay(1000);}
Now you should spend some time playing with println and making it display a message of your choice! Perhaps add some more println statements in order to make the message longer?
Math is hard, let's try programming!
We've played around with printing out phrases, but it turns out we can also print out numbers pretty easily too. /* * Math is fun! */int a = 5;int b = 10;int c = 20;void setup() // run once, when the sketch starts{ Serial.begin(9600); // set up Serial library at 9600 bps Serial.println("Here is some math: "); Serial.print("a = "); Serial.println(a); Serial.print("b = "); Serial.println(b); Serial.print("c = "); Serial.println(c); Serial.print("a + b = "); // add Serial.println(a + b); Serial.print("a * c = "); // multiply Serial.println(a * c); Serial.print("c / b = "); // divide Serial.println(c / b); Serial.print("b - c = "); // subtract Serial.println(b - c);}void loop() // we need this to be here even though its empty{} Try out this sketch on your Arduino
Note that we're using 2 procedures here, the original println and now also print. The print procedure is just like println except it does not print out a "carriage return" at the end, starting a new line. You can experiment with changing the print's to println's and looking at the Serial Monitor output to verify this for yourself. Here's whats going on in the Arduino with this sketch. For example, lets look at this line: Serial.println(a); We've seen that if you use a quoted line of text as input to println procedure, it will display that text. In this case you can see that if you use a variable to println it will look up what that variable contains and print that out! It turns out that the Arduino is smart enough to also do math when asked: Serial.println(a + b); In this case, the Arduino looks at what the input to println is, and finds its actually a calculation. It looks up what a is (5) and what b is (10) and then adds them together (+) and then uses that as the value to send to println Note that for now, we can only do math using integers, which if you recall, are whole numbers. That means we can't yet print out numbers like 3.14 or 1.5. I could go on and on about operators, its all very important stuff, but many people have written good tutorials on this topic already so I'm going to send you off to read them there!
Pythagorean party
Let's make our first simple calculator, to calculate a hypoteneuse. If you remember from grade school, if you have a right-triangle, the hypoteneuse h can be calculated from the lengths of the two legs, c1 and c2 (which we'll call a & b)
a2 + b 2 = h 2 /* * Math is fun! */#include "math.h" // include the Math Libraryint a = 3;int b = 4;int h;void setup() // run once, when the sketch starts{ Serial.begin(9600); // set up Serial library at 9600 bps Serial.println("Lets calculate a hypoteneuse"); Serial.print("a = "); Serial.println(a); Serial.print("b = "); Serial.println(b); h = sqrt( a*a + b*b ); Serial.print("h = "); Serial.println(h);}void loop() // we need this to be here even though its empty{} The first thing that's new here is this line at the very beginning of the sketch: #include "math.h" // include the Math Library header Which basically says "We'd like to use the math procedures, which are in a library that requires us to include the file math.h where the sqrt procedure lives". Just ignore it for now, it's not important. The second thing that's different here is that when we create the variable h we don't assign it a value.
It turns out that this is totally OK, it just means that we don't know what h is going to store yet, because we're going to calculate it later. Since it's not assigned to a value upon creation, the Arduino just creates the box, the stuff inside is whatever was in left over in memory. Default values If you don't assign a value to a variable, it could be any value. Make sure you don't try to use the variable before you assign it a value! Later on in the sketch, we assign it the value.
In this line, we square a and b and then add them together, then we call the sqrt() procedure (which does exactly what you may think), to take the square root. Then we assign that to the variable h.
Whatever was in h before is lost, replaced by the new value. You can nest procedures and functions all you want, calling a procedure on the return value of another procedure. Quick quiz!
Now its your turn to create a calculator.
(This is a pretty useful law which forms the basis of electronics, and we'll study it in depth more later.) Starting with two variables, i for current and r for resistance, have it print out the amount of voltage that can be measured accross the resistor.
Drive size calculator
Let's write a program that will do that hard drive size calculation we did before. We'll start with the hard drive size in GB, and print out how many MB there are. We'll start simple, just printing out the drive size in GB /* * Drive size calculator! */int drive_gb = 5;void setup() // run once, when the sketch starts{ Serial.begin(9600); // set up Serial library at 9600 bps Serial.print("Your HD is "); Copy and paste this sketch into Arduino software and name the sketch DriveCalc. Then compile and upload it.
OK, lets add a section of code that will print out the number of Megabytes in the hard drive. /* * Drive size calculator! */int drive_gb = 5;int drive_mb;void setup() // run once, when the sketch starts{ Serial.begin(9600); // set up Serial library at 9600 bps Serial.print("Your HD is "); This time if you compile and upload it you should get
Which is correct, yay! Now try a few different whole numbers for the drive size, from 1 GB to 100 GB. You may notice that if you put in a 100GB drive size, something very, very strange happens:
A 100GB drive should have 102400MB in it, not some negative number. What's going on here?
Introduction to types (part 1)
What's happening is that we have an overflow problem. Think about your car odometer. The odometer has only 4 digits, it can display 0 miles to 9999 miles travelled. If you travel 10000 miles, the odometer will "roll over" to 0 again, and from then on it will display an incorrect value.
Keeping that in mind, remember in lesson 2 we said that when we define a variable we also define the box-type of the variable? The box is where we store the data, in this case the type is int. It turns out that an int type can store only 2 bytes.
Quick quiz! To figure out how big a number we can store in a 2 byte-sized box use a calculator and take 2 to the power of the number of bits (since each bit can store 2 values, 0 or 1). Then we subtract 1 because like in the car odometer, you can't actually display the final value, 10000. So, in this case the largest number is 216 - 1 = 65535. Since the number we're trying to store (102400) is larger than that, we see that "rollover." OK let's fix it! All we need to do is change the variable type so that it can store more than 2 bytes of data. Here is a short list of types we can use.
It looks like we want to use the long type. So lets make that change /* * Drive size calculator! */int drive_gb = 100;long drive_mb; // we changed the type from "int" to "long"void setup() // run once, when the sketch starts{ Serial.begin(9600); // set up Serial library at 9600 bps Serial.print("Your HD is "); Compile and upload this sketch....then run the Serial Monitor....
Uh oh, we didn't actually fix the problem! How frustrating, we did the right thing and it still didn't work. The problem we have now is although the boxes are the right size, we're not handling them well. drive_mb = 1024 * drive_gb; If you look at this line, what's happening here is that the Arduino looks up the value of the variable drive_gb to get 100. Then we multiply 100 by 1024 to get 102400 and put that in the drive_mb box. Except the way that the Arduino software does this is that it creates a temporary variable the same size as drive_gb to store that calculation result before it sticks it into drive_mb. So basically we are still getting an overflow, except now its happening as we do the calculation. Here is one way to fix this insiduous bug: /* * Drive size calculator! */int drive_gb = 100;long drive_mb;void setup() // run once, when the sketch starts{ Serial.begin(9600); // set up Serial library at 9600 bps Serial.print("Your HD is "); Now when we do the calculation, the temporary result is stored in a box the same size as drive_mb (a long) instead of an int. Compile and upload this sketch to try it out
There you go, now its working!
Introduction to types, part 2
It turns out that I wasn't completely honest in the previous section when I described all the different types. There's another important fact to know, and that has to do with storing negative numbers.
We know that a variable that is 2 bytes large (16 bits) can store 216 different values.
We assumed before that these values were 0 - 65535 inclusive. But then how do we store negative numbers? It turns out that there are two kinds of variables, signed and unsigned. By default, variables are signed.
Quick quiz!
Why Types?
OK so you're probably wondering: "This is such a pain, why bother with different size types? Lets just have every variable be as big as possible and we'll never have roll-over problems." Well, on your desktop computer, with gigabytes of memory (RAM), this is a reasonable thing to do. However, the tiny tiny computer in the Arduino has a grand total of 1 Kilobyte of memory. And some of that is used for background stuff you don't see. For small sketches sure you can make everything a long and be done with it, but if you have a bigger sketch, you'll run out of memory really fast and then you'll have major problems. So in this case, every byte counts! What's weird about signed numbers is that if you reach the end of the positive value range you'll rollver into the negative values. For example, lets say you have a signed int. If you have the value 32767 in that variable, and you add 1 to the variable, you'll actually rollover to -32768.
This sketch will test out this fact: int test = 32767;void setup() // run once, when the sketch starts{ Serial.begin(9600); // set up Serial library at 9600 bps Serial.print("Test value is: "); Compile and upload to run the test.
Quick quiz!
Now it's your turn! Write some sketches that will help you understand variable sizes, try creating variables of different types and signedness and adding and subtracting. Although this lesson part seems quite boring, and severely lacking in blinky lights, understanding this stuff now will save you from a lot of headaches later when you have data overflows and your program is all wonky and you're really frustrated because you can't figure out why. (Trust me on this one!)
Wrapping up, the final project!
Now its time for you to expand the drive size calculator. Starting with the DriveCalc sketch, modify it so that it will also calculate how many KB are stored in the hard drive. Test it out with a couple different drive sizes. Once you've got that working, modify it again so that it will also display how much space the drive actually holds thanks to the sneaky math-trick that manufacturers use. Have the sketch display how much storage space is 'missing' (in KB) as well. Here's one possible solution: /* * Drive size calculator! */int drive_gb = 100;long drive_mb;long drive_kb;long real_drive_mb;long real_drive_kb;void setup() // run once, when the sketch starts{ Serial.begin(9600); // set up Serial library at 9600 bps Serial.print("Your HD is "); Serial.print(drive_gb); Serial.println(" GB large."); drive_mb = drive_gb; drive_mb = drive_mb * 1024; drive_kb = drive_mb * 1024; Serial.print("In theory, it can store "); Serial.print(drive_mb); Serial.print(" Megabytes, "); Serial.print(drive_kb); Serial.println(" Kilobytes."); real_drive_mb = drive_gb; real_drive_mb = real_drive_mb * 1000; real_drive_kb = real_drive_mb * 1000; Serial.print("But it really only stores "); Serial.print(real_drive_mb); Serial.print(" Megabytes, "); Serial.print(real_drive_kb); Serial.println(" Kilobytes."); Serial.print("You are missing "); Serial.print(drive_kb - real_drive_kb); Serial.println(" Kilobytes!");}void loop() // run over and over again{}
Conclusion
Good work, you got through one of the more boring lessons. In this lesson you learned how to print text and data to the Serial Monitor. This is essential for debugging future projects! You also learned about data types and storage and how to use the Arduino to calculate stuff.
a
Lesson 5
a
Introduction
We've done a lot so far, blinking lights, printing messages...all of that stuff is output: signals coming from the Arduino. The next step is to start playing with input, with the Arduino responding to outside events. In this lesson we will begin with the most basic kind of input, a push-button switch!
What you'll need
What's a switch?
You're probably familiar with switches, there's tons of them in your house. One kind of switch you use every day is a light switch. A light switch is a simple device with two positions, on and off. When on, two wires are connected inside, which allows current to flow. When off, the two wires are disconnected.
On the left, the switch is open and no current flows. On the right, the switch is closed, current flows and the light turns on.
In this photo, you can see the internals of a light switch. The two wires connect to the top and bottom. The flat bar that goes verically down the middle is what is physically moved to connect or disconnect. Light switches are great but we need something smaller. We'll be primarily using 6mm tactile button switches.
These little switches are a 1/4" on each side, cost about 25 cents, and can plug directly into a breadboard. These mechanical devices have 4 legs, which may make you think that there are 4 wires that are switched on and off, but in fact, two on each side are actually connected together inside. So really, this switch is just a 2-wire switch.
Normally, the two wires are disconnected (normally open) but when you press the little button on top, they are mechanically connected.
To get the buttons to sit better in the protoshield, you may want to straighten out the legs (just squish them with a pair of pliers) so that they look like the button on the left. Quick Quiz!
Light switch
We're going to make our first test of the pushbutton by having it turn on and off an LED light
Get out your red LED and 1.0KΩ resistor, as well as the tiny pushbutton and build the schematic onto your protoshield: Power up the Arduino and try pressing the button. The LED should light up when the button is held down (current is able to flow) and go dark when it's released (current is not able to flow).
Switch capability
Before you try to turn a 100W lightbulb on and off using a pushbutton switch, be aware that switches have ratings that will tell you the maximum amount of current and voltage they can switch. The little switches are only rated for a few volts and milliAmps. Big switches such as wall light switches are rated for 120V and many Amperes. Make sure you choose the right switch for the job or you may accidentally cause a small fire! Quick Quiz!
There's a lot of information, but learning how to navigate these sorts of pages is rather important. Use your detective skills to figure out the follwing:
DigitalRead
Switches are great for controlling current, as shown by our little light switch demo. But they're even better as input devices!
In previous lessons we set a pin on the microcontroller (say pin 13) to HIGH (5V) or LOW (ground, 0V) using the DigitalWrite procedure. Now we get to do the opposite. We will set the voltage on a pin to 5V or ground and then use DigitalRead to inquire whether that pin is HIGH or LOW For our first test, we will use a wire as our switch. Turn on the Arduino and run this little sketch /* You'll note that we have to tell the Arduino to set the pin as an input. This is pretty easy, use pinMode() but use INPUT instead of OUTPUT pinMode(switchPin, INPUT); // sets the digital pin as input to read switch We also use the new digitalRead() procedure, which just takes as an input the pin to examine. Serial.println(digitalRead(switchPin)); // Read the pin and display the value
The digitalRead() procedure returns a result when its done. That result is either 0 (LOW) or 1 (HIGH) depending on what it saw when it looked at the pin's voltage. In this case, we read the pin and then pass the result as an input to another procedure, println(). Sure we could use a variable to hold the result from digitalRead() and then use that variable as input to println() but this is much more succinct. var = digitalRead(switchPin); // read the pin and save it into varSerial.println(var); // print out the value stored in var Now use a wire to alternate between connecting Pin 2 to 5V and Ground through a 100Ω resistor, and watch the serial monitor.
You should see it print out two messages depending on whether a the wire jumper connects the input to HIGH (5V) or LOW (ground) voltage. Dont forget, in digital binary land, HIGH is another word for 1 and LOW is another word for 0.
Valid inputs
The best way to completely destroy a microcontroller such as an Arduino is to feed it voltages that are much too high. Make sure your input voltages are between 0 and 5V! Never connect a 9V battery directly into an input pin, it will fry the pin for good and possibly destroy the Arduino microcontroller!
Whats this 100Ω resistor all about?
There's a 100Ω resistor we use to connect the input pin to either HIGH or LOW voltage. Why is it there? Well, lets say you accidentally set P2 to be an OUTPUT type pin, but then you connected it to 5V. If you write a LOW to the pin (0V) but its connected to HIGH (5V), you've basically caused a short circuit at that pin. This isn't very good for the pin and could damage it! The 100Ω resistor acts as a buffer, to protect the pin from short circuits.
Floating high above the clouds
Of course, connecting and disconnecting a wire is a lot of work, and we'd like to replace that with a mechanical switch. Only thing is, our switch can only connect and disconnect two wires, it can't alternate connections.
Fig 5.3Our two alternative switch wiring possibilities
For example, in these schematics we can connect and disconnect pin 2 to 5V, or we can connect and disconnect pin 2 to ground. In both cases, as long as the button is held down, the pin is connected to a valid input voltage. When the button is released, though, pin 2 is not connected to anything. This is called a floating input voltage. Basically, it's invalid input! Try building up one of these schematics, and trying out the switch testing sketch above. When the button is held down you should definately get the right printout. When its released, it may keep the old value, or it may change, but its certainly not reliable!
One solution is to get a switch that alternates connections, like this one, diagrammed here.
The problem is, these switches are suprisingly complex and 10 times more expensive than a little tactile button! Instead we use a trick called a pull-down resistor.
The pull-down resistor here is the 10K resistor. When the switch is held down, the 100Ω resistor is connected directly to 5V. When the switch is released, the 100Ω resistor is connected to the 10K resistor which pulls it down to ground.
Here's how to think of it: When you press the button and connect the 100Ω resistor to 5V, the button has a very small resistance (less than 1 Ω!), so it provides a strong pull to 5V. However, when the switch is disconnected, there is no longer a strong pull to 5V. In fact, its let go completely. But there is still weak pull to ground. Despite being a weak connection, it's better than nothing and so the resistor pulls the input pin to LOW. Build this circuit and try it out with the switch test sketch. It should be very reliable now! If its not working, make sure you have the right resistor values and that the parts are connected up properly. You can also use the switch to connect the input to ground, and use a resistor as a pull-up resistor.
Try this schematic as well, and verify for yourself that the button is now reliable.
Note that the strong and weak connections have nothing to do with whether the switch is configured as a pull-up or pull down. The strength of the connection comes from the fact that the button is very low resistance when held down and that the resistor is much much more resistive to current flow than the button.
Must a pullup/down resistor be 10KΩ?
You'll notice that both the Arduino schematic, and the examples here use a 10KΩ resistor as the pullup or pulldown. Is there something special about 10KΩ? Nope! While, it is pretty much univerally used as the 'default' value, most of the time you can use as high as 100KΩ or as low as 4.7KΩ. Going much lower will waste more power, going higher may give you unstable results (due to microcontroller-internals that are not that important right now). Quick Quiz!
There is a switch and a resistor (Europeans use a rectangle instead of a squiggly for resistors), they are both connected to a pin on the Arduino microcontroller called RESET (in the bottom right corner)
Iffy statements
The next step is to combine inputs (buttons) and outputs (LEDs). We will make a simple digitally-controlled light. The sketch we want to write does the following When the button is pressed, the LED turns on Which we can rephrase more specifically as
If the button is pressed, turn on the LED. Here is how we will wire up the switch and LED.
Build this schematic on your protoshield
Copy and paste this sketch into the Arduino software and upload it to the Arduino. Verify that when the button is pressed, the LED turns on and when the button is released, the LED turns off. That way you can tell if its the input half that isnt working or the output half. /* * Switch and LED test program */ int ledPin = 12; // LED is connected to pin 12int switchPin = 2; // switch is connected to pin 2int val; // variable for reading the pin statusvoid setup() { pinMode(ledPin, OUTPUT); // Set the LED pin as output pinMode(switchPin, INPUT); // Set the switch pin as input}void loop(){ val = digitalRead(switchPin); // read input value and store it in val if (val == LOW) { // check if the button is pressed digitalWrite(ledPin, HIGH); // turn LED on } if (val == HIGH) { // check if the button is not pressed digitalWrite(ledPin, LOW); // turn LED off }} This sketch introduces a completely new and exciting type of statement, the if statement. This is a logical statement, which you may remember from grade school math class. Basically, until now we've had the Arduino just do stuff: blink LEDs, print out messages, etc. But now we want it to make decisions.
The if statement is the first statement that is conditional, it only runs the statements if a condition is true. In this case, the conditions are "is the button pressed?" and "is the button not pressed?"
Quick Quiz!
Now its your turn: add another red LED and resistor to pin 11, modify the sketch so that when the button is pressed one LED is lit and the other one is off and when the button is released the first LED is off and the second LED is lit.
Try to wire up the protoshield just from the schematic. If you're having trouble, click here for a photo of the parts wired up. Here is one possible solution sketch: /* * Switch and 2 LED test program */ int led1Pin = 12; // LED #1 is connected to pin 12int led2Pin = 11; // LED #2 is connected to pin 11int switchPin = 2; // switch is connected to pin 2int val; // variable for reading the pin statusvoid setup() { pinMode(led1Pin, OUTPUT); // Set the LED #1 pin as output pinMode(led2Pin, OUTPUT); // Set the LED #2 pin as output pinMode(switchPin, INPUT); // Set the switch pin as input}void loop(){ val = digitalRead(switchPin); // read input value and store it in val if (val == LOW) { // check if the button is pressed digitalWrite(led1Pin, HIGH); // turn LED #1 on digitalWrite(led2Pin, LOW); // turn LED #2 off } if (val == HIGH) { // check if the button is not pressed digitalWrite(led1Pin, LOW); // turn LED #1 off digitalWrite(led2Pin, HIGH); // turn LED #2 on }}
Do it...or else!
Having an LED turn on or off when a button is pressed is quite impressive, but it would be pretty odd if you had to press a button constantly to keep the TV on. What we want is an alternating action switch, where the press-and-release of a button does something, not just press-and-hold. Basically we want to test whether the button was just released, or just pressed.
To do this, we need to keep track of the button input value, to see if its changed. This is called the state of a button. When the state changes (an action occurs), that's when we want to perform an action. /* Upload it to your Arduino and try it out, watching the serial monitor as you press and release the button. Lets go through the new lines of code: int buttonState; // variable to hold the button state This line isn't too unusual, its just a variable that is going to hold the state of the button. Since we don't know the state of the button when the Arduino is first turned on, we will leave it as unknown (uninitialized). buttonState = digitalRead(switchPin); // read the initial state Inthe setup() procedure, we initialize (set the initial/starting value) of the button state variable by reading the button value once we've started up and set the pin to an input. void loop(){ val = digitalRead(switchPin); // read input value and store it in val OK now to the interesting part. In the loop procedure, we begin by first checking the button pin state and storing it an temporary variable val. if (val != buttonState) { // the button state has changed! if (val == LOW) { // check if the button is pressed Now we see 2 if statements that are nested, this means that we perform one test and if that test comes out true we go on to perform another test. This is more complex than a simple if statement but not much more different than the kinds of decisions we make all the time. For example: if ( it is raining ) { // look up, is there water falling on me? if ( I have an umbrella ) { // check my purse OpenUmbrella(); // Perform the umbrella opening procedure } } Of course, we can't open the umbrella if we don't have one. And there's no point in checking if we have one if its not raining! In the first if statement, we check if the current button state (HIGH or LOW) is different than the last time we looked at the button. If it is different (tested by the != inequality operator ) then we execute the next group of statements, enclosed by the {} braces. Lets move on and examine the new statement we see, which is the exotic if-else statment. if (val == LOW) { // check if the button is pressed Serial.println("Button just pressed"); } else { // the button is -not- pressed... Serial.println("Button just released"); } This statement is easy to understand: before, we would run a test and if that test passed, we would perform the statements in the {} braces. Now we also have an alternative, which is what we should do if the test fails! Now we used to perform two tests, one for (val == LOW) and one for (val == HIGH). This code is equivalent but its a little more straightforward. If its not LOW it must be HIGH.
In the if-else statement, we simply examine val to deterimine if the last digitalRead() procedure informed us that the button is currently pressed or not pressed.
Finally, we make sure that we've updated the button state variable with the current state. Quick Quiz!
Counting presses
A pretty useful techinque you'll want to add to your collection of sketch-knowledge is how to keep track of button presses. Try this sketch /* We've added one new thing in this sketch, which is the ++ operator. Simply, the statement "buttonPresses++" increments (adds 1 to) the buttonPresses variable.This is a shortcut for "buttonPresses = buttonPresses + 1". Quick Quiz!
Design challenge, part 1
The phone rings, and you pick it up!
The contracts are faxed and signed and now it's time to do your job. Here is a video demonstrating the functionality the customer wants
http://www.ladyada.net/learn/arduino/lesson5.html
Lesson 6 https://learn.adafruit.com/all-about-leds Arduino Ethernet+SD Whatsit?We just got the latest version of the Arduino Ethernet shield with a MicroSD card slot and I promised Bill Greiman I'd try out the latest version of his SdFatLib library so I decided to code up a simple Webified file browser. Its a quicky project and demonstrates what you can do, but it isn't 100% perfect so you should be ready to modify it if you'd like to do other stuff, 'K? This is a good beginning to a logging web-monitor, or remote storage system. Get familiarBefore you do this tutorial you'll want to get familiar with what you're working on. This isn't a beginner tutorial, its best used by those who already have quite a bit Arduino or microcontroller experience and are 'fluent' in C/C++/Java! Also, read up on how to use the Ethernet shield and Ethernet library . Then review my notes on SD card usage and installing the library we'll be using You should have already gotten the Ethernet shield working with your network setup, too.
While we're happy to share this code, please note that this project is just example code. It is completely unsupported. Enjoy it! Mod it! Hack it! But please don't expect more than what is posted here! You can download the latest code from GitHub (click Download Source in the top right) Initializing Micro-SD card on an Ethernet shield
The latest Arduino Ethernet shield comes with a handy MicroSD card slot so that you can store and retrieve data through the shield. Very handy! Lets show how to talk to the card. Be sure to have the very latest version of SdFatLib , as you'll need some of the newer capabilities! First thing to note is that the SS (Slave Select) pin for the card is digital 4 (although as of the writing of this mini-tutorial, the schematic hasn't been updated, you'll have to trust me!) Open up the SdFatInfo example sketch and change the line in loop() from uint8_t r = card.init(SPI_HALF_SPEED); To: pinMode(10, OUTPUT); // set the SS pin as an output (necessary!) digitalWrite(10, HIGH); // but turn off the W5100 chip! uint8_t r = card.init(SPI_HALF_SPEED, 4); // Use digital 4 as the SD SS line Be sure to add those two extra lines right before-hand! They Enable the SPI interface. If you're on a Mega, use pin 53 instead of 10 Now upload and test the card, you should see something like this:
Indicating you talked to the card all right List filesPut some text files on your SD card, using a computer, so that you have data to read. Make sure they are in the root directory, and not in a folder Then run the SdFatLs example sketch from the SdFat library, you should see it list all the files you have on the card, again, you'll have to make the changes from above to update the card.init() part to the new SS pin
For example, the card I'll be using has two files on it from some previous datalogging. Merge WebServer + SdFatLsWe'll begin by combining WebServer (the example sketch that comes with the Ethernet lib) and SdFatLs to make a web server that lists the files on the SD card. You can download the file here (you'll need to copy&paste it, do so carefully!)then follow along! Part one is the Ethernet and SD card objects and a simple error function (void error_P(const char* str)) that prints out errors and halts the program if there are serious problems. You should, of cousre, set your mac and ip as necessary, use the ip and mac that worked from your previous Ethernet shield explorations! The card, volume, and root are objects that help us traverse the complex structure of an SD card The error function is not too exciting, it just prints out the error and sits in a while(1); loop forever /* * This sketch will list all files in the root directory and * then do a recursive list of all directories on the SD card. * */ #include <SdFat.h>#include <SdFatUtil.h>#include <Ethernet.h> /%%**%%%%**%%%%**%%%%**%%%%**%%%%**%% ETHERNET STUFF %%**%%%%**%%%%**%%%%**%%%%**%%%%**%%/byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };byte ip[] = { 192, 168, 1, 177 };Server server(80); /%%**%%%%**%%%%**%%%%**%%%%**%%%%**%% SDCARD STUFF %%**%%%%**%%%%**%%%%**%%%%**%%%%**%%/Sd2Card card;SdVolume volume;SdFile root; // store error strings in flash to save RAM#define error(s) error_P(PSTR(s)) void error_P(const char* str) { PgmPrint("error: "); SerialPrintln_P(str); if (card.errorCode()) { PgmPrint("SD error: "); Serial.print(card.errorCode(), HEX); Serial.print(','); Serial.println(card.errorData(), HEX); } while(1);} Part 2 is the setup() function. It sets up the Serial object so we can debug the connection in real time. It then prints out the RAM usage. You'll need a Atmega328Arduino for this experiment, and you should see at leat 1000 bytes of RAM free. Once this gets to under 250 bytes, you may be running too low! Then we do the trick where we make the hardware SS pin #10 to an OUTPUT and HIGH to disable the wiznet chip while we check the card contents. If you're on a Mega, change this to 53. Then we initialize the card which should go fine since you already tested this before Then we verify the card structure, print out all the files, and print "Done!". Finally we stuck the Ethernet initialization code at the end here! Now we have both the Ethernet and SD card working void setup() { Serial.begin(9600); PgmPrint("Free RAM: "); Serial.println(FreeRam()); // initialize the SD card at SPI_HALF_SPEED to avoid bus errors with // breadboards. use SPI_FULL_SPEED for better performance. pinMode(10, OUTPUT); // set the SS pin as an output (necessary!) digitalWrite(10, HIGH); // but turn off the W5100 chip! if (!card.init(SPI_HALF_SPEED, 4)) error("card.init failed!"); // initialize a FAT volume if (!volume.init(&card)) error("vol.init failed!"); PgmPrint("Volume is FAT"); Serial.println(volume.fatType(),DEC); Serial.println(); if (!root.openRoot(&volume)) error("openRoot failed"); // list file in root with date and size PgmPrintln("Files found in root:"); root.ls(LS_DATE | LS_SIZE); Serial.println(); // Recursive list of all directories PgmPrintln("Files found in all dirs:"); root.ls(LS_R); Serial.println(); PgmPrintln("Done"); // Debugging complete, we start the server! Ethernet.begin(mac, ip); server.begin();}
We'll skip ahead to the loop() where we wait for clients (checking via server.available()) and then read the client request before responding. This is basically copy-and-pasted from the Webserver example sketch that comes with the Ethernet library (well, the first and last parts of the loop are at least). There's a little trick where to simplify the code, the writer of this sketch doesn't actually check to see what file the web browser wants, it always spits out the same thing. In this case, we're going to have it spit out the files by using a helper function called ListFiles(client, 0) which we skipped over but will show next. The 0 in the second argument to the function just tells the function whether to print out the file sizes void loop(){ Client client = server.available(); if (client) { // an http request ends with a blank line boolean current_line_is_blank = true; while (client.connected()) { if (client.available()) { char c = client.read(); // if we've gotten to the end of the line (received a newline // character) and the line is blank, the http request has ended, // so we can send a reply if (c == '\n' && current_line_is_blank) { // send a standard http response header client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println(); // print all the files, use a helper to keep it clean //ListFiles(client, 0); client.println("<h2>Files:</h2>"); ListFiles(client, 0); break; } if (c == '\n') { // we're starting a new line current_line_is_blank = true; } else if (c != '\r') { // we've gotten a character on the current line current_line_is_blank = false; } } } // give the web browser time to receive the data delay(1); client.stop(); }} Now we'll go back and exampine the ListFiles function. This is a bit tedious, but worth looking at. We've simplified it by removing recursive listing, which means we don't list files in any subdirectories. The dir_t p object is a "Directory Entry" holder. It will store the information for each entry in the directory. We first reset the root directory by rewind()'ing it. Then we read the directory file by file. Some files are unused or are the "." and ".." (up directory) links, which we ignore. We also only list FILEs or SUBDIRectories. Then we print the name out by going through all 11 characters (remember the file names are in 8.3 format) and ignore the space. We also stick the '.' between the first 8 and last 3 characters. If its a directory type file, we put a slash at the end to indicate it. If its not, we can print out the file size in bytes. Finally, after each file name we stick in a "<br>" which will go to the next line in a web browser void ListFiles(Client client, uint8_t flags) { // This code is just copied from SdFile.cpp in the SDFat library // and tweaked to print to the client output in html! dir_t p; root.rewind (); while (root.readDir(p) > 0) { // done if past last used entry if (p.name[0] == DIR_NAME_FREE) break; // skip deleted entry and entries for . and .. if (p.name[0] == DIR_NAME_DELETED || p.name[0] == '.') continue; // only list subdirectories and files if (!DIR_IS_FILE_OR_SUBDIR(&p)) continue; // print file name with possible blank fill //root.printDirName(*p, flags & (LS_DATE | LS_SIZE) ? 14 : 0); for (uint8_t i = 0; i < 11; i++) { if (p.name[i] == ' ') continue; if (i == 8) { client.print('.'); } client.print(p.name[i]); } if (DIR_IS_SUBDIR(&p)) { client.print('/'); } // print modify date/time if requested if (flags & LS_DATE) { root.printFatDate(p.lastWriteDate); client.print(' '); root.printFatTime(p.lastWriteTime); } // print size if requested if (!DIR_IS_SUBDIR(&p) && (flags & LS_SIZE)) { client.print(' '); client.print(p.fileSize); } client.println("<br>"); }} OK after all that work, lets upload that sketch to the Arduino! Make sure you have the correct ip address for your network, then use a browser on the same network to visit your website. Here is what I got - there are those two files from my previous datalogging experiments! Browsing files!Obviously, we should make it so you can clicky those file names, eh? Well! Thats the next sketch, you can download the latest version from github here (click Download Source) in the top right hand corner! Fix the ip address to match your network, and SS pin (if you're on a Mega)
Not a lot has changed between the previous code, the setup is the same, the big changes are in the loop() code. The bones are the same - we look for new client connections. But this time we read the client request into a character buffer (clientline) until we get a newline character (such as \n or \r). This indicates we have read an entire line of text. To 'finish' the string, we put a null character (0) at the end. We then use strstr which will look for substrings. If we have a "GET / HTTP" request for the root directory, we do the same as before, printing out the list of files. If we have no space after "GET /" that means its something like "GET /file" which means we will have to extract the filename. We make a pointer to the string and start it right after the first slash. Then we look for the beginning of the "HTTP/1.1" string which follows the filename request and turn the first character into a string-terminator. Now we have the name of the file which we can try to open. If we fail to open the file, we will return a 404. Otherwise, we print out all of the file contents. // How big our line buffer should be. 100 is plenty!#define BUFSIZ 100 void loop(){ char clientline[BUFSIZ]; int index = 0; Client client = server.available(); if (client) { // an http request ends with a blank line boolean current_line_is_blank = true; // reset the input buffer index = 0; while (client.connected()) { if (client.available()) { char c = client.read(); // If it isn't a new line, add the character to the buffer if (c != '\n' && c != '\r') { clientline[index] = c; index++; // are we too big for the buffer? start tossing out data if (index >= BUFSIZ) index = BUFSIZ -1; // continue to read more data! continue; } // got a \n or \r new line, which means the string is done clientline[index] = 0; // Print it out for debugging Serial.println(clientline); // Look for substring such as a request to get the root file if (strstr (clientline, "GET / ") != 0) { // send a standard http response header client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println(); // print all the files, use a helper to keep it clean client.println("<h2>Files:</h2>"); ListFiles(client, LS_SIZE); } else if (strstr (clientline, "GET /") != 0) { // this time no space after the /, so a sub-file! char *filename; filename = clientline + 5; // look after the "GET /" (5 chars) // a little trick, look for the " HTTP/1.1" string and // turn the first character of the substring into a 0 to clear it out. (strstr (clientline, " HTTP"))[0] = 0; // print the file we want Serial.println(filename); if (! file.open(&root, filename, O_READ)) { client.println("HTTP/1.1 404 Not Found"); client.println("Content-Type: text/html"); client.println(); client.println("<h2>File Not Found!</h2>"); break; } Serial.println("Opened!"); client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/plain"); client.println(); int16_t c; while ((c = file.read()) > 0) { // uncomment the serial to debug (slow!) //Serial.print((char)c); client.print((char)c); } file.close(); } else { // everything else is a 404 client.println("HTTP/1.1 404 Not Found"); client.println("Content-Type: text/html"); client.println(); client.println("<h2>File Not Found!</h2>"); } break; } } // give the web browser time to receive the data delay(1); client.stop(); }} Lets look at the new file listing code as well, its very similar, but now we've added a bit of HTML so that each file is part of a <ul> list and the name is a URL link. void ListFiles(Client client, uint8_t flags) { // This code is just copied from SdFile.cpp in the SDFat library // and tweaked to print to the client output in html! dir_t p; root.rewind (); client.println("<ul>"); while (root.readDir(p) > 0) { // done if past last used entry if (p.name[0] == DIR_NAME_FREE) break; // skip deleted entry and entries for . and .. if (p.name[0] == DIR_NAME_DELETED || p.name[0] == '.') continue; // only list subdirectories and files if (!DIR_IS_FILE_OR_SUBDIR(&p)) continue; // print any indent spaces client.print("<li><a href=\""); for (uint8_t i = 0; i < 11; i++) { if (p.name[i] == ' ') continue; if (i == 8) { client.print('.'); } client.print(p.name[i]); } client.print("\">"); // print file name with possible blank fill for (uint8_t i = 0; i < 11; i++) { if (p.name[i] == ' ') continue; if (i == 8) { client.print('.'); } client.print(p.name[i]); } client.print("</a>"); if (DIR_IS_SUBDIR(&p)) { client.print('/'); } // print modify date/time if requested if (flags & LS_DATE) { root.printFatDate(p.lastWriteDate); client.print(' '); root.printFatTime(p.lastWriteTime); } // print size if requested if (!DIR_IS_SUBDIR(&p) && (flags & LS_SIZE)) { client.print(' '); client.print(p.fileSize); } client.println("</li>"); } client.println("</ul>");} OK upload the sketch already! Now you'll see that the file names have turned into links (we also added the file size in bytes)
Click on a filename to view it
If you try to view a file that is not on the card, you'll get a 404 error (file not found)
This page was autogenerated from http://www.ladyada.net/wiki//tutorials/learn/arduino/ethfiles.html Please edit the wiki to contribute any updates or corrections.
HELP!!!
HELP! While Arduino is a nice little system, there's a lot of bugs. Hopefully they'll be fixed soon, but until then, here's problems you're likely to run into.
avrdude: stk500_getsync(): not in sync: resp=0x00
If you get the following error message "avrdude: stk500_getsync(): not in sync: resp=0x00" that means that the Arduino is not responding. There are literally dozens of reasons this could be.
Check the following:
Note that it is nearly impossible for anyone to debug this, as there are so many possible issues. Try everything.
java.lang.NullPointerException at processing.app.Serial.setDTR
If you get the following error message java.lang.NullPointerException at processing.app.Serial.setDTR(Serial.java:480) It means you dont have a serial port selected, go back and verify that the correct driver is installed (lesson 0) and that you have the correct serial port selected in the menu. This is a bug in Arduino and will hopefully be fixed in v10.
avrdude: Expected signature for ATMEGA is ...
If you get the following error avrdude: Expected signature for ATMEGA is ...
Then you have either the incorrect chip selected in the Tools menu or the wrong bootloader burned onto the chip
ser_send(): write error: sorry no info avail
(no screenshot as I can't reproduce it)
You have the wrong serial port selected. Make sure the driver is installed and you have the correct serial port number, see lesson 0.
Buy stuff
https://www.adafruit.com/category/17 http://www.ladyada.net/learn/arduino/index.html
DIN A4 ausdrucken |
Anleitung-Tutorial‎ > ‎