Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore Arduino Projects For Dummies

Arduino Projects For Dummies

Published by Rotary International D2420, 2021-03-23 20:46:07

Description: Brock Craft - Arduino Projects For Dummies-For Dummies (2013)

Search

Read the Text Version

Xively works in greater detail. 2. To connect your Arduino, click the Develop button at the top of the page. On the Development Devices page, click the Add Device button, as shown in Figure 12-17. Figure 12-17: Adding a device in your Xively Developer Workbench. 3. Type a descriptive name for your home sensing station. 4. Select whether you want your data to be public or private. When a device is private, the device and its data are accessible only to you (and those to whom you grant access); the information is not listed in Xively’s online public directory. When a device is public, all data about and created by it can be copied, shared, and modified by anyone, including for commercial purposes. 5. Click the Add Device button at the bottom of the page. After you add your Arduino, you are taken to the Xively Workbench. This is where you manage your device and its channels. At the top of the page, you are provided with a Feed ID and API key, as shown in Figure 12-18.

Figure 12-18: Setting up your data channels. Take note of your Feed ID and API key. 6. Click the Add Channel button to create a light level channel for your device. 7. Configure the ID of your channel, as shown in Figure 12-19. The first sensor is for light level, so type the word light into the ID field. 8. Configure the characteristics of your channel. You can add tags if you want, but they are optional. Leave the Units field blank. Because you are measuring light levels on an arbitrary scale from 0 to 100, type of 100 into the Symbol field. 9. Click the Save Channel button. 10. Repeat Steps 6 through 9 to add two more channels for temperature to your device, called temp1 and temp2. In this project, I use the Celsius scale. But you can use Fahrenheit if you change the code, as I described earlier in this chapter. In the Units field type Celsius (or Fahrenheit). In the Symbol field, type C (or F).

The channel names are used in your code. Make sure you use the exact channel names you use here. If you use different ones, you will have to modify your code to match them, or your sensor data won’t be posted to Xively. Figure 12-19: Configuring your device on Xively. 11. Note your Feed ID and API key. Your Arduino’s Feed ID and API key are shown in the lower-right corner of the page (refer to Figure 12-19). You need these for your code. The API is very long, so you should cut and paste it into a blank document or directly into your code. After you start posting data, you’ll be able to access graphs at the Feed URL shown at the top-right of the page. 12. To get ready for coding, open the example code for Chapter 12 from this book’s companion website, copy the code, paste it into a new Arduino sketch, and save the sketch. Get the example code from this book's companion website (www.dummies.com/go/arduinoprojectsfordummies). You modify it in the next section. You should now have a newly enabled Xively account with three channels but no data. These will be updated with data automatically when you send your data the first time. Programming Your Sensing Station When you set up your Arduino as a device on Xively, the Feed ID for your account and your device’s API key are assigned automatically. You program your Arduino to use your unique feed’s API key every time it updates your feed with new data. You modify the example code for this chapter to post data using the unique Feed ID and API key assigned by Xively. To program your Arduino to post data to Xively, you need to obtain two code libraries: one for connecting to Xively and the other for using Hypertext Transport Protocol (called HttpClient), which allows your Arduino to send data via the web. The code libraries for Xively and HttpClient

are included on the companion website with the code examples for all the projects at www.dummies.com/go/arduinoprojectsfordummies. Install the libraries into the Arduino Libraries folder for your operating system. If you are unsure about how to do this, it's explained in Chapter 3. The Xively and HttpClient code libraries are updated regularly. You can also get them from their code repository on a service called github, where developers store the latest versions. The github URLs for the two libraries are also provided in the code comments. Understanding the code With the libraries installed, you tweak the example code to communicate with your feed and device. The listing that follows shows how you alter the example code: #include <SPI.h> #include <Ethernet.h> #include <HttpClient.h> #include <Xively.h> #define API_KEY \"***** YOUR API KEY GOES HERE *****\" #define FEED_ID ***** YOUR FEED ID GOES HERE ***** byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; const int lightSensorPin=2; const int tempPin1=3; const int tempPin2=4; unsigned long lastConnectionTime = 0 const unsigned long connectionInterval = 15000 char sensorId1[] = \"light\"; char sensorId2[] = \"temp1\"; char sensorId3[] = \"temp2\"; // Create three datastreams for the feed XivelyDatastream datastreams[] = { XivelyDatastream(sensorId1, strlen(sensorId1), DATASTREAM_FLOAT), XivelyDatastream(sensorId2, strlen(sensorId2), DATASTREAM_FLOAT), XivelyDatastream(sensorId3, strlen(sensorId3), DATASTREAM_FLOAT), }; // Wrap the 3 datastreams into one feed XivelyFeed feed(FEED_ID, datastreams, 3); // Create the ethernet client and Xively client EthernetClient client; XivelyClient xivelyclient(client); void setup() { Serial.begin(9600); Serial.println(\"Initializing network\"); while (Ethernet.begin(mac) != 1) { Serial.println(\"Error getting IP address via DHCP, trying again...\");

delay(15000); } Serial.println(\"Network initialized\"); Serial.println(\"Ready.\"); } The important things to note in the preceding code are your FEED_ID and your API_KEY. You need to replace these with the ones assigned by Xively to your account and device, respectively. Cut and paste them into your code to make sure they are identical. Your Arduino uses them every time you upload data to your data feed to authenticate to the Xively servers. Above those are the four libraries you include in the sketch. In addition to Xively and HttpClient, you also are using SPI and Ethernet, which provide communication to your Ethernet shield and specify how it operates. Every device connected to an Ethernet network has what’s called a Media Access Control (MAC) address. You’ve no doubt heard of IP addresses. MAC addresses sit “below” IP addresses, at the hardware level. Each piece of Ethernet hardware on a network has to have a unique address. Normally, these are burned onto the board at the manufacturer, but you can assign your own, as I show in this code. Newer Ethernet shields have a label on the bottom with a MAC address. You can put that number here, or simply ignore it. As long as every MAC address is unique on your network, it won’t pose a problem. But if you have two Ethernet shields running this code on your network, you will need to set different MAC addresses for them. After the MAC address, the example sketch uses the three integers for the three analog pins from your test sketch: const int lightSensorPin=2; const int tempPin1=3; const int tempPin2=4; Next, the code declares two long integers to store the time in milliseconds, and the time you last posted data to Xively. You use these to set an update interval. The code specifies 15,000 milliseconds (15 seconds). If you want to update at a different interval, change it here. Your sensors have their own IDs, which correspond to the channels you created on Xively: char sensorId1[] = \"light\"; char sensorId2[] = \"temp1\"; char sensorId3[] = \"temp2\"; Make sure the names in the quotation marks are identical to the names you created for the three channels of your device. The channels are updated by a Xively data stream object called datastreams, which is an array

containing the three sensors. These three char variables uniquely identify each data stream used in your Xively account's feed, which correspond to the three channels you set up when you created your device: XivelyDatastream datastreams[] = { XivelyDatastream(sensorId1, strlen(sensorId1), DATASTREAM_FLOAT), XivelyDatastream(sensorId2, strlen(sensorId2), DATASTREAM_FLOAT), XivelyDatastream(sensorId3, strlen(sensorId3), DATASTREAM_FLOAT), }; Each data stream consists of its sensorID, which you created earlier, a variable to specify the length of the data being sent, and a float variable that contains the data itself (you can also use other kinds of variables). These values are added when your readings are posted to Xively. You could create many more streams here, limited only by your Arduino's memory. Each data stream corresponds to the channels you set up for your Xively devices, so you need a data stream for each channel. You wrap these three streams together to send them to your feed. The FEED_ID comes from the variable declaration at the top of the code that Xively created for you. The last value in the parentheses (3) specifies how many data streams you have: XivelyFeed feed(FEED_ID, datastreams, 3); The next lines create an Ethernet client and a Xively client for your Arduino to use to send data. The setup() section creates a serial port so that you can display what's going on for testing and debugging. It also establishes the Ethernet connection on your network, using an automatically assigned IP address. If you want to use a static IP address, you can do that, too. Chapter 11 describes how to use a static IP address with your Ethernet shield. Understanding the main loop In the main loop(), readings are posted to Xively with the sendData() function, which follows the main loop(). There's also a getData() function that verifies what was posted to Xively and prints it to the serial monitor. The getData() function is not essential, but it's good for debugging or live monitoring. Later, you use the getVoltage() function from your test sketch. First, you use your three temperature sensors and the sendData() and getData() functions so that you can send three sensor readings. Remember to change the values in the map() function of your lightLevel reading (shown in bold) to correspond to the values you obtained from testing your sensors, as described in the previous section. void loop() { if (millis() - lastConnectionTime > connectionInterval) { float lightLevel = map(analogRead(lightSensorPin),0,1023,0,100); sendData(0, lightLevel); getData(0); float temperature1 = ((getVoltage(tempPin1) -.5) * 100L);

sendData(1, temperature1); getData(1); float temperature2 = ((getVoltage(tempPin2) -.5) * 100L); sendData(2, temperature2); getData(2); Serial.println(\"Waiting for next reading\"); Serial.println(\"========================\"); lastConnectionTime = millis(); } } In this code, you use the same method to get the sensor readings you used in the test sketch and employ the sendData() and getData() function calls to send the values to Xively. The sendData() function sends the values to each channel and the getData() function allows you to read back the data from Xively, to make sure your code is working properly. The sendData function takes a parameter for which sensor to send and also the value to send. Recall that your sensor values are stored in a data stream array called datastreams[]. Each sensor has a position in that array, starting with the light sensor, which is at position 0. This number is the first value you put into the sendData() function call, followed by the lightLevel reading just taken. The getData() function contains the same number, 0, which refers to the light sensor: sendData(0, lightLevel); getData(0); You use the same code to take the temperature readings that you used in your test sketch. Because the positions for the temperature data streams in the datastreams[] array are 1 and 2, you use those numbers for the sendData() and getData() function calls: sendData(1, temperature1); getData(1); Take a moment to understand how the sendData() and getData() functions work. The sendData() function accepts two values, one for the position of the sensor in the datastreams[] array, and a second for the reading just taken. The local integer variable streamIndexNumber contains the number you used in the sendData() function call: void sendData(int streamIndexNumber, float sensorValue) { datastreams[streamIndexNumber].setFloat(sensorValue); Serial.print(\"Sensor value is: \"); Serial.println(datastreams[streamIndexNumber].getFloat()); Serial.println(\"Uploading to Xively\"); int ret = xivelyclient.put(feed, API_KEY); } The next line actually stores the value of the reading just taken into the datastreams[] array at

the position that was specified by your function call (0, 1, or 2, depending on which sensor was read), and sets the reading's value as a float: datastreams[streamIndexNumber].setFloat(sensorValue); The value is then printed to the serial monitor. The last line in the function finally sends the data to Xively, using a function from the Xively library, xivelyclient.put(). This is where your API key is needed. It's used to verify that you are allowed to post data to the feed. Don't share the key with others, or they'll be able to post to and read from your feed, too. The getData() function allows you to read back what you've posted (or read data from other feeds, if you have the API key). It takes an integer as input, and that integer specifies the position of the data stream (that is, the channel) in the feed that contains your sensor data: void getData(int stream) { Serial.println(\"Reading the data back from Xively\"); int request = xivelyclient.get(feed, API_KEY); if (request > 0) { Serial.print(\"Datastream: \"); Serial.println(feed[stream]); Serial.print(\"Sensor value: \"); Serial.println(feed[stream].getFloat()); Serial.println(\"========================\"); } } This function uses another built-in function from the Xively library, xivelyclient.get(), which gets your Xively feed using your FEED_ID and your API_KEY. In the printed output, you specify exactly which stream from your feed you want to print: Serial.println(feed[stream]); The stream you are printing is one of the three you've been posting from your datastreams[] array. Finally, you simply use the getVoltage() function from your test sketch and — voilà! — your code is complete. Making sense of your sensor readings Now take it for a test drive. Upload the code to your Arduino and turn on your serial monitor. You should see something similar to the output shown in Figure 12-20.

Figure 12-20: Monitoring your Xively feed posts in the serial monitor. To see what it looks like on Xively, go to your feed's URL on Xively. You can find your feed's URL in the upper-right corner of your Xively Developer's Workbench. My feed is at: https://xively.com/feeds/1424780519. Simply replace the number at the end with your FEED_ID. The reporting screen should look somewhat like mine, shown in Figure 12-21. You can use the gear widget to alter how your graphs look and to get custom embedded code that you can paste into your website, blog, or Twitter. If you are sharing tweets with your Facebook account, you can post them on Facebook, too. You will likely agree that using an Arduino and Xively to post your sensor data to the Internet makes a lot of sense!

Figure 12-21: Displaying your sensor data on Xively.

Part IV Advanced Arduino Projects Visit www.dummies.com/extras/arduinoprojects to learn how to use the LED cube pattern generator to create sequences of animation frames and play them back.

In this part . . . Learn about GPS and Arduino Build a GPS data logger Build a programmable LED cube Decode remote controls lying around your house Learn to program servo motors

Chapter 13 Building a GPS Data Logger In This Chapter Understanding GPS Building a GPS data logger shield Collecting data with your data logger Plotting your course using online maps and Google Earth You’ve no doubt used the Global Positioning System (GPS) either in your car or on your phone. GPS is everywhere — literally over our heads, all the time. Designed for the United States military to aid with defense systems, GPS uses a constellation of satellites to provide precise location information to any receiver that can receive and decode the GPS signal. This task was challenging, as you can imagine. GPSs in the early days were as big as a small suitcase. But these days, you can get a GPS receiver on a wristwatch! Only trouble is, many of the consumer products out there don’t give you the flexibility to do whatever you want with the GPS data. That’s where Arduino comes to the rescue! In this project, you can use an Arduino and a GPS shield kit to build a battery-powered GPS receiver that logs data to a mini SD card for several hours. You program your Arduino to collect the data, and you can then use it however you wish. Track your bicycle trips, hiking excursions, or walking tours. You could even stick the logger in a car to build up a log of driving habits and destinations. Ever have trouble remembering what parts of a city you explored while on vacation? Not anymore. Because you store the data in a standard format, you can make a plot of your trail, using tools online or applications, such as Google Earth. Building the GPS data logger shield itself is easy and takes under an hour. If you haven’t tried soldering before, this project is a good one to start with because it is pretty easy to do and you won’t be at much risk of damaging things if you have trouble getting the hang of it. You then test your data logger to make sure it is working properly. It will take another hour or so to get everything into your enclosure. Finally, you go out and collect some GPS data. You can then plot the map online, get the data converted for use with software, such as Google Earth, and even download an image file if you need one. Understanding GPS The Global Positioning System is a constellation of 32 satellites that are whizzing around about 20,200km (12,600 miles) above your head. They orbit once every 12 hours and are arranged so

that at least 6 satellites are always visible from anywhere on earth. Each satellite sends signals that include its exact position and the time when its message was sent. With this information from a minimum of 3 satellites, a GPS receiver can calculate your position based upon the transit time of the messages. Because GPS relies on signals from several satellites, it can take time for your GPS receiver to “get a fix.” GPS relies on line-of-sight, meaning signals from the satellites will be blocked by tall structures. If only two are visible from your location, it won’t be possible to calculate your latitude, longitude, and altitude until at least one more satellite pops into view. When you first build and test your project, it can take a while to get a fix, so it’s a good idea to place your receiver (or optional antenna) where it can get a good unobstructed view of the heavens above. Selecting Your Parts First, get together the parts and tools you need to build the data logger. You put everything into an enclosure, so you will need to do a little bit of light drilling for the power switch and the optional external antenna, if you choose to use one. You need the following parts, shown in Figure 13-1: An Arduino Uno An Adafruit Industries Ultimate GPS logger shield A micro SD or micro SDHC card A 9V DC battery and snap connector A single-pole, single throw (SPST) rocker switch, such as Jameco #316451 or Maplin # N19CL An enclosure, such as Jameco #2134926 or Farnell #1848692, or a translucent one from Maplin, #N07GC A scrap of pine wood or wooden strips about 1cm (1⁄4\") thick and cut to the same width as your enclosure (optional) Three or four short pan head screws, about 1cm (1⁄4\") long. You can also use pan head wood screws (#6 screws should do). A 3-5V external magnetic mount GPS antenna, available from Adafruit or Jameco #2153297 (optional) An SMA to uFL/u.FL/IPX/IPEX RF “pigtail” adapter cable (optional) from Adafruit or other online sellers An adaptor to read the micro SD card, using your computer or laptop You need to build this project with an Arduino Uno, Arduino Duemilanove, or Diecimila. You can

also use an Arduino Leonardo or a Mega, but they need some modifications to the code to work correctly that I don’t cover here. If you plan to use one of the latter, you should check out the Adafruit website that has detailed instructions for using other Arduinos. The workhorse of this project is the Adafruit Ultimate GPS Logger Shield. It contains all the key components needed to get and record GPS data, including the GPS receiver, and an SD card slot. It also has a prototyping area in case you want to add additional features to your data logger. Getting a GPS module to work can be kind of tricky because you need some additional components to be able to connect it to an Arduino. The cool thing about this shield is that all these components are already connected, tested, and ready to go, so you can focus on building the project and not on troubleshooting why your GPS receiver isn’t working. You can download schematics and full-color parts placement diagrams from the companion website (www.dummies.com/go/arduinoprojectsfordummies). Figure 13-1: The parts you need for this project. You can find a micro SD or SDHC card just about anywhere these days. I picked one up from the supermarket for about five bucks. You are only recording text data to it, so you don’t need a big one. Go for cheap. Even with a 2GB card, at one reading per second, you’ll be able to store millions of positions before you run out of room on it. And your battery will die long before that. You need to make sure you have a micro SD card reader so that you can copy the data from the card to your computer or laptop. You can get a micro SD to USB adaptor for about five bucks on Amazon or eBay. To take your data logger into the wild, without your computer or laptop, you need to keep it powered up and you need a way to turn it on and off. This means a battery power supply and

power switch. To get everything into a portable, small enclosure, use a standard 9V DC battery and 9V battery snap connector. You power the Arduino directly from the clip, which you solder onto the GPS shield. My tests conclude that a standard rectangular 9V battery lasted about five and a half hours. Because battery life is directly related to the chemical action of the battery materials, larger batteries will yield longer life. If you decide you want longer staying power, you can replace the 9V battery with a 9V battery pack that holds six AA cells, using the same style snap connector. These will substantially extend how much data you can collect. To switch it on and off, I used a slimline rocker switch that gives the project a nice professional finish and is very inexpensive. The tricky part of using square-shaped rocker switches is that you need to bore a square hole in your enclosure. You can also use simple toggle switches that use a single, round bore hole, but these will stick out from the side of the box and could be easily switched off accidentally. You need a small plastic enclosure to protect your project. An ABS plastic one is fine and is easy to cut into for the power switch and antenna. Jameco and Farnell offer a made-for-Arduino custom enclosure that works well, but you won’t be able to see the status lights and you need an antenna. I found a translucent blue one from Maplin, which means I can also see the status lights on the shield. If you use a clear box, you might be able to get away without using an antenna at all, but you’ll have to try it out to be sure. A metal box blocks the signal, so get the antenna if you are using one. You need to hold your Arduino firmly in the box, but project enclosures rarely have the right internal supports (called “bosses”) for your Arduino. Instead of screwing your Arduino into the plastic, you glue the short strips of wood into your project enclosure so that you can attach your Arduino to it with three or four pan head or #6 wood screws. The length of the screws should be about the same as the thickness of the wood strips, or slightly longer, as your Arduino will not sit completely flush against the wood. If you are using an enclosure specially designed for Arduinos, you won’t need the strips of wood or the screws. GPS requires an unobstructed, line-of-sight view to the satellites that provide the tracking signal. Your GPS shield has an integrated antenna onboard. However, its sensitivity is limited. A plastic enclosure shouldn’t interfere with the antenna, but using an external antenna provides greater sensitivity, although it will draw a little more power. Many GPS extension antennas are out there, and the magnetically mountable ones can be easily slapped onto the top of a car or a bicycle frame. If your antenna has an SMA connector and is made for GPS, it should work. The antenna connector on the shield is a tiny little u.FL connector, which keeps the shield compact. However, most GPS antennas use a co-axial “sub-miniature version A” (SMA) connecter, which is threaded. So, to connect the GPS antenna to the shield, you also need a short “pigtail” SMA to u.FL adapter.

The u.FL connector is known by several industry names, including IPX, IPEX, and UMCC, but they are all the same design. You can easily find a pigtail adaptor for one of these connectors on eBay or Amazon and Adafruit also sells them. If you are using a plastic enclosure like the one in the parts list, you need a couple of tools for cutting the holes in the enclosure for the power switch and the antenna. You need either a hand drill or a power drill and approximately 7mm (1⁄4\") drill bit for your switch. If you are using a square toggle switch, you’ll need to square up the holes with a fine hand file. Building Your Project Building your project is done in three steps. First, you assemble the GPS shield and test to make sure it’s working correctly. You then program and upload code to enable the data logger. Finally, you check to make sure you are logging data to your SD card. This project is really simple, so there’s no wiring schematic, and you don’t need to prototype it on breadboard. Assembling and testing the GPS shield Putting the shield together is really easy. All you have to do is attach the pin headers and insert a battery. What could be simpler? First, fire up your soldering iron and make sure that it’s ready to go. Then do the following steps to put it together: 1. Separate the strip of pin headers included with your shield into groups that match your Arduino’s header sockets. It’s a good idea to use a pair of needle nose pliers to snap off the required number, as shown in Figure 13-2. That way, you can be sure that you’ve got the right number of pins in each segment and they break off cleanly. You also won’t inadvertently snap the strip where you don’t intend. Make sure that you count carefully. The Arduino header sockets do not all have the same number of holes! 2. You use your Arduino as a support for your pin headers while you solder them onto the shield. Insert the pin headers into your Arduino’s header sockets, as in Figure 13-3. 3. Seat your GPS shield onto the pin headers. You may need to wiggle things around a bit in order to get the shield in place. Make sure all the pins extend through the top of your shield and that there are no missing pins, as shown in Figure 13-4.

Figure 13-2: Snapping off the right number of pin headers. Figure 13-3: Using your Arduino as a soldering support.

Figure 13-4: Placing your shield into position for soldering. 4. Now use your soldering iron to solder each of the pins to your shield. If you are right handed, start at the left side (and start at the right if you are left handed). That way you will be able to see your work as you go along. Refer to Figure 13-5. After you’ve soldered the shield to your pins, you’re almost ready to perform your maiden voyage — a test to make sure your GPS shield is working. Your shield has two operating modes: direct connection and software serial, which are selected by a tiny switch on the shield, shown in Figure 13-6. In the direct connection mode, your Arduino doesn’t run any code. Instead, it acts as an intermediary to your shield, so that you can communicate directly with the GPS module’s serial interface. You use Arduino IDE serial monitor to send and receive commands directly to the GPS module on your shield. This is useful for testing the GPS unit, and for sending configuration commands if you want to change how it operates. When you are satisfied with the tests, you can put the GPS shield into software serial mode. Your Arduino has one serial port, which it uses to communicate with your computer. It’s physically connected both to your USB port and digital Pins 0 and 1. However, when you want your Arduino to control your GPS module, you also need a second serial port to connect to it and send commands. That’s where the software serial port comes in. Software Serial is a library that allows your Arduino to use additional pins for serial communication. It’s the only way you can send and receive serial data to other devices while you also monitor your Arduino with your computer. The soft serial switch lets you switch between the two.

Figure 13-5: Soldering your shield to your pin headers. Figure 13-6: Switching communication modes on your Arduino. Because of the digital pin layout, direct connection using this switch only works on the Arduino Uno, Duemilanove, Diecimila, Arduino compatible, or Arduino Mega. To use direct connection mode for testing the GPS module, you first upload a “blank” sketch onto your Arduino. Open your Arduino IDE and type the following into a new sketch:

void setup() {} void loop() {} Save this sketch with a name you’ll remember, such as “blank.” Switch your shield to “Soft Serial” mode so that you can send this code to your Arduino. Then, connect your USB cable and upload the blank sketch. Now that the code is loaded, you can test your GPS module and monitor its output directly from the GPS chip. Flip the switch on your shield to Direct, as shown in Figure 13-7. This connects your USB serial connection directly to the GPS module. Later, when you are ready to use your shield for data logging, you will switch it back to the “Soft Serial” setting. If you have uploaded your blank sketch code, the red “FIX” LED should be flashing once per second. If not, you may need to cycle the power. Unplug your USB cable, make sure that you have set your switch to “Direct,” and then plug it back in. If the red LED still isn’t flashing, you might have a problem with your soldering or your board. Figure 13-7: Switching to Direct Connection mode to test the GPS module. Open your Arduino IDE and click on Serial Monitor, making sure it is set to 9600 baud in its drop-down menu. You should see output similar to that in Figure 13-8. If you do, your module is working correctly, though it hasn’t picked up any satellites yet. Nonetheless, it still sends data so you know it’s working.

Figure 13-8: Viewing output directly from your GPS module. This text is pretty hard to interpret unless you know what the GPS module is saying. It uses the National Marine Electronics Association (NMEA) format and outputs data for four different GPS data standards, each on a separate line and preceded by a \"$\" sign. The one you are interested in is the Global Positioning Recommended Minimum sentence ($GPRMC). This line gives you the following information, as shown in Figure 13-9: The NMEA sentence format used Time in Greenwich Mean Time (GMT) A satellite “fix” code: Active (A) or Invalid/Void (V) The longitude in decimal degrees The longitude hemisphere, north (N) or south (S) The latitude in decimal degrees The latitude hemisphere, east (E) or west (W) The latitude, longitude, and hemispheres contain nothing if there is no fix — so you will just see commas with no data until you go outdoors to get a fix! The speed of travel over land (in knots). The “azimuth” or direction of travel. An azimuth is just a “compass” direction, which is a horizontal angle around the horizon, measured in degrees (0–360). 0 is north, 90 is east, 180 is south, and 270, west. The Coordinated Universal Time (UTC) date, starting from Week 1 in “GPS time” (which started in January 1980). This is updated when your GPS receives the correct current GMT from satellites — but it hasn’t seen one yet. A checksum, preceded by an asterisk, which tests the raw data for transmission errors. When you can see this information, you know the GPS unit is alive and well. You’re now ready to

hunt for satellites! If you are using a laptop, you can go outside to check whether you can get a fix from the GPS satellites. If you are using a desktop and the optional extension cable and pigtail adaptor, you might be able to get a signal by sticking the antenna out of a nearby window. Attach the antenna as described at the end of this chapter to make sure your module is working before you build the enclosure. Figure 13-9: Interpreting raw NMEA data from your GPS module. Be patient! It can take a while to get a fix from the GPS satellites. In the best case, you’ll get a fix in about a minute. However, you may have to wait 10 or 15 minutes or even longer, depending on the situation overhead. But after you do get a fix, you’ll receive updated tracking data every second. Your GPS module will also start reporting the position data to your serial monitor. The red LED labeled “FIX” on your shield will flash once every second until you get a fix. Afterward, it will flash once every 15 seconds as long as it has a fix. If it loses the fix, it will revert to flashing once per second. If you are able to take your GPS module outside or if you have are using the optional long antenna, you may be able to get a fix while you are connected directly to the GPS module. Your status code will change to “A” and you will receive latitude and longitude information. The GPS logger shield has an onboard Real Time Clock (RTC). The button battery is to keep this powered up when you aren’t using it. However, your GPS module gets the time for the satellites. So you don’t need this unless you write code to support it. If you do insert your

button battery, your GPS module might stop operating after about 20 seconds unless you’ve set up the RTC. So keep it out during testing. Programming your data logger Now that you’ve communicated directly with your GPS module, you can upload code to log data to your SD module. You need to switch the GPS module back to Soft Serial if you aren’t communicating directly to the GPS module. All the code you’ll upload to the board requires Soft Serial. The code for this project is on the companion website for the book, www.dummies.com/go/arduinoprojectsfordummies, and is in a zipped file containing the files you need: The data logging sketch that runs on your Arduino, called shield_sdlog. A library that interfaces with the GPS module, called Adafruit_GPS. A library that writes data to the SD card, called SD. The library that allows you to create “virtual” serial ports, called Software Serial. Software Serial is a “core library,” so it is part of the Arduino IDE 1.0 installation. If you are using an older version of the IDE, you should update it. You can hunt for these yourself online or on github, the code sharing website (see: https://github.com/adafruit/Adafruit-GPS-Library). But to make things easier, these are all in the Zip file for Chapter 13, on this book's website. You should download the Zip file now and extract the files to your system. To make things easier, I've renamed the Adafruit library on the companion website to Adafruit_GPS. The Adafruit library on github extracts to Adafruit-GPS-Library-master and you'll need to rename it for the code to work properly. Refer to the instructions on installing libraries in Chapter 3. After you’ve downloaded the files, fire up the Arduino IDE. If it’s already running, you need to restart it so that the new libraries will appear in your Application menus. Now, navigate through the menus and select File→Examples→Adafruit_GPS→shieldlog_sd. It’s not necessary to go into the gory details of how each of the code lines work. But you should focus your attention on the following lines: // see if the card is present and can be initialized: if (!SD.begin(chipSelect, 11, 12, 13)) { //if (!SD.begin(chipSelect)) { // if you're using an UNO, you can use this line instead Serial.println(\"Card init. failed!\");

error(2); } This project uses an Arduino Uno, so you need to add two forward slashes to comment out the first line and then remove the comment from the second line beginning if (!SD.begin. Otherwise you will get an error. The rest of the code handles the following things: It creates the variable GPSECHO, which you should leave set to true while you are testing your module. It sends all that data to the serial port so you can see what’s happening. Later, you can turn it off, if you wish. It creates the variable LOG_FIXONLY, which makes sure that entries are only recorded to your SD card if your GPS module has a fix. Leave this “false” until you are finished testing. It makes sure that you are able to write a fresh file to the SD card, and sequentially numbering new files. It establishes communication with the GPS module and kick-starts it. It writes the data received from your GPS module onto the SD card, inside the newly created file. A new file with a two-digit sequence number is created whenever you power up your module. Take a moment to look through the code before uploading it to your Arduino. If you plan to try out any of the other example sketches included in the Adafruit library (which I highly recommend), be sure to change the lines referring to Software Serial at the top of the sketch so that you are using Pins 7, 8 and not Pins 2, 3. Otherwise you won’t see any output in the serial monitor. Testing your data logger After you’ve made the changes to your code, connect your USB cable to your USB port, select the correct serial port for your Arduino from the Arduino IDE, and upload your code. You don’t need to remove the GPS shield before you upload your code. Make sure the switch is set to Soft Serial. When uploading is finished, enable the serial monitor in your IDE. Make sure your baud rate is now set to 115200, or you will see gibberish on the serial monitor. If you are indoors, you should see output very much like what you saw when you were directly connected to the GPS module during testing. If you happen to be outdoors, or you have used the GPS extension antenna and placed it outside a window, you may just start to see some GPS data after a while. Figure 13-10 shows a diagram of the output from your GPS module when you are receiving data. You should see output similar to this in the serial monitor. It’s much the same as your earlier test, but now it has information in the previously blank fields.

Remember, it can take anywhere from a minute to 15 minutes before you see any GPS data. Once you are happy that you’ve got it working properly, make two final changes to the code: 1. Set the GPSECHO variable to false. You don’t need to echo data to the serial monitor when you are logging data and not connected to a computer. 2. Set LOG_FIXONLY to true. You are only logging data when you have a fix on GPS satellites. When you’ve edited these values, you can disconnect your data logger from your computer. Make sure that the switch on top of the GPS shield is set to Soft Serial. Now you are ready to build your enclosure and secure the module inside its new home! Making the enclosure Assembling and programming the shield was the easy part. Making the enclosure is just about as easy. All you need to do is provide holes for the switch and the antenna connector, solder the power switch, and solder the snap connector for your battery onto the shield. Figure 13-10: Receiving GPS data from your GPS module. You need your hot glue gun for this part, so plug it in and allow it to warm up while you do the following steps, referring to Figures Figure 13-11 through Figure 13-14: 1. Use your drill bit to bore out the hole for the rocker switch. It may be easier to bore two adjacent holes and then remove the material between them. 2. If you are using the optional antenna, bore a hole for it using the same bit. I placed mine next to the hole for the rocker switch, as shown in Figure 13-11. 3. Use a small file to make the hole for the power switch nice and square. See Figure 13-12.

I did not drill a hole for the USB connector because I wanted a tightly enclosed box. You might find it easier to bore a hole for your USB connector if you plan on frequently programming your GPS module. I’ve found it’s more likely that I just “set it and forget it,” so I didn’t bother to create a hole in the enclosure for my USB connector. 4. Insert your power switch into the enclosure. Figure 13-11: Drilling holes for your power switch and antenna.

Figure 13-12: Filing the hole for your rocker switch. 5. If you are using an external antenna, insert your antenna pigtail adapter into the enclosure. Be sure to use the washers provided, with the serrated washer on the inside of the enclosure and the lock washer and retaining nut on the outside of the enclosure, as shown in Figure 13-13. 6. Now insert your scraps of pine into your enclosure to estimate where you want to place your Arduino. You need to leave enough room for the 9V battery and to make sure your power switch won’t touch your Arduino. 7. Use your hot glue gun to apply glue to the wood and press it firmly into the bottom of the enclosure. See Figure 13-14. Figure 13-13: Mounting your power switch and pigtail SMA antenna adapter. Figure 13-14: Positioning your Arduino and gluing your wood on the enclosure. 8. Test the position of your Arduino and GPS shield “sandwich” on the wood inside your enclosure, making sure that it doesn’t touch the contacts of your power switch. Adding the power supply The power supply is simply your 9V battery connected to the switch. The positive lead is connected to one side of the rocker switch. The other side is connected to the Vin pin on your GPS shield, which is connected to your Arduino’s power input pin (through a pin header on the shield). The negative lead goes straight to your ground pin. Do the following steps, as shown in Figures Figure 13-15 and Figure 13-16:

1. Solder the red, positive wire from your 9 volt battery clip to one side of the switch. It doesn’t matter which side. (The battery clip should not be connected to any battery.) 2. Solder a jumper wire or other spare piece of wire to the other side of your switch. If you have a red one, that’s even better. 3. Separate your GPS shield from your Arduino and use three or four of your wood screws to secure your Arduino to the wood, as shown in Figure 13-15. 4. Insert your mini SD card into the shield, as in Figure 13-16. Be careful when you insert it. The spring inside has a tendency to make the card fly out of your hands if you don’t hold it steady. Don’t insert the small button battery until you are finished testing. 5. Now insert your GPS shield back onto your Arduino, taking care to make sure you’ve slotted it into the right holes. Figure 13-15: Soldering the power switch connections and installing your Arduino. Figure 13-16: Installing your mini SD card and battery (after testing).

6. If you are using an external antenna, insert the u.FL connector into the socket on your GPS shield, as shown in Figure 13-17. It’s a tiny little socket located just below your mini SD card slot. The u.FL connector is not made for heavy use. Instead, it’s optimized for size. After you’ve connected your pigtail adapter to it, you should leave it in place and try to avoid connecting and disconnecting it repeatedly. To keep the cable out of the way, I routed the cable underneath, between the shield and the Arduino. Figure 13-17: Connecting the optional external antenna adapter. 7. Now, solder the red power wire from your power switch to the input power pin labeled Vin, as shown in Figure 13-18. 8. Carefully solder your black ground connection from your battery connector (still not connected to any battery) to the input labeled GND on your shield, which is connected directly to the GND input on your Arduino. Actually, there are two holes labeled GND. You can use either one of them, but I find the hole that is farther away from the Vin pin is easier to solder. 9. Make sure your power switch is turned off and attach your battery, as shown in Figure 13- 19. 10. Screw the lid back onto your enclosure. 11. Attach the optional external GPS antenna. 12. Turn the power switch on.

Figure 13-18: Soldering your power input wire. Figure 13-19: Connecting your battery and external antenna. Collecting and Plotting GPS Data Now you are ready to go out into the wild and start collecting routing data. If you’re using it, you can slap the external antenna onto your car or bicycle or any other ferrous metal surface. The steel panels of a car work great. I snaked my antenna through the sunroof and hit the road. Tracking your path Before you set off on your data logging adventure, make sure that the “FIX” LED is blinking once every 15 seconds. If it is blinking once per second it has not yet acquired the signal of at least three satellites and so won’t write data to your SD card.

If you are using a single 9V battery, you can expect about three to five hours of tracking time. If you switch off the receiver during your journey, the code will automatically create a new log file. It automatically increments the numbers on the suffix of the filename. When you’ve got your data collected, you can switch off the unit and remove the SD card. Plotting your data Depending on how long you were tracking, your log file will contain a long list of GPRMC sentences, with each reading on a separate line. You should see text like that in Figure 13-10, but with geographic coordinates that match your own trek. If your log file looks similar to this, you are ready to plot the data as a map. There are several ways to do this, but the raw GPRMC sentence is not in a format that can be easily read by most mapping websites and software. If you want to plot the coordinates using a tool like Google Earth, you will need to convert your raw data into the .kml format. You can do that and a whole lot more using Adam Schneider's excellent gpsvisualizer.com website. To plot your map, do the following steps, as shown in Figure 13-20: 1. Open your web browser and navigate to gpsvisualizer.com. 2. In the box labeled Get Started Now, click the Choose File button and locate your data file on your computer. 3. Choose an output format from the drop-down menu. The default is Google Maps. If you want to get an image file you can download, you should select the image file output format that you want from the menu. Depending on the size of your file, it will take a few moments to process the data. You should soon see output like that in Figure 13-20. 4. You can select the link at the top of the page to download an HTML file that contains a link to Google Maps, which will draw the map for you. Figure 13-20: Plotting your data on gpsvisualizer.com. If you would like to explore the map in Google Earth, which also allows you to save an image file, you can also select the output as a .kml file on the main landing page for gpsvisualizer.com. The text files generated by your data logger are pretty small. The 5½-hour log file I generated in Figure 13-20 contains 24,380 lines of text, but only takes up 1.7MB of space on the card. So even with a small 2GB card, you can leave your data files on the SD card and keep on adding more for

a long time. However, it is a good idea to occasionally copy them to your local system for safekeeping. Now head out there and get tracking ’til you drop!

Chapter 14 Building a Remote-Controlled Car In This Chapter Decoding a remote control Using servo motors Programming steering commands Building a three-wheeled chassis You can buy remote-controlled car kits in hobby shops, but building your own is much more fun — and it’s easy to do with an Arduino and a little ingenuity. In this project, you create a fully drivable remote-controlled (RC) car by using an ordinary household remote control, an Arduino, and servo motors. You use your Arduino to decode the signals coming from any of your remotes and then use the decoded signal to tell your car to move forward, backward, and turn. One cool thing about this project is that after you figure out how to use any old remote control with your Arduino, you can transfer this capability to just about any other project that you want to add a remote control to! You can download schematics and full-color parts placement diagrams from the companion website (www.dummies.com/go/arduinoprojectsfordummies). Selecting and Preparing Your Parts The parts you need are shown in Figure 14-1. You should get together the following components to build your car, which will take about five hours from starting gun to finish line: An Arduino A remote control TSOP2438 or TSOP4838 Infrared Receiver Module (Vishay Semiconductor) (Mouser Electronics 782-TSOP2438, and RS Components #708-5070). Alternatively, use a PNA4602 module. Two continuous-rotation servo motors (such as GoTeck GS-3360BB, Futaba 900-00008, Jameco #283039, or the Arduino Servo Module, Rapid #73-4464) A battery holder for six AA batteries and a 9V battery clip

Six AA batteries Eight pin headers A breadboard For the chassis: Two cylindrical cans of Pringles brand potato chips Two rubber bands about 8cm (3-4 inches) A piece of scrap plywood or balsa wood, at least 11 x 17cm (4 x 7 inches) A ball caster kit (Tamiya Brand — or Jameco #358336 or Cool Components #000984) Mounting hardware or hot glue Self-adhesive hook-and-loop fastener (optional) Figure 14-1: The parts you need for this project. You can use any Arduino for this project. An Arduino Uno is shown in the figures. The awesome thing about this project is that you can use pretty much any remote control you have in your house. You don’t have to use the Toshiba remote shown in Figure 14-1. We have six of them, and we only use two, so I grabbed a spare one. You should select a remote that has arrows in the directions that you want to drive: left, right, forward, reverse, and — the all-important — stop! I got one of our old television remotes because it has a circular input pad, with a button in the center, which is a good place for the “brakes.” It is possible that during testing, your remote will not be detectable. You might need to try a different one if you can’t detect it during your testing. The key component of this system is the Infrared (IR) Receiver module, a Vishay Electronics

TSOP2438, which operates on the 38KHz carrier frequency. Other frequencies are used as well, but you need to detect 38KHz, one that is most common to household remote controls. The component works by sensing the infrared light patterns emitted by your remote and translating them into digital output signals your Arduino can read using a special IR library. Only infrared light can be detected by the sensor — its epoxy case acts as a filter on other light frequencies. However, ambient light has infrared signatures, too. For example, a fireplace is a great source of heat and is also in the infrared spectrum. So this component is designed to ignore such stray noise. Servo motors come in two flavors: 180 degree sweeping motion, or continuous rotation. Because you are using these motors for propulsion, you must get continuously rotating servos, such as the ones listed. The servos operate at 5V DC and can be somewhat power hungry. They also come with an accessory kit that contains mounting plates and armatures and an assortment of screws for mounting them. You need an additional angle bracket if you want to mount the servos using this hardware. You can also simply mount them to your car with hot glue. You use a 9V battery pack for the project. You could use a single, rectangular 9V cell, but it won’t last very long. The servo motors are pretty power hungry. You should get a 9V battery pack that holds six AA cells. They offer a nice balance between lifespan and weight. The heavier C or D cells last longer, but they may be too heavy for your car to move easily. Look for a battery holder that has a snap connector like those used for 9V batteries. This makes it easier to detach your battery pack from your car when it’s time to reload. Figure 14-1 appears to show a pack containing two cells, but that’s because the other four batteries are underneath the top two. You need eight pin headers. The longer ones are easier to work with. You use two for your battery pack, and the other six to connect your servos to the breadboard. Pin headers usually come in long strips, so just break off a short section of two pins and two short sections of three pins each. For the chassis, you can use any small piece of wood you might have lying around. The styling of the chassis is up to you, but the frame itself is carrying the weight of the components and the more weight you have, the more durable your design needs to be. A piece of scrap plywood should do nicely. You can also use plastic, balsa wood, or even cardboard, as long as it’s large enough to support all your components and the material is not too heavy. Probably the tastiest part of the project is the two cans of Pringles, which you use as the car’s wheels — sadly, not the fuel. You can use almost any kind of rigid disc as a wheel, but Pringles (in addition to being edible) are easy to get, cheap, and the cans have a metal base. You need two wheels, so that’s two cans. You can use small or large cans, since you are only using the metal base. I’d recommend large cans (more chips to eat!). You also need two rubber bands that can fit snugly around the cans without distorting them. Without them, your wheels won’t get very good traction. If you want to get fancy, you can buy a huge variety of remote-controlled car wheels at

hobby shops or online. Just make sure that you can easily attach them to the shaft of your servo motors. You also need a hammer and a small nail to attach the wheels to your servos, and a hot glue gun, if you wish to glue the servos to your chassis instead of mounting them with bolts. The benefit of hot gluing your servos to your chassis is that it’s quick and easy. The drawback is that you will have to rip them off if you ever want to reuse them for another project. You can use a small section of self-adhesive hook-and-loop fastener (commonly called Velcro) to affix your battery pack. Building Your Detector and Drive The most important step comes at the beginning. Eat one of the cans of Pringles! You’ll need to empty the cans before you build the car. After that’s out of the way, you can proceed with getting your remote control to talk to your Arduino. After you decode your remote control, you can test your servo motors and program them to drive your car. Building your circuit on the breadboard The schematic in Figure 14-2 shows the circuit diagram of the car. The design is simple because both the IR sensor and the servos can be controlled without any additional components. Figure 14-2: Schematic diagram of the RC car. Follow the parts placement diagram in Figure 14-3 to hook up the detector and motors to your Arduino. The infrared receiver module is inserted into the breadboard, facing upward so that it can see the signals emitted by your remote control.

During final assembly, you attach the breadboard directly to your car’s chassis, so if you want a clean look, keep the wiring tidy. The IR receiver module only requires connections for power, ground, and the signal output. It detects infrared signals that are sent from the front of your remote control. There is an infrared LED on your remote control (it may be behind a little plastic window) that sends out coded pulses of infrared light that correspond to each button. Because the light pulses are infrared, your eyes can’t detect them. The infrared receiver module can though, and it decodes these infrared pulses into digital high (+5V) and low (0V) voltages, which are sent to the module’s output pin. To test whether your remote is working, you can point it to a digital camera or some smartphone cameras, which can see the pulses. This is especially useful if you are using a remote control that has been separated from the appliance that it was originally paired with. Connect the IR receiver module, as shown in Figure 14-3, with the output connection going to digital Pin 2. Make sure that the dome of the IR receiver is pointing upward or it may not be able to detect your remote when you send commands. Using the pin headers makes it easy to attach and remove your servos. Use the pin header strips with three pins each to connect the servo motors to your breadboard. Connect the signal wires to digital Pins 9 and 10. In fact, as long as your code specifies the correct pins, you can use any pins labeled with a tilde “~” because those pins can output pulse-width modulation (PWM). You use PWM to control the movement of the servo motors. Your Arduino employs pulse-width modulation to generate smoothly changing output, which approximates an analog signal. I describe pulse-width modulation in more detail in Chapter 5. You add the battery pack later. Right now, you need to connect your Arduino to your computer so that you can use the serial port to display the pulses that are decoded by the IR receiver.

Figure 14-3: Parts placement on the breadboard. Coding the detector After you’ve placed the components, you need to test your remote control so that you know the values that it spits out for different buttons. Take a look at the following code to make sure it makes sense to you, and then upload it so you can test your remote control. #include <IRremote.h> const int irReceivePin = 2; // pin connected to IR detector output IRrecv irrecv(irReceivePin); // create the IR library decode_results results; // IR results are stored here void setup() // Start the IR receiver { Serial.begin(9600); irrecv.enableIRIn(); } void loop() { if(irrecv.decode(&results)) { showReceivedData(); irrecv.resume(); // Receive the next value } delay(250); } void showReceivedData() { if (results.decode_type == UNKNOWN) { Serial.println(\"-Could not decode message\"); } else { if (results.decode_type == NEC) { Serial.print(\"- decoded NEC: \"); }

else if (results.decode_type == SONY) { Serial.print(\"- decoded SONY: \"); } else if (results.decode_type == RC5) { Serial.print(\"- decoded RC5: \"); } else if (results.decode_type == RC6) { Serial.print(\"- decoded RC6: \"); } Serial.print(\"Value = \"); Serial.println(results.value, DEC); // Print the results as a decimal value } } The first line imports the Infrared Receiver library. This library is an excellent resource that was written by Ken Shirriff. The library decodes the raw data pulses that your IR receiver is sending to Pin 2. Download a Zip file of the library from this book's companion website, www.dummies.com/go/arduinoprojectsfordummies, or from https://github.com/shirriff/Arduino-IRremote, where the latest version of the libraries is hosted. To install, do the following: 1. Extract the zipped archive. 2. Rename the directory, which will be named something similar to “shirriff-Arduino- IRremote-xxx” to IRremote. 3. Move the IRremote directory to your Arduino libraries folder. On a Mac, this is typically just Documents/Arduino/libraries/libraryname/libraryname.cpp, and on Windows My Documents/Arduino/libraries/ libraryname/libraryname.cpp. 4. Restart the Arduino IDE. You should see some example sketches under the menu: File→Examples→IRRemote. If you aren’t sure how to install libraries to the libraries folder on your system, refer to Chapter 3, which has general instructions on what you need to do. This library handles four of the most common types of remote control signals: NEC, SONY, RC5, and RC6. Different manufacturers use different encoding protocols, but your remote is probably using one of these standards. There is also support for other kinds of remote control in the library, but you have to go digging around in the library code files to enable them. The first variable, irReceivePin, stores the pin number your IR module is connected to. Then you create an IR receiver object called irrecv, which takes as a parameter the variable that specifies to which pin (Pin 2) the module is connected. The data that is decoded by the library is presented within a special decode_results object called results. After specifying these variables, you use setup() to open a serial communication channel, so you can report the decoded key codes. You then enable the input by using a function of the irrecv object called irrecv.enableIRIn().

The main loop() decodes the results and displays them. The irrecv object you created has a decode() function, which knows whether there are decoded values. The if statement tests whether there are results to look at and if so, executes the showReceivedData() function. After that, the irrecv.resume() function prepares the module to get the next button pressed. The delay in the loop is to provide you time to read the results on the output window. If there is no delay, the button presses will spew out of the Arduino very quickly. This would not normally pose a problem. However, when you hold down a button or press the same one many times, some remote controls send a “repeated key” result instead of simply repeating the last button you pressed. The showReceivedData() function does the work of displaying the key code for the button you pressed. The value of the last key press is stored within a results class that knows about the different types of remote control protocols. The if statement tests whether the decoded results are of a known protocol type and if not, reports an error. Otherwise, the further series of if statements tests to determine which type of result was received and prints this to the serial monitor. The last statement prints the actual value that was decoded: Serial.println(results.value, DEC); You can output several different data formats, so DEC specifies that you want to get it as a regular old decimal number. Reading your remote control codes To check your remote, open the serial monitor in your Arduino IDE and press a few buttons on your remote control. You should see something similar to Figure 14-4. This is the result of pressing the numbers 0–9 on my Toshiba LCD TV remote control. Figure 14-4: Example output of remote control codes. After you’ve got some readings on your monitor, press the buttons you want to use to control your car. You need forward, reverse, left, right, and the all-important STOP, which is essential for avoiding collisions. I added one last button (a red one), for “Turbo!” mode, which really pours on a bunch of speed. Choose a good button for Turbo mode. Make a note of the codes that your remote generated, because you need these for the next part of the sketch. Coding the drive motors When you’ve got the six codes, you just need to associate them with actions to drive your motors.

Add the next part of the Arduino sketch so that you can test your motors. Before setup(), add the following code (new code in bold): #include <Servo.h> #include <IRremote.h> IRrecv irrecv(irReceivePin); decode_results results; const int rightMotorPin = 9; const int leftMotorPin = 10; Servo rightServo; Servo leftServo; int rightSpeed=90; int leftSpeed=90; long keyCode=0; The first instruction adds a Servo control library, one of the standard ones that’s included with your Arduino IDE. The Servo library contains all the instructions needed to send pulses to your servo motors by using PWM. You don’t want to have to write these yourself (which truly would be akin to reinventing the wheel!). It’s customary to put all the libraries at the top of your code. That way, you can refer to them later when you create objects that use their capabilities. You next create two integer constant variables to keep track of the pins you've got your servos attached to and assign these the values of the digital pins you used, 9 and 10. Two slightly cryptic lines each create a Servo object, one called rightServo and one called leftServo. You can now send instructions to the servo objects, and they'll respond to them. The main instruction you’re sending is the direction the objects should turn. Continuous rotation servo motors take values from 0–180 degrees, and the center point, 90, means stationary. Sending a value below 90 rotates the shaft left, and above 90 rotates right. The farther from 90 you go, the faster the rotation speed, up to the limits of the servos’ capabilities. You need to store the value that you are sending to your servos, so the variables leftSpeed and rightSpeed take care of this. You increment and decrement these values to turn your servos. Setting them to start at 90 means your car will remain stationary when you start it up. The last long integer variable, keyCode, stores the decoded value that you will obtain from the IR library. You use this value to determine which rotation rules to apply to your servos. If you find that one of your servo motors is turning consistently too slowly, you can increase the value by which its speed is incremented. Just make sure that you use whole numbers only. You use PWM for the motors and PWM values can only be whole numbers from 0 to 255. Now add the following code to your setup() (new code in bold):

void setup() // Start the IR receiver { Serial.begin(9600); irrecv.enableIRIn(); leftServo.attach(9); rightServo.attach(10); pinMode(rightMotorPin, OUTPUT); pinMode(leftMotorPin, OUTPUT); } As you might deduce, you have to \"attach\" your servos so that you can address them from your Arduino. You then specify that the rightMotorPin and leftMotorPin will be used for OUTPUT because those are the pins you are using to send PWM control signals to your servos. Now, you can assign your button codes to the movement of your motors. Add the following to the main loop: void loop() { if(irrecv.decode(&results)) { showReceivedData(); keyCode=results.value; if(keyCode != -1) { switch (keyCode){ case 50174055: // Replace this code with the one from your remote! Serial.println(\"Forward\"); leftSpeed-=1; // Opposite values propel the wheels forward rightSpeed+=1; break; case 50182215: // Replace this code with the one from your remote! Serial.println(\"Backward\"); leftSpeed-=1; // Opposite values propel the wheels backward rightSpeed+=1; break; case 50168955: // Replace this code with the one from your remote! Serial.println(\"Stop\"); leftSpeed=90; // A value of 90 stops the servos from turning rightSpeed=90; break; case 50152125: // Replace this code with the one from your remote! Serial.println(\"Turn Left\"); // Wheels move in opposite directions leftSpeed-=1; rightSpeed-=1; break; case 50135805: // Replace this code with the one from your remote! Serial.println(\"Turn Right\"); // Wheels move in opposite directions

leftSpeed+=1; rightSpeed+=1; break; case 50139885: // Replace this code with the one from your remote! Serial.println(\"TURBO!!\"); // need to move left servo to go right leftSpeed=leftSpeed-50; rightSpeed=rightSpeed+50; break; } } } delay(250); } In this code, the first thing that happens is the decoded results.value is assigned to the integer keyCode. If the value is not -1, that means there is something to act on — a button has been pressed. This is tested by the next if statement. If a button has been pressed, you check to see whether it is one of the buttons you chose to control movement, using a switch...case statement. The switch...case conditional structure is used to test a variable among a number of possible situations. The variable keyCode is the test variable and its value is passed to the switch function, which determines which case is applicable. These cases are defined within the curly brackets. You can have as many cases as you want (limited by memory). Only the one that matches your criterion will be performed. The first case is moving the car forward: switch (keyCode){ case 50174055: // Replace this code with the one from your remote! Serial.println(\"Forward\"); leftSpeed-=1; rightSpeed+=1; break; My Toshiba remote control sends an infrared signal for the value \"50174055\" whenever the up arrow is pressed. That's the case I want to test against. The switch statement looks at the value of keyCode, and in the case that it matches the number 50174055, executes everything after the colon until the statement break. At this point, no more test cases are evaluated, and the Arduino skips to the last curly bracket that ends the switch() statement. Anything else within the statement will be ignored. If the forward button is pressed, you need to turn the servos in the appropriate direction for the way they are mounted on the chassis. However, when you mount the servos to the chassis, they will be facing away from each other, and thus, pointed in opposite directions. So, the left servo has to turn counterclockwise to propel the car forward and the right servo has to turn clockwise to propel the car forward. That is, the speed for both servos has to change at the same rate, but in opposite directions. To go forward, leftSpeed is decreased by 1 and rightSpeed is increased by 1, and to go backward, just the opposite. You do this in the case statement: case 50182215: // Replace this code with the one from your remote! Serial.println(\"Backward\");

leftSpeed+=1; // Opposite values propel the wheels backward rightSpeed-=1; break; The third case in the switch...case structure is when the car stops. Both the speed values are set to 90, which the servo interprets as stationary. The next two statements handle turning — this baby can turn on a dime! That's because the wheels move in opposite directions. To go left, the left servo speed is decreased, turning it counterclockwise. The right servo has to turn clockwise. If both servos were facing the same way, this would mean that its rightSpeed variable has to be increased. However, because the right servo is mounted in the opposite orientation to the left servo, its speed variable also has to be decreased. It's a bit counterintuitive, but it works. And when you want to turn right, you just do the opposite, increasing the speed variable for both wheels. The last case statement is for Turbo! mode. It adds forward (or negative) speed in an increment of 50, rather than 1. Make sure to change the key codes to match the ones you decoded for your remote. Now that you have the speed variables under control, you need to send the values to the servos. You do this with a function that updates the motors. Add an instruction to call this function at the end of your main program loop: Void loop(){ ... updateMotors(); delay(10); } You also can change the delay timer to 10 milliseconds. You don't need the longer 250ms delay any more. You can also delete the showReceivedData function if you want, because you won't be needing it any more. Now define the updateMotors() function at the very bottom of your code: void updateMotors(){ leftServo.write(leftSpeed); rightServo.write(rightSpeed); } Testing the drive motors After you’ve checked your code, upload it to the breadboard test bed and check out the action. You should be able to point your remote in the general direction of your breadboard and get the motors turning. You may even be able to detect infrared light bounced off of the ceiling or adjacent walls.

Try it. When your code is running, you may notice that your motors are turning slightly, even when they are supposed to be stationary. This is probably due to a slight calibration problem. There is a tiny hole on the top of your servo motor, underneath which is a tiny potentiometer you use to fine-tune the servo. To calibrate your motors, insert a small screwdriver into this hole until you feel it click into the potentiometer’s head. Adjust left and right and the motor will turn. Do this until you get a feel for the range of movement. Then, center the potentiometer so that the servo shaft does not move. You may hear a slight clicking sound, after you’ve got it centered, but this is normal. I think of it as the sound of the engines idling! Test that all your remote control commands are accurately detected and that your servos are turning correctly. Servos are power hungry. If you test the motors in “Turbo!” mode, there’s a chance you might draw too much current from your USB port all at once, in which case your Arduino will be disconnected from your USB port. You’ll have to reboot it to start the sketch running again. If this happens, you won’t be able to test drive in Turbo mode until you connect your battery pack. The final test is solo operation. You need to connect your AA battery pack — the power plant — to your system. Fire up your soldering iron and grab the remaining two pin headers. Clamp these into your helping hands and tin the pins by applying a bit of solder to them. Then tin the leads of your battery connector and solder them to the pin headers, as shown in Figure 14-5. You should do this quickly and precisely. If you heat the pins too long, the plastic that holds them will melt and you’ll need to start all over. Figure 14-5: Soldering pin headers to your power leads.

Take time to let the pins cool down between tinning them and attaching the power leads. After you’ve soldered them together you are ready to test. Disconnect your Arduino from your computer. Next, plug in your battery pack to the Vin and GND connections on your Arduino’s power headers. It’s very important to make sure you get the polarity right! Do not insert the power leads into the wrong headers and do not insert them backward. If you do, you could damage your Arduino permanently. When the power is connected, you should be able to do the computer-free operational test, as shown in Figure 14-6. After you’ve finished building the brains and the power plant, you can move on to assembling the car’s frame, or chassis. Figure 14-6: Testing your system before assembly. Building Your Chassis Now lay your Arduino, breadboard, and battery pack on the scrap wood to judge their size. Then mark the outside dimensions and cut the wood to size. Because your car is using three-point suspension, with a ball caster serving as the front wheel, you want to make sure you have balanced all your components and the weight is distributed evenly. So, mark the centerline of the wooden platform, as shown in Figure 14-7. Next, close to the one end, mark the centerline for the servo motor axles. There should be enough room to mount the servos to

your chassis. If you are using screws or bolts, make sure that they are positioned on the platform so that the axles of the servos will be on the same axis. You also need to be sure that they are parallel to one another. If your wheels are not parallel, your motors will be working against one another and your car will be hard to control. If you want to bolt your Arduino to the chassis (instead of using tape or hot glue), take a moment to mark bore holes on the top end of your chassis, at the back. Use your Arduino as a template and use the holes in the corners of your Arduino’s PCB. Figure 14-7: Marking your centerline. Now assemble and mount the ball caster kit, as shown in Figure 14-8. Use the enclosed instructions as a guide and brush up on your Japanese! The ball caster has a clever way of setting the height. There are several shafts sticking out of the plastic base. Depending on which way you orient the plate that holds the ball bearing in place, you can get a final height of either 25mm or 35mm. Because the Pringles can wheels are pretty high, use the 35mm setting. The kit comes with a bunch of extra mounting screws. You can either use these to mount the bearing to your chassis, or you can use hot glue, which is not as reliable, but is easier. Mount your ball caster on the centerline, as shown in Figure 14-9. Figure 14-8: Assembling and setting the ball caster.

Figure 14-9: Mounting the ball caster. Next, prepare the wheels. If you haven’t already done so, eat the second can of Pringles. Save the plastic lid! Then mark a line about 1cm (1⁄2 inch) up from the bottom of the can. This is easy to do if you set your Sharpie on a book about that thickness and hold it so that it is touching the side of the can. Then simply rotate the can to make a consistent mark around its circumference. Using this line as a guide, carefully cut off the bottom of both cans using a sharp hobby knife, as shown in Figure 14- 10. With the wheels removed, use a hobby knife to bore a small hole in the plastic lid at the tiny dimple in the exact center. It should be big enough to fit your pen through. Then, use the lid as a template to mark a guide mark on the metal discs from the bottom of the can, as shown in Figure 14-11. Now grab your hammer and nail. Also, locate the mounting screw that secures the header plates onto your servo. This should be in the accessory pack that came with your servos. The shaft plate mounting screw is usually the single black one and not the shiny silver ones that are used for mounting your servo motor. The nail should be the same thickness as the plate mounting screw but no thicker than its head. Otherwise the wheel won’t stay on!

Figure 14-10: Slicing off your wheels. Use your hammer and the nail to punch a hole in the center of the metal disc, as shown in Figure 14-11. Do this on a surface that you don’t mind nailing into a bit. When you’ve punched a hole, carefully fold the metal burrs outward a bit. Then use your hammer to tap them so that they are flush with the metal surface. Watch out for those burrs — they are sharp. This thing has drawn blood — I can tell you! Figure 14-11: Marking the center of your wheels. Now that you have a hole for the axle shaft, fit the rubber bands around the circumference of your wheels and attach one of the servo header plates in your accessory kit to each of the shafts of your servos. They should fit snugly but are removable if you ever need to do any tire service. Thread the shaft mounting screw through your wheel and screw it securely onto the drive shaft of the servo, as shown in Figure 14-12.


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook