Quantcast
Channel: SparkFun Tutorials
Viewing all 1123 articles
Browse latest View live

MCP4725 Digital to Analog Converter Hookup Guide

$
0
0

MCP4725 Digital to Analog Converter Hookup Guide a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t29

To DAC, or Not to DAC...

When learning about the world of microcontrollers, you will come across analog-to-digital converters quite frequently. These allows us to read in signals from analog sensors and convert them into a digital language our microcontrollers and other computational devices can understand. However, what if you need to do the opposite? What if you need your Arduino to speak the language of analog signals? Enter the MCP4725 Digital-toAnalog Converter Breakout.

alt text

This tiny IC allows you to do just that. By using the Arduino’s I2C lines, you can create a wide variety of analog waveforms on the other end.

Covered in This Tutorial

In this tutorial, we will overview the breakout and discuss additional hardware details. Then an assembly section will discuss how to connect this breakout to a microcontroller. Last, the firmware will be broken down to help you understand how the digital to analog conversion happens.

Suggested Reading

Board Overview

Before we discuss hooking up the breakout, let’s go over some of the features of this board.

Pinout

The first thing to point out is the pinout on this breakout now conforms to the standard I2C pinout we’ve started using on most devices that use the two-wire interface. Thus, it is easy to solder some headers on the breakout and plug it directly into an Arduino with the same pinout for the I2C pins. There is also the signal out and a GND pin grouped together to connect to an oscilloscope or whatever other device you’re hooking up to the breakout.

alt text

Power

The breakout can be powered anywhere between 2.7V to 5.5V, making it great for both 5V and 3.3V microcontrollers.

I2C Communication

A few features have been added to this breakout to give the user more flexibility with the IC, particularly when it comes to adding multiple DACs to one bus. First, we’ve broken out the address selection pin (A0) to a jumper pad. By default, this pin is pulled LOW to GND. To change the address of your other device, simply de-solder the jumper and add a blob of solder to the middle pad and the Vcc pad.

address selection

If you’re going to have more than one MCP4725 on a bus, you’ll also want to disable the pull-up resistors on all but one breakout. To make this easier, we’ve added another jumper on the back of the board. The pull-ups are enabled by default. If you need to disable them, you’ll need to cut the traces on the jumper pad with an Xacto knife. If you ever need to re-enable the pull-ups, simply solder the three pads back together.

pullup enable

Last, there are two mounting holes to mount this board inside the enclosure of your choice.

Hooking it Up

To use the MCP4725, all you’ll need is some male headers, a SparkFun RedBoard or other microcontroller, and a means to see your signal. Using an oscilloscope will be the easiest way to get started.

First, solder the headers onto your breakout. We recommend using a 4-pin header facing downward for the power and communication connections and using a 2-pin header facing up for the Out and GND pins. See the below image for an example.

alt text

Most Arduino boards have the I2C on the A4 and A5 pins. Then, in the firmware we’ll uplaod in the next section, we can set pins A2 and A3 as GND and Vcc respectively to power the breakout. If you prefer to wire everything to a breadboard, you can solder a 6-pin header and connect everything with some jumper wires.

alt text

Last, it’s time to connect the MCP4725 to whatever device you’ll be sending analog signals. In this tutorial, we’ll be visualizing the signal with an oscilloscope. Using the o-scope probes, you could connect to the headers directly, or you could use some jumper wires. Make sure to not mix up the Out and GND pins.

alt text

Firmware

With everything hooked up, it’s time to upload some code to the Arduino that will allow the breakout to send analog signals. In this example, the code will generate a simple sine wave.

Open up the Arduino IDE, and copy in this snippet of code:

language:c
/******************************************************************************
MCP4725 Example Waveform Sketch
Joel Bartlett
SparkFun Electronics
Sept. 11, 2014
https://github.com/sparkfun/MCP4725_Breakout

This sketch takes data from a lookup table to provide
waveforms to be generated by the MCP4725 DAC.

Development environment specifics:
Arduino 1.0+
Hardware Version V14

This code is beerware; if you see me (or any other SparkFun employee) at the local,
and you've found our code helpful, please buy us a round!

Distributed as-is; no warranty is given.

This code builds off the sketch written by Mark VandeWettering, which can be found here:
http://brainwagon.org/2011/02/24/arduino-mcp4725-breakout-board/
*/

#include <Wire.h>//Include the Wire library to talk I2C

//This is the I2C Address of the MCP4725, by default (A0 pulled to GND).
//Please note that this breakout is for the MCP4725A0.
#define MCP4725_ADDR 0x60
//For devices with A0 pulled HIGH, use 0x61

//Sinewave Tables were generated using this calculator:
//http://www.daycounter.com/Calculators/Sine-Generator-Calculator.phtml


int lookup = 0;//varaible for navigating through the tables

int sintab2[512] =
{
  2048, 2073, 2098, 2123, 2148, 2174, 2199, 2224,
  2249, 2274, 2299, 2324, 2349, 2373, 2398, 2423,
  2448, 2472, 2497, 2521, 2546, 2570, 2594, 2618,
  2643, 2667, 2690, 2714, 2738, 2762, 2785, 2808,
  2832, 2855, 2878, 2901, 2924, 2946, 2969, 2991,
  3013, 3036, 3057, 3079, 3101, 3122, 3144, 3165,
  3186, 3207, 3227, 3248, 3268, 3288, 3308, 3328,
  3347, 3367, 3386, 3405, 3423, 3442, 3460, 3478,
  3496, 3514, 3531, 3548, 3565, 3582, 3599, 3615,
  3631, 3647, 3663, 3678, 3693, 3708, 3722, 3737,
  3751, 3765, 3778, 3792, 3805, 3817, 3830, 3842,
  3854, 3866, 3877, 3888, 3899, 3910, 3920, 3930,
  3940, 3950, 3959, 3968, 3976, 3985, 3993, 4000,
  4008, 4015, 4022, 4028, 4035, 4041, 4046, 4052,
  4057, 4061, 4066, 4070, 4074, 4077, 4081, 4084,
  4086, 4088, 4090, 4092, 4094, 4095, 4095, 4095,
  4095, 4095, 4095, 4095, 4094, 4092, 4090, 4088,
  4086, 4084, 4081, 4077, 4074, 4070, 4066, 4061,
  4057, 4052, 4046, 4041, 4035, 4028, 4022, 4015,
  4008, 4000, 3993, 3985, 3976, 3968, 3959, 3950,
  3940, 3930, 3920, 3910, 3899, 3888, 3877, 3866,
  3854, 3842, 3830, 3817, 3805, 3792, 3778, 3765,
  3751, 3737, 3722, 3708, 3693, 3678, 3663, 3647,
  3631, 3615, 3599, 3582, 3565, 3548, 3531, 3514,
  3496, 3478, 3460, 3442, 3423, 3405, 3386, 3367,
  3347, 3328, 3308, 3288, 3268, 3248, 3227, 3207,
  3186, 3165, 3144, 3122, 3101, 3079, 3057, 3036,
  3013, 2991, 2969, 2946, 2924, 2901, 2878, 2855,
  2832, 2808, 2785, 2762, 2738, 2714, 2690, 2667,
  2643, 2618, 2594, 2570, 2546, 2521, 2497, 2472,
  2448, 2423, 2398, 2373, 2349, 2324, 2299, 2274,
  2249, 2224, 2199, 2174, 2148, 2123, 2098, 2073,
  2048, 2023, 1998, 1973, 1948, 1922, 1897, 1872,
  1847, 1822, 1797, 1772, 1747, 1723, 1698, 1673,
  1648, 1624, 1599, 1575, 1550, 1526, 1502, 1478,
  1453, 1429, 1406, 1382, 1358, 1334, 1311, 1288,
  1264, 1241, 1218, 1195, 1172, 1150, 1127, 1105,
  1083, 1060, 1039, 1017,  995,  974,  952,  931,
   910,  889,  869,  848,  828,  808,  788,  768,
   749,  729,  710,  691,  673,  654,  636,  618,
   600,  582,  565,  548,  531,  514,  497,  481,
   465,  449,  433,  418,  403,  388,  374,  359,
   345,  331,  318,  304,  291,  279,  266,  254,
   242,  230,  219,  208,  197,  186,  176,  166,
   156,  146,  137,  128,  120,  111,  103,   96,
    88,   81,   74,   68,   61,   55,   50,   44,
    39,   35,   30,   26,   22,   19,   15,   12,
    10,    8,    6,    4,    2,    1,    1,    0,
     0,    0,    1,    1,    2,    4,    6,    8,
    10,   12,   15,   19,   22,   26,   30,   35,
    39,   44,   50,   55,   61,   68,   74,   81,
    88,   96,  103,  111,  120,  128,  137,  146,
   156,  166,  176,  186,  197,  208,  219,  230,
   242,  254,  266,  279,  291,  304,  318,  331,
   345,  359,  374,  388,  403,  418,  433,  449,
   465,  481,  497,  514,  531,  548,  565,  582,
   600,  618,  636,  654,  673,  691,  710,  729,
   749,  768,  788,  808,  828,  848,  869,  889,
   910,  931,  952,  974,  995, 1017, 1039, 1060,
  1083, 1105, 1127, 1150, 1172, 1195, 1218, 1241,
  1264, 1288, 1311, 1334, 1358, 1382, 1406, 1429,
  1453, 1478, 1502, 1526, 1550, 1575, 1599, 1624,
  1648, 1673, 1698, 1723, 1747, 1772, 1797, 1822,
  1847, 1872, 1897, 1922, 1948, 1973, 1998, 2023
};


void setup()
{
  Wire.begin();

  // Set A2 and A3 as Outputs to make them our GND and Vcc,
  //which will power the MCP4725
  pinMode(A2, OUTPUT);
  pinMode(A3, OUTPUT);

  digitalWrite(A2, LOW);//Set A2 as GND
  digitalWrite(A3, HIGH);//Set A3 as Vcc
}
//---------------------------------------------------
void loop()
{
  Wire.beginTransmission(MCP4725_ADDR);
  Wire.write(64);                     // cmd to update the DAC
  Wire.write(sintab2[lookup] >> 4);        // the 8 most significant bits...
  Wire.write((sintab2[lookup] & 15) << 4); // the 4 least significant bits...
  Wire.endTransmission();
  lookup = (lookup + 1) & 511;
}

Once the sketch is uploaded, fire up the o-scope, connect the probe, if you haven’t yet, and you should be greeted with a nice looking sine wave.

alt text

Resources and Going Further

With that, you should be able to get your MCP4725 working the way you’d like and integrated into your next project. For more information on the MCP4725, please visit the links below.

Need more? Check out these other SparkFun tutorials:


learn.sparkfun.com |CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado


Re-Programming the LilyTiny / LilyTwinkle

$
0
0

Re-Programming the LilyTiny / LilyTwinkle a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t272

Introduction

The LilyTiny (and LilyTwinkle) are both great, low-cost, sew-able microcontrollers for eTextile projects. For most projects that only need to interface to a small number of LEDs or sensors, the LilyTiny is a great option.

alt text

The LilyTiny has 6 petals. Two are reserved for power(+) and ground(-). The other four are general purpose I/O pins (GPIOs). The LilyTiny is pre-loaded with a sample sketch which shows a variety of LED patterns on each of the pins:

  • “breathing” pattern (pin 0)
  • heartbeat pattern (pin 1)
  • simple on-off blink (pin 2)
  • random fade (pin 3)

This is a great place to start, but the only way to re-program one of these boards is to use an AVR Programmer and an ISP Pogo Pin Adapter to connect to the 6 exposed pins on the bottom of the LilyTiny board.

This is okay if you haven’t already sewn your board into your project. If you have, we can still re-program your board. This tutorial will show you exactly how to accomplish this.

Things you will need

There are a couple of ways to re-program your board. We will focus on one of the easiest methods here – using the Tiny AVR Programming stick.

alt text

Tiny AVR Programming Stick with Pomona 5250 SOIC Clip used to re-rogram the ATtiny85 on the LilyTwinkle.

ATTiny Board Files

Before we start, we need to setup the Arduino programming environment to handle the ATTiny hardware. The ATTiny is not part of the “default” board files that comes with Arduino 1.x. You will need to “install” these board files to your Arduino environment in order to re-program your LilyTiny.

The High-Low Tech Lab at MIT has a really nice tutorial on this process here.

Install the ATTiny hardware files

We will first need to install the ATTiny hardware board files.

Create a folder under your Arduino sketchbook called “hardware.”

  • Locate your Arduino sketchbook folder (you can find its location in the preferences dialog in the Arduino software) - this is typically under Documents > Arduino

  • Create a new sub-folder called “hardware” in the sketchbook folder, if it doesn’t exist already.

  • Open (unzip) the ATTiny-master.zip file and copy the “attiny” folder (not the attiny-master folder) from the unzipped ATtiny master.zip file to your new “hardware” folder.

You should end up with folder structure like Documents > Arduino > hardware > attiny that contains the file boards.txt and another folder called variants.

  • Restart the Arduino development environment.

  • You should see ATtiny entries in the Tools > Board menu.

Tiny AVR Programmer

Follow the hook-up guide for the Tiny AVR programmer. For Windows / PC users, there are a few driver files that you’ll need. For Mac / OS X users, the Tiny AVR Programmer should be plug-and-play ready.

Tiny AVR Programmer Hookup Guide

October 28, 2013

A how-to on the Tiny AVR Programmer. How to install drivers, hook it up, and program your favorite Tiny AVRs using AVRDUDE!

Use the 4-wire ribbon cables and the straight pin break-away headers to connect the SOIC clip to the Tiny AVR Programmer. Make sure that the left side pins are wired to the left side of the SOIC clip and the right side pins are wired to the right side of the SOIC clip.

I also recommend using a USB extension cable with the Tiny AVR Programmer so you have a little more movement from your computer when re-programming.

alt text

Tiny AVR Programmer with 4-wire ribbon cables and straight pin break-away headers.

Test Code - "Hello World!"

As with nearly every introductory Arduino project, we test our system with a “blink” program – the equivalent to “Hello World!” in most other programming environments. First, we need to make sure the configuration is set properly in the Arduino IDE.

Step 0 - Open up the Arduino IDE

Step 1 - Setting the Board Type

The LilyTiny has an ATtiny85 microcontroller on it. Change the board type in the Arduino IDE to correspond with this. The ATtiny85 can be set with either a 1 MHz internal clock or an 8 MHz internal clock. Be sure to select 8 MHz. Select: Tools –> Board –> ATtiny85 (internal 8 MHz clock)

alt text

Step 2 - Setting the Programmer

Because we are using the Tiny AVR as our programmer, we need the change the default programmer. This settings is also under the Tools menu.

alt text

Step 3 - Upload Code

Copy the code below and paste this into your Arduino window.

int blinkPin = 0;
void setup()
{
   pinMode(blinkPin, OUTPUT);
}

void loop()
{
    digitalWrite(blinkPin, HIGH);
    delay(500);
    digitalWrite(blinkPin, LOW);
    delay(500);
}

Click the upload button. You may see a few warning messages such as:

avrdude: please define PAGEL and BS2 signals in the configuration file for part ATtiny85

You can ignore this one. If everything is working, you should be seeing a blink on GPIO 0 (pin 5 of the ATtiny).

Notes on Programming the ATtiny85

alt text

The ATtiny85 isn’t your everyday Arduino microcontroller. It packs a lot of punch for its small size. The following Arduino commands should be supported:

All 5 pins are general purpose digital I/Os (GPIO). This means that they can be used with both digitalWrite() and digitalRead().

Pins 0 and 1 support PWM output (analogWrite).

Pins 2, 3, & 4 are tied to A/D on the chip (analogRead).

While the ATtiny85 supports most of the things you need, there are some things it can’t do.

No Hardware Serial (UART)

The ATtiny85 does not have a built in hardware UART. If you try to compile any Arduino code with Serial.begin() or Serial.print() you’ll get an error. However, there is a work around for this – using Software Serial. This tutorial shows an example of how to do this.

Resources and Going Further

For more information regarding the ATtiny85, LinyTiny/Twinkle or AVR programming, check out the following links:

alt text

Going Further

  • H2OhNo!– The H2OhNo! water alarm and development board uses an ATtiny85 to sense the presence of water. This tutorial goes deep into getting the ATtiny85 into a very low power mode.
  • Shift Registers– If you’re feeling restrained by the ATtiny’s lack of pins, you may be able to use a shift register to expand on that I/O count.
  • Using the Arduino Pro Mini 3.3V– If you’re looking for small, but need more pins and functionality check out the Arduino Pro Mini.

learn.sparkfun.com |CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

Hacking Your Maker Faire Badge

$
0
0

Hacking Your Maker Faire Badge a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t298

Introduction

The SparkFun Faire Game Badge is not only fun at Maker Faire, but also gives you the power of a full microcontroller you can use at home! This tutorial will walk you through the process of hooking up your board to other electronics, as well as how to upload new code.

Maker Faire Badges

Suggested Reading

If you aren’t familiar with the following concepts, you may want to read up on these additional tutorials before moving forward with hacking your badge.

Board Overview

The Badge has several features you should be aware of when hacking on it.

Bare Badge

Bare badge, showing all features discussed below.

Microcontroller

The IC on this board is the ATMega328. This is the same chip that runs the Arduino Uno, and several of our LilyPad boards. However, this board relies on the internal oscillator of the 328, instead of having an external crystal like the Uno or LilyPad main board.

Power System

The board has a battery holder for a 3V, 20mm coin cell battery. We recommend using the CR2032, as this has a higher capacity of 250mAh at 3V. The ON/OFF switch at the bottom of the board enables the user to turn off the battery supply when the badge is not in use.

The board can also be powered off of the 3.3V and GND pins on the FTDI header on the left side of the board. This is not connected in any way to the ON/OFF switch, so the board will run as long as this is connected.

Communication

There are several methods of communicating with your badge. The first is the FTDI header on the left hand side of the board. The board mates with a 3.3V FTDI Breakout Board, which enables you to communicate via serial over a USB interface to the board.

You can also communicate or program the board via the ICSP header on the right side of the board. This will communicate with the board using SPI protocol.

Participation Indicator

This is an RGB LED, located in the top center of the board (right where the lovely silk label points!). The board comes pre-programmed with this LED functioning as a participation indicator for our #makergame, but you can use this for any purpose you so desire. The blue channel of the LED is connected to pin D9 on the ATMega328, the red channel connects to pin D10, and the green channel connects to pin D11/MOSI. Keep this in mind if you decide to use the ICSP header for hacking your badge later - use of the MOSI line will restrict your ability to use the green channel on the LED.

The three pins to which the LED connects are capable of pulse-width-modulation (PWM) control, so this is a nice feature to be aware of when you are thinking how you would like to hack your board.

Buzzer

The buzzer is located on the left side of the board. This comes pre-programmed to act as an indicator for our #makergame, just like the LED. Again, though, just like the LED, you can reprogram your board to use this for whatever application you’d like. The buzzer is tied to D2 on the ATMega328.

Additional I/O Pins

There are 14 additional pins broken out for you, the user, to configure on your badge. Digital pins 3-8 are broken out on the bottom right side of the board. Pins 3, 5, and 8 are capable of PWM control, which makes these useful pins for things like driving servos or other small motors.

Analog pins 0-7 are broken out on the bottom left side of the board. These pins can be used for analog-to-digital conversion, and are very helpful for interfacing with sensors that have analog signal outputs.

Assembling the Board

Now that you are familiar with the hardware available on the badge, it’s time to assemble it.

We will be using male headers for this tutorial, but keep in mind that you could use female headers if you so choose.

To begin, break apart six sets of 2-pin headers from the strip of male headers. Place these in the holes labeled “Initials Boards” on the top of the pcb. Then, without soldering anything, place the three initials boards onto the headers.

Placing letter boards

You want to place the initials boards before soldering to ensure everything lines up correctly and will fit together on the front of the badge. The headers will wiggle a bit doing this, so it may help to have your pcb clamped using a third hand.

Now that you have the three initials boards lined up and placed on your badge, it’s time to begin soldering. Start soldering the initials boards to the headers. Take your time and reposition the boards as needed as you go, so everything continues to line up.

Soldering Initials Boards

Once all of the initials boards have been soldered to the headers, it’s time to flip your badge over. It may be easier to only solder the back of one initials board to the badge at a time. However, since you already ensured everything will line up, this shouldn’t be a problem!

Back of Badge

The back of your badge should look like this once the intials boards are soldered.

These letter boards just act as jumpers between the headers, so keep in mind you could use hookup wire in place of the initials boards.

It’s now time to add in additional headers. You will want to solder headers to the FTDI connection at the very least, as well as to any of the digital or analog pins broken out. If you plan on changing the bootloader on the board, you will also want to solder headers to the ICSP.

Back of the badge, fully soldered

In order to allow the badge to lay relatively flat when being worn, you will want to make sure you are always soldering on the back of the badge. It should look like the picture above once you are done.

Once you have that complete, flip your badge back over and be proud of your work! Your badge is ready to act as a full Arduino and be hacked!

Completed Badge

Uploading Code

With your board soldered and ready to go, you can now program your badge just like you would any other Arduino!

As mentioned previously, this board does not have an external crystal on it. For production runs of this board,the bootloader from the OpenSegment was used. Keep this in mind if you decide to overwrite the bootloader via the ICSP or ever need to reinstall the bootloader. Setting the fuse bits incorrectly for an external oscillator will lead to a bricked badge, so be very careful to double check before writing over the bootloader!

When uploading code to your board from the Arduino IDE, you will want to select the“Pro or Pro Mini (3.3V, 8MHz) w/ ATmega328” board option. Keep in mind as you write new code for your board that you do have some pins that are not available as they are on a standard Arduino, as described previously in the #Board Overview.

Resources and Going Further

Going Further

Now that you’ve figured out how to hack your badge for other projects, it’s time to start thinking about what else you can do!

Some things you may want to consider are swapping out the battery connector on the board, or modifying the power supply. This will allow you to hook up different items to your circuit and run the board for longer periods of time, or run more high powered applications.

Additional Resources

If you have any feedback, please visit the comments or contact our technical support team at TechSupport@sparkfun.com.

Check out these additional resources for more information and other project ideas.


learn.sparkfun.com |CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

LTC4150 Coulomb Counter Hookup Guide

$
0
0

LTC4150 Coulomb Counter Hookup Guide a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t225

Count your Coulombs

alt text

If you’ve worked with circuits a bit, you probably know that you can measure the current a circuit is using by using an ammeter (or more likely a multimeter on the amps setting), and that this is useful information to know.

Instantaneous current consumption is definitely useful, but sometimes you’d like to keep track of cumulative current use, especially when you’re trying to determine how much power is left in a battery. Battery life is easy to predict for a circuit that uses a constant amount of current, but things get a lot harder when the circuit is doing different things at different times, like lighting up LEDs.

"Jeep Odometer" by Sav127 at en.wikipedia - Licensed under Creative Commons Attribution-Share Alike 3.0 via Wikimedia Commons

Consider the speedometer and odometer in a car. The speedometer is like an ammeter - it shows you your instantaneous speed, which is good to know, but it can’t tell you how far you’ve gone unless you’re constantly keeping track of it. This is the odometer’s job; it constantly monitors your speed, accumulates it over time, and tells you how far you’ve traveled.

A coulomb counter is like an odometer for current. It constantly monitors the current your circuit is using, adds it up, and gives you a pulse each time a given amount of amp-hours have been used. With each pulse, you’ll also get a “polarity” signal, which tells you which direction the current is flowing (great for rechargeable batteries!). By counting the pulses and direction, you can maintain an accurate count of how much power your circuit is removing from (or putting back into) your battery. If you start with a full battery, you’ll always know exactly how much of it is left! Neat, huh?

Suggested Reading:

Battery Basics

Before we talk about coulombs, let’s talk for a minute about batteries.

When you buy a battery from SparkFun (or anywhere else), you’ll decide which one you want based on two important numbers:

One of these is how many volts the battery provides. You’ll of course want to pick a battery that matches your project’s requirements (too much or too little voltage isn’t good). Usually we’ll recommend a specific battery, such as two 1.5V AA cells for our Simon game.

The other number is the capacity of the battery, or how “big” it is. The higher the capacity, the longer your project will run. Higher capacity batteries are larger and heavier than smaller ones, so you’ll need to trade off size and weight vs. runtime – you might want to use AA batteries for a more portable project, even though they won’t last as long as D batteries would.

We measure battery capacity in milliamp-hours (mAh) for small batteries, or amp-hours (Ah) for large ones. This number indicates the theoretical amount of current a battery can provide for one hour before running out of juice.

For example, all of these alkaline batteries have the same voltage (1.5V), but different capacities:

alt text

  • D: 12000mAh
  • C: 8000mAh
  • AA: 2700mAh
  • AAA: 1200mAh

The AAA battery above has a capacity of 1200mAh, which means it could provide 1.5V at 1200mA (1.2A) for one hour. But that’s just the current it could provide for one hour. It could just as easily provide:

  • 600mA for two hours (600mA = 1200mAh/2h)
  • 300mA for four hours (300mA = 1200mAh/4h)
  • 150mA for 8 hours (150mA = 1200mAh/8h), etc.

Conversely, depending on the kind of battery you’re using, it might be possible to get:

  • 2400mA for half an hour (2400mA = 1200mAh/0.5h)
  • 4800mA for 15 minutes (4800mA = 1200mAh/0.25h)
  • 72000mA (72A!!!) for 1 minute! (72000mA = 1200mAh/(1/60h))

In reality, the chemicals in a battery can only react at a certain rate, so you can’t get unlimited amounts of power even for a short amount of time. However, high-discharge LiPo batteries without protection circuitry CAN discharge breathtaking amounts of power for a few minutes, and are used in model aircraft for exactly this reason.

If you want to know how long a battery will last, the math is easy:

  • To determine the current a full battery can provide for a given number of hours, divide the total capacity by hours:

    1200mAh / 10 hours = 120mA

  • To determine how long a full battery will last at a given current draw, divide the total capacity by your project’s current draw:

    1200mAh / 50mA = 24 hours

What is a Coulomb?

"Charles de coulomb". Licensed under Public domain via Wikimedia Commons - http://commons.wikimedia.org/wiki/File:Charles_de_coulomb.jpg

Charles-Augustin de Coulomb, 1736-1806

A coulomb (like most units named after people, the name is written out in lowercase unless you’re specifically referring to that person), is defined as one amp for one second:

1A x 1s = 1C

Because there are 3600 seconds in an hour, one amp hour equals 3600 coulombs:

1Ah = 3600C

How does the LTC4150 Measure Coulombs?

The LTC4150 has an output pin called interrupt, or INT for short (the line above the name indicates that this is an “active low” signal). This line is normally high, but will pulse low each time 0.614 coulombs passes through the device (which also happens to equal 0.1707 milliamp-hours or 0.0001707 amp-hours):

1 INT = 0.614439C

1 INT = 0.1707mAh

1 INT = 0.0001707Ah

Or to look at it another way, you will get 5859 INT“ticks” for each amp-hour:

5859 INTs = 1Ah

Keeping Track of the Charge in a Battery

As you know, battery capacity is measured in mAh (milliamp-hours) or Ah (amp-hours). If your battery holds 1 amp-hour when it’s full, you can continuously draw one amp from it for one hour before it’s empty. You could also pull ½ amp for two hours, or 2 amps for ½ hour, etc.

Because it measures amp-hours as you’re using them, the coulomb counter makes it very easy to keep track of your battery’s state-of-charge (how full it is):

  1. First, assuming you’re starting with a full battery, set a variable to your battery’s initial state-of-charge (e.g. 1000.0 mAh).

  2. Listen for the “tick” (low) signals from the INT pin.

  3. Each time you detect a tick, check the direction signal, and add or subtract the above per-tick mAh value (0.1707 mAh) to your battery-state variable.

  4. Profit!

As we saw in the last section, one “tick” from the device is equal to 0.0001707 amp-hours. Conversely, it takes 5859 ticks to equal one amp-hour. If your battery has a capacity of two amp hours, then it would take 11718 ticks (5859 * 2) to completely drain (or fill*) the battery.

* Note that in real life it takes a bit more current to charge a battery than you’ll later get out of it. This is because the chemical processes that store charge aren’t 100% efficient, with the excess turning into heat. The amount of loss varies depending on the type of battery, charge rate, age of the battery, temperature, etc. You can account for this by providing a manual “reset” input when the battery is fully charged, or doing some calibration to see how many more ticks you get when charging vs. discharging (though this will change with battery age, temperature, etc.).

We’ve written example code that shows you how to do all this, see the Example Code section for more information.

Bonus: Determining Average Current

An additional (and entirely optional) trick is that if you keep track of the time delay between “ticks”, you can back out the average current used over that period. The equation is very simple:

mA = 614.4 / (delay between “ticks” in seconds)

Note that because this number is the average current use over the time period, the instantaneous current could be higher or lower. This is also covered in the example code.

Connecting the Hardware

The LTC4150 Coulomb Counter IC has a very simple interface. It has an INT (interrupt) output that is normally high, but will go low when a given amount of current has passed through the device. There is also a POL output that tells you which direction current is flowing.

Max Ratings

The Coulomb Counter can accommodate power sources up to 8.5V, and currents up to 1A. It works particularly well for single-cell (3.7V) Lipo batteries.

On the interface side, the Coulomb Counter can be attached to systems running at either 3.3V or 5V (see solder jumpers below). The resistors on the board have been selected for those two voltages; other I/O voltages may need different resistor values.

Solder jumpers

There are three solder jumpers on the Coulomb Counter board that configure it for different situations. Please read this section carefully and make any necessary changes before using your Coulomb Counter.

alt text

  • Solder jumper SJ1 (on the component side of the board) controls the behavior of the INT output. If SJ1 is closed (the default), INT will pulse low and immediately return high. If SJ1 is open (clear), INT will stay low until you use the CLR input to manually reset it. If your code uses interrupts to detect INT ticks, you will probably want to leave SJ1 closed. This will save you the step of having to manually reset INT on each tick. If you are manually polling the INT output, you will probably want to open (clear) SJ1 to give you more time to detect the low signal. See the Example Code section for more information on interrupts vs. polling.

alt text

  • Solder jumpers SJ2 and SJ3 (on the bottom of the board) select whether you’ll be connecting the Coulomb Counter to a 3.3V or a 5V system. If you’re using a 5V system (the default), leave these two solder jumpers open (clear). If you will be connecting the Coulomb Counter to a 3.3V system, close both of these jumpers.

To close a solder jumper, melt a small blob of solder onto the jumper so that it bridges both pads, shorting them together.

To open or “clear” a solder jumper, use some solder wick and a hot iron to remove the solder blob bridging the two pads. Place the wick over the blob, and heat the blob through the wick. When the solder melts, the wick will absorb it. When you’re done, ensure that the two pads are fully separated (no solder bridging them).

Electrical Connections

As you would when using an ammeter, you will need to install your Coulomb Counter between your power source (usually a battery) and your circuit. All the current your circuit uses needs to pass through the Coulomb Counter to be measured.

At one end of the breakout board are headers labeled IN and OUT. Connect your battery or power supply to the IN header or JST battery connector (they’re identical), and connect the OUT header to your project. The JST connector matches the connectors used on SparkFun Lipo batteries, and can be used to connect a single-cell 3.7V Lipo battery as your power source. (You could also add a 2-pin JST pigtail or adapter to your own battery or other power source and plug it into this connector).

Barrel Jack to 2-pin JST

Barrel Jack to 2-pin JST

In stock TOL-08734

Two pin JST connector to a 2.1x 5.5mm barrel jack, 6.25 inch long jumper cable. We use this cable to adapt from a wall power …

2.95
JST Jumper 2 Wire Assembly

JST Jumper 2 Wire Assembly

In stock PRT-09914

This is a simple two wire cable. Great for jumping from board to board or just about anything else. There is a 2-pin JST conn…

0.95
Jumper Wire - JST Black Red

Jumper Wire - JST Black Red

In stock PRT-08670

This is a simple two wire cable. Great for jumping from board to board. 2-pin JST connector on one end, bare cable on the opp…

0.95
Jumper Wire - JST Black Blue

Jumper Wire - JST Black Blue

In stock PRT-08671

This is a simple two wire cable. Great for jumping from board to board. 2-pin JST connector on one end, bare cable on the opp…

0.95

Note that if you’ll be using both the Coulomb Counter and a Lipo charger, connect the Coulomb Counter (not the charger) directly to your battery. This way the Coulomb Counter can monitor both charging and discharging:

alt text

PROTIP: if you connect a JST pigtail to the output of the Coulomb Counter, you can conveniently plug it straight into your system’s JST battery connector:

alt text

You can even do the same thing to a Lipo charger, for complete plug-and-play modularity:

alt text

LiPo Charger Basic - Micro-USB

LiPo Charger Basic - Micro-USB

Only 4 left! PRT-10217

If you need to charge LiPo batteries, this simple charger will do just that, and do it fast! The LiPo Charger Basic is stripp…

7.95
USB LiPoly Charger - Single Cell

USB LiPoly Charger - Single Cell

Out of stock PRT-12711

If you need to charge LiPo batteries, this simple charger will do just that, and do it fast! The USB LiPo Charger is a basic …

14.95
LiPo Charger Basic - Mini-USB

LiPo Charger Basic - Mini-USB

Out of stock PRT-10401

If you need to charge LiPo batteries, this simple charger will do just that. It is designed to charge single-cell Li-Ion or L…

7.95
Power Cell - LiPo Charger/Booster

Power Cell - LiPo Charger/Booster

In stock PRT-11231

The PowerCell board is a single cell LiPo boost converter (to 3.3V and 5V) and micro-USB charger in one. The board comes with…

19.95

Interface pins

At the other end of the Coulomb Counter, you’ll find a header with six pins. These are the pins you’ll need to connect to your microcontroller. Depending on what you want to do, you’ll need at least the first four pins:

NameFunctionDirectionNotes
VIOI/O VoltagePowerConnect to 3.3V or 5V depending on your system. Note that you may need to change jumper settings (see above).
INT
InterruptOutput
(from CC)
Goes low when 0.0001707 amp-hours have passed through the board. Is cleared (goes high) when CLR goes low. Connect to an interrupt input pin.
POLPolarityOutput
(from CC)
Indicates direction of current flow. Low = current from IN to OUT (discharging). High = current from OUT to IN (charging).
GNDGroundPowerConnect to GND pin on your system.
CLRClearInput
(to CC)
If INT is low, make CLR low to reset INT. This is done automatically if SJ1 is closed (ties CLR and INT together).This pin can be left disconnected if SJ1 is closed and you are using interrupts to sample INT.
SHDNShutdownInput
(to CC)
If SHDN is low, the chip will be held in reset. There is a pullup resistor from this pin to VIO, so if you leave it disconnected, the board will remain active. This pin can be left disconnected if you do not need the shutdown function.

PROTIP: When you see a signal name that contains an asterisk or has a line over it, that’s an indication that this signal uses “negative logic”. In negative logic, a low logic level means the signal is asserted or active. Thus, if you see a signal named RESET, you must provide a low signal to reset the part, and keep it high at other times.

Note that the Coulomb Counter is powered by the IN header (usually your battery) and not by the VIO pin, which is used only as a voltage reference for the output pins. This is so that the small amount of power used by the Coulomb Counter itself is included in its measurements for maximum accuracy. The Coulomb Counter uses under 1mA when it’s running, and you can use the SHDN (shutdown) input to reduce its power consumption further (though it will not be able to keep track of current use while shut down).

Typical Connections

Before plugging your Coulomb Counter into your microcontroller, see the Solder Jumpers section above for instructions on setting up the board for a 3.3V or a 5V system.

Our Arduino Example Code has been written so that you can plug the Coulumb Counter board directly into Arduino digital pins 2 through 7 as shown below. (We’ve made D2 permanently HIGH for VIO, and D5 LOW for GND.)

alt text

This makes it easy to test out the board, but in most cases you will want to use wires to connect the boards so as not to waste valuable I/O ports on pins that could be left disconnected. Speaking of which:

Do I need to use all six pins?

Probably not!

  • If you will be using interrupts to sample the INT signal (recommended), you can leave the CLR pin disconnected.

  • If you do not need shutdown functionality, you can leave the SHDN pin disconnected.

  • You can connect VIO and GND to your system’s regulated voltage (3.3V or 5V) and GND. You don’t need to waste I/O pins.

If you’re using interrupts to sample the INT signal (recommended), you can get away with only two I/O ports (INT and POL) plus VIO and GND. Note that for ATmega 328-based Arduinos, INT can only be connected to D2 or D3 without additional pin-change-interrupt libraries.

3.3V Systems

The Coulomb Counter is well-suited for 3.3V systems like the Arduino Pro or Pro Mini:

alt text

These diagrams show the use of a single-cell Lipo battery powering the system. Note that you should also connect 3.3V to VIO and GND to GND for the logic level reference. You can do this with the Arduino’s VCC (3.3V) line, or connect it to an I/O pin set HIGH as we do in our Example Code.

alt text

5V Systems

For 5V systems like the Arduino Uno or SparkFun Redboard, you can run an unregulated supply up to 8.5V through the Coulomb Counter to the Arduino’s VIN terminal. Note that you will need to connect 5V to VIO for the logic level reference. You can do this with the Arduino’s 5V line, or connect it to an I/O pin set HIGH as we do in our Example Code.

alt text

If you want to power the Arduino from a regulated 5V line, you can do that as well. Run the power supply through the Coulomb Counter to the Arduino’s 5V terminal. You will also need to get 5V to the Coulomb Counter’s VIO pin, and so on.

alt text

Running the Example Code

We’ve included two example programs for the Arduino microcontroller to show you how to use the Coulomb Counter. If you’re not using an Arduino, the example code is very straightforward and should be easily adapted to other microcontrollers.

To Interrupt or Not to Interrupt?

The two code examples are called “Coulomb_int” and “Coulomb_polling”. They do exactly the same thing (measure battery consumption), but differ in the way they detect changes on the INT output. Which one you choose will depend on your requirements and skill level.

Interrupts

The “standard” way to detect a pin change is to use interrupts. Interrupts are a hardware feature built into microcontrollers that allow them to handle high-priority events immediately.

To use interrupts, you write a special function called an Interrupt Service Routine (ISR) and set up the hardware appropriately. Then whenever a special interrupt pin on your microcontroller receives the desired input (goes high or goes low), whatever is going on in the main loop is paused, and your ISR function runs. When the ISR function finishes, the main loop picks up right where it left off. This all happens automatically - the only way the main loop would know that anything had happened would be if the ISR function changed some variables behind the scenes (such as how much battery is left, which is exactly what we do in the example code).

The interrupt example code has the advantage of not needing the CLR input, so you can get away with only two I/O pins; INT and POL.

Note that on ATmega 368-based Arduinos, only two pins support external interrupts without additional libraries: D2 (INT0) and D3 (INT1). We use D3 in our example code.

Polling

Interrupts are very useful, but if you’re still learning the finer points of programming, there’s no shame in using a simpler technique called polling. Polling is simply testing an input over and over again until it becomes the state you’re looking for.

By default, the Coulomb Counter is set up so that the INT output will go low and immediately return high. It will only be low for a few microseconds (millionths of a second!), which is enough for interrupt-based code to detect the falling edge, but random checking will almost certainly miss such a brief signal.

However, if you open (clear) solder jumper SJ1, each time INT goes low, it will stay low until you manually reset it. This makes it much easier to write polling code, as INT will stay low until the next time you get around to checking it. To reset it, make CLR low and then high.

The polling example code has the disadvantage of requiring three I/O pins as opposed to two (INT, CLR, and POL). You should also be careful to ensure that you check INT faster than every half-second or so; if a new INT comes in while the old one is still low, you will miss it.

Wiring the Hardware

Here are the minimum required connections for the example sketches. (See the previous page for wiring diagrams.)

If you want to try the interrupt example code:

  • Leave solder jumper SJ1 closed (the default)
  • You will need to connect (at least):
    • VIO to VCC
    • INT to D3
    • POL to D4
    • GND to GND

If you want to try the polling example code:

  • Open (clear) solder jumper SJ1 (Instructions)
  • You will need to connect (at least):
    • VIO to VCC
    • INT to D3
    • POL to D4
    • GND to GND
    • CLR to D6

For EITHER version of the code:

  • Ensure that SJ2 and SJ3 are both open (clear) for a 5V Arduino, or both closed (soldered) for a 3.3V Arduino.

Downloading the code

The example code is maintained at the Coulomb Counter BOB Github repository. You can download a ZIP file of the entire repository (or clone it to your computer if you have the github software installed), or save the sketches directly:

For either version of the code, you should change line 120 to reflect the full capacity of your lipo battery. The default is 2000mAh:

volatile double battery_mAh = 2000.0; // milliamp-hours (mAh)

This will provide an accurate readout of how many mAh remain in your battery as you use it.

Running the Example Code

Upload the code to your Arduino as you normally would. Open a serial monitor window set to 9600 baud. You should see a reset message, followed by updates as INT“ticks” occur.

alt text

The columns from left to right are:

  • mAh (milliamp-hours) remaining in the battery (subtracted from the battery size value at line 120)
  • State-of-charge (percentage remaining)
  • Time delay between ticks
  • Average mA computed from the last time delay.

Note that the first mA reading will be incorrect, as it requires the time delay between two readings to perform its calculations.

Remember that if you don’t have anything connected to the output of the Coulomb Counter, the current passing through the board will be zero and you will not see pulses from the INT pin. (You may get one pulse every 10 minutes or so from the very small amount of current that the LTC4150 chip uses.)

Resources and Going Further

Changing the Sense Resistor

The Coulomb Counter uses a sense resistor to measure current. This very small resistor (0.05 ohms) is the only component located between the input and the output. The LTC4150 measures the voltage drop across this resistor; thanks to Ohm’s law the voltage drop is directly proportional to the current passing through the resistor.

We’ve installed an 0.05 ohm sense resistor in the Coulomb Counter, which is why the maximum current is 1A and you get 5859 “ticks” per Ah. If you want more resolution (ticks per Ah) at a lower maximum current, or want more current* at less resolution, you can replace this resistor with a different value part. You will need to remove the existing part and replace it with another surface-mount part, or use the provided footprint for a through-hole resistor. Refer to the LTC4150 datasheet for information on resistor selection. There is also a spreadsheet in the Github documentation folder that may be useful.

* Note that the PCB traces on the board are not designed to handle more than 1.6A continuously, and the JST connectors are not designed for more than 2A.

Also note that there is no easy way to increase the maximum supply voltage of 8.5V. Sorry!

Using the SHDN Input

You can reset or shut down the LTC4150 by making the SHDN input LOW. This will reduce the power consumption of the board, but the LTC4150 will not measure current consumption in this mode. This input has a pullup resistor; if you do not need shutdown functionality, you can leave this input disconnected.

Going Further

We hope you find the LTC4150 Coulomb Counter useful. If you have any problems, feel free to contact our Tech Support Department. And let us know what you’re using it for!

Other tutorials you may enjoy:


learn.sparkfun.com |CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

Galileo Experiment Guide

$
0
0

Galileo Experiment Guide a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t275

Introduction

LED Galileo Circuit

Ready to learn the basics and see your Galileo in action? The Galileo board is software-compatible with the Arduino Software Development Environment, which makes getting started a snap. From building simple circuits to creating a Simon Says game, you will have a better understanding on how to build circuits and how to work with the Galileo. With these skills you can then create your own awesome project!

In this SparkFun Inventor’s Kit for Galileo guide, you will learn the following:

Experiment List:

Parts Needed

If you are following through all of the SIK Galileo tutorials we suggest getting these parts:

Required Reading

  • Galileo Getting Started Guide - If your Galileo is fresh out of the box and you are just getting started, then we highly recommend you start here first.

Suggested Reading

Before continuing on with this tutorial, we recommend you be somewhat familiar with the concepts in the following tutorial:

  • How to Use a Breadboard - First time working with a breadboard? Please check out this tutorial! It will help you understand why the breadboard is a great for prototyping and how to use one.

SIK Galileo - Part 1: Blinking an LED

Introduction

To help you get started with the Galileo, the SIK Galileo tutorials will take you through different basic circuits. In this tutorial, we will go over how to work with an LED.

LEDs are small, powerful lights that are used in many different applications. To start off, we will work on blinking an LED, the Hello World of microcontrollers. That’s right - it’s as simple as turning a light on and off. It might not seem like much, but establishing this important baseline will give you a solid foundation as we work toward more complex experiments.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x Galileo
  • 1x LED
  • 1x 330Ω Resistor
  • 2x Jumper Wires

If you are following through all of the SIK Galileo tutorials we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

Out of stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

Out of stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

1/6 Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 330Ohm resistors make excellent…

0.95
LED - Assorted (20 pack)

LED - Assorted (20 pack)

In stock COM-12062

We all know that you can never get too many LEDs. Don't worry, we've got you covered. This is a pack of basic red, yellow, bl…

2.95
Intel® Galileo

Intel® Galileo

In stock DEV-12720

The Intel® Galileo board is based on the Intel® Quark SoC X1000, a 32-bit Intel Pentium®-class system on a chip (SoC). It …

79.95

View the SparkFun Inventor’s Kit for Galileo wishlist, to see the parts needed to go through the all the experiments.

Suggested Reading

Before continuing on with this experiment, we recommend you be familiar with the concepts in the following tutorial:

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram and hookup table below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components are highlighted with a yellow warning triangle, in the table. Polarized components can only be connected to a circuit in one direction.

Please note: Pay close attention to the LED. The negative side of the LED is the short leg, marked with a flat edge.

LED drawing

Components like resistors need to have their legs bent into 90° angles in order to correctly fit the breadboard sockets. You can also cut the legs shorter to make them easier to work with on the breadboard.

Bent resistor

Fritzing Diagram

Graphic for LED hookup

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Hookup Table

ComponentGalileoBreadboardBreadboard
c2 ( + )c3 ( - )
330 Resistora3( - )
Jumper WireGND( - )
Jumper WirePIN 13e2

Code to Note

pinMode(13, OUTPUT);

Before you can use one of the Galileo’s pins, you need to tell the Galileo whether it is an INPUT or OUTPUT. We use a built-in “function” called pinMode() to do this.

digitalWrite(13, HIGH);

When you’re using a pin as an OUTPUT, you can command it to be HIGH (output 5 volts), or LOW (output 0 volts).

Copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Inventor's Kit Galileo
Example sketch 01

BLINKING A LED

  Turn an LED on for one second, off for one second,
  and repeat forever.

Hardware connections:

  Most Arduinos already have an LED and resistor connected to
  pin 13, so you may not need any additional circuitry.

  But if you'd like to connect a second LED to pin 13, or use
  a different pin, follow these steps:

    Connect the positive side of your LED (longer leg) to Galileo
    digital pin 13 (or another digital pin, don't forget to change
    the code to match).

    Connect the negative side of your LED (shorter leg) to a
    330 Ohm resistor (orange-orange-brown). Connect the other side
    of the resistor to ground.

    pin 13 _____ + LED - _____ 330 Ohm _____ GND

    (We always use resistors between the Galileo and and LEDs
    to keep the LEDs from burning out due to too much current.)

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/


// Welcome to the Galileo!

// If you're brand-new to this, there will be some new things to
// learn, but we'll jump right in and explain things as we go.

// The Galileo is a tiny computer that runs programs called
// "sketches". These are text files written using instructions
// the computer understances. You're reading a sketch right now.

// Sketches have computer code in them, but also (hopefully)
// "comments" that explain what the code does. Comments and code
// will have different colors in the editor so you can tell them
// apart.

// This is a comment - anything on a line after "//" is ignored
// by the computer.

/* This is also a comment - this one can be multi-line, but it
must start and end with these characters */

// A "function" is a named block of code, that performs a specific,
// well, function. Many useful functions are already built-in to
// the Galileo; others you'll name and write yourself for your
// own purposes.

// All Galileo sketches MUST have two specific functions, named
// "setup()" and "loop()". The Galileo runs these functions
// automatically when it starts up or if you press the reset
// button. You'll typically fill these function "shells" with your
// own code. Let's get started!


// The setup() function runs once when the sketch starts.
// You'll use it for things you need to do first, or only once:


void setup()
{
  // The Galileo has 13 digital input/output pins. These pins
  // can be configured as either inputs or outputs. We set this
  // up with a built-in function called pinMode().

  // The pinMode() function takes two values, which you type in
  // the parenthesis after the function name. The first value is
  // a pin number, the second value is the word INPUT or OUTPUT.

  // Here we'll set up pin 13 (the one connected to a LED) to be
  // an output. We're doing this because we need to send voltage
  // "out" of the Galileo to the LED.

  pinMode(13, OUTPUT);

  // By the way, the Galileo offers many useful built-in functions
  // like this one. You can find information on all of them at the
  // Galileo website: http://arduino.cc/en/Reference
}


// After setup() finishes, the loop() function runs over and over
// again, forever (or until you turn off or reset the Galileo).
// This is usually where the bulk of your program lives:


void loop()
{
  // The 13 digital pins on your Galileo are great at inputting
  // and outputting on/off, or "digital" signals. These signals
  // will always be either 5 Volts (which we call "HIGH"), or
  // 0 Volts (which we call "LOW").

  // Because we have an LED connected to pin 13, if we make that
  // output HIGH, the LED will get voltage and light up. If we make
  // that output LOW, the LED will have no voltage and turn off.

  // digitalWrite() is the built-in function we use to make an
  // output pin HIGH or LOW. It takes two values; a pin number,
  // followed by the word HIGH or LOW:

  digitalWrite(13, HIGH);   // Turn on the LED

  // delay() is a function that pauses for a given amount of time.
  // It takes one value, the amount of time to wait, measured in
  // milliseconds. There are 1000 milliseconds in a second, so if
  // you delay(1000), it will pause for exactly one second:

  delay(1000);              // Wait for one second

  digitalWrite(13, LOW);    // Turn off the LED

  delay(1000);              // Wait for one second

  // All together, the above code turns the LED on, waits one
  // second, turns it off, and waits another second.

  // When the computer gets to the end of the loop() function,
  // it starts loop() over again. So this program will continue
  // blinking the LED on and off!

  // Try changing the 1000 in the above delay() functions to
  // different numbers and see how it affects the timing. Smaller
  // values will make the loop run faster. (Why?)
}

What You Should See

You should see your LED blink on and off. If it isn’t, make sure you have assembled the circuit correctly and verified and uploaded the code to your board, or see the troubleshooting section.

Galileo LED blink

Real World Application

Almost all modern flat screen televisions and monitors have LED indicator lights to show they are on or off.

Troubleshooting

LED Not Lighting Up?

LEDs will only work in one direction. Try taking it out and twisting it 180 degrees (no need to worry, installing it backward does no permanent harm).

Program Not Uploading

This happens sometimes, the most likely cause is a confused serial port, you can change this in tools > serial port >

Still No Success?

A broken circuit is no fun, send us an e-mail and we will get back to you as soon as we can: techsupport@sparkfun.com

SIK Galileo - Part 2: Reading a Potentiometer

Introduction

In this circuit you’ll work with a potentiometer.

A potentiometer is also known as a variable resistor. When powered with 5V, the middle pin outputs a voltage between 0V and 5V, depending on the position of the knob on the potentiometer. A potentiometer is a perfect demonstration of a variable voltage divider circuit. The voltage is divided proportionate to the resistance between the middle pin and the ground pin. In this circuit, you’ll learn how to use a potentiometer to control the brightness of an LED.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x Galileo
  • 1x LED
  • 1x 330Ω Resistor
  • 6x Jumper Wires
  • 1x Potentiometer

If you are following through all of the SIK Galileo tutorials we suggest using these parts:

Trimpot 10K with Knob

Trimpot 10K with Knob

In stock COM-09806

There are lots of trimpots out there. Some are very large, some so small they require a screwdriver. Here at SparkFun, we jus…

0.95
Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

Out of stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

Out of stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

1/6 Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 330Ohm resistors make excellent…

0.95
LED - Assorted (20 pack)

LED - Assorted (20 pack)

In stock COM-12062

We all know that you can never get too many LEDs. Don't worry, we've got you covered. This is a pack of basic red, yellow, bl…

2.95
Intel® Galileo

Intel® Galileo

In stock DEV-12720

The Intel® Galileo board is based on the Intel® Quark SoC X1000, a 32-bit Intel Pentium®-class system on a chip (SoC). It …

79.95

View the SparkFun Inventor’s Kit for Galileo wishlist, to see the parts needed to go through the all the experiments.

Suggested Reading

Before continuing on with this experiment, we recommend you be familiar with the concepts in the following tutorial:

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram and hookup table below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components are highlighted with a yellow warning triangle, in the table. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram

Fritzing Pot Galileo

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Hookup Table

ComponentGalileoBreadboardBreadboardBreadboard
330 Resistorj21( - )
h20 ( + )h21 ( - )
Potentiometerb6b7b8
Jumper Wiree6( - )
Jumper WireA0e7
Jumper Wiree8( + )
Jumper WirePIN 13j20
Jumper Wire5V( + )
Jumper WireGND( - )

Code To Note

int sensorValue;

A “variable” is a placeholder for values that may change in your code. You must introduce, or “declare” variables before you use them; here we’re declaring a variable called sensorValue, of type “int” (integer). Don’t forget that variable names are case-sensitive!

sensorValue = analogRead(sensorPin);

We use the analogRead() function to read the value on an analog pin. analogRead() takes one parameter, the analog pin you want to use (“sensorPin”), and returns a number (“sensorValue”) between 0 (0 volts) and 1023 (5 volts).

delay(sensorValue);

Microcontrollers are very fast, capable of running thousands of lines of code each second. To slow it down so that we can see what it’s doing, we’ll often insert delays into the code. delay() counts in milliseconds; there are 1000 ms in one second.

Copy and paste the following code into the Arduino IDE. Hit upload and see what happens!

language:cpp
/* SparkFun Inventor's Kit Galileo
Example sketch 02

POTENTIOMETER

  Measure the position of a potentiometer and use it to
  control the blink rate of an LED. Turn the knob to make
  it blink faster or slower!

What's a potentiometer?

  A potentiometer, or "pot" for short, is a control knob.
  It's the same type of control you'd use to change volume,
  dim a lamp, etc. A potentiometer changes resistance as it
  is turned. By using it as a "voltage divider", the Arduino
  can sense the position of the knob, and use that value to
  control whatever you wish (like the blink rate of an LED,
  as we're doing here).

Hardware connections:

  Potentiometer:

    Potentiometers have three pins. When we're using it as a
    voltage divider, we connect the outside pins to power and
    ground. The middle pin will be the signal (a voltage which
    varies from 0 Volts to 5 Volts depending on the position of
    the knob).

    Connect the middle pin to ANALOG IN pin 0 on the Galileo.
    Connect one of the outside pins to 5V.
    Connect the other outside pin to GND.

    (TIP: if once your program is running, the knob feels
    "backwards", you can swap the 5V and GND pins to reverse
    the direction.)

  LED:

    Most Arduinos already have an LED and resistor connected to
    pin 13, so you may not need any additional circuitry.

    But if you'd like to connect a second LED to pin 13, or use
    a different pin, follow these steps:

      Connect the positive side of your LED (longer leg) to
      Arduino digital pin 13 (or another digital pin, but don't
      forget to change the code to match).

      Connect the negative side of your LED (shorter leg) to a
      330 Ohm resistor (orange-orange-brown).

      Connect the other side of the resistor to ground.

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/


// Welcome back! In this sketch we'll start using "variables".

// A variable is a named number. We'll often use these to store
// numbers that change, such as measurements from the outside
// world, or to make a sketch easier to understand (sometimes a
// descriptive name makes more sense than looking at a number).

// Variables can be different "data types", which is the kind of
// number we're using (can it be negative? Have a decimal point?)
// We'll introduce more data types later, but for the moment we'll
// stick with good old "integers" (called "int" in your sketch).

// Integers are whole numbers (0, 3, 5643), can be negative, and
// for reasons we won't go into right now, can range from -32768
// to 32767. (Don't worry, if you need to work with larger numbers,
// there are other data types for that. See:
// http://arduino.cc/en/Reference/VariableDeclaration
// for a list of all the data types you can use).

// You must "declare" variables before you use them, so that the
// computer knows about them. Here we'll declare two integer
// variables, and at the same time, initialize them to specific
// values. We're doing this so that further down, we can refer to
// the pins by name rather than number.

// Note that variable names are case-sensitive! If you get an
// "(variable) was not declared in this scope" error, double-check
// that you typed the name correctly.

// Here we're creating a variable called "sensorPin" of type "int"
// and initializing it to have the value "0":

int sensorPin = 0;    // The potentiometer is connected to
                      // analog pin 0

int ledPin = 13;      // The LED is connected to digital pin 13

// One more thing. If you declare variables outside of a function,
// as we have here, they are called "global variables" and can be
// seen by all the functions. If you declare variables within a
// function, they can only be seen within that function. It's good
// practice to "limit the scope" of a variable whenever possible,
// but as we're getting started, global variables are just fine.


void setup() // this function runs once when the sketch starts up
{
  // We'll be using pin 13 to light a LED, so we must configure it
  // as an output.

  // Because we already created a variable called ledPin, and
  // set it equal to 13, we can use "ledPin" in place of "13".
  // This makes the sketch easier to follow.

  pinMode(ledPin, OUTPUT);

  // The above line is the same as "pinMode(13, OUTPUT);"

  // You might be wondering why we're not also configuring
  // sensorPin as an input. The reason is that this is an
  // "analog in" pin. These pins have the special ability to
  // read varying voltages from sensors like the potentiometer.
  // Since they're always used as inputs, there is no need to
  // specifically configure them.
}


void loop() // this function runs repeatedly after setup() finishes
{
  // First we'll declare another integer variable
  // to store the value of the potentiometer:

  int sensorValue;

  // The potentiometer is set up as a voltage divider, so that
  // when you turn it, the voltage on the center pin will vary
  // from 0V to 5V. We've connected the center pin on the
  // potentiometer to the Arduino's analog input 0.

  // The Arduino can read external voltages on the analog input
  // pins using a built-in function called analogRead(). This
  // function takes one input value, the analog pin we're using
  // (sensorPin, which we earlier set to 0). It returns an integer
  // number that ranges from 0 (0 Volts) to 1023 (5 Volts).
  // We're sticking this value into the sensorValue variable:

  sensorValue = analogRead(sensorPin);

  // Now we'll blink the LED like in the first example, but we'll
  // use the sensorValue variable to change the blink speed
  // (the smaller the number, the faster it will blink).

  // Note that we're using the ledPin variable here as well:

  digitalWrite(ledPin, HIGH);     // Turn the LED on

  delay(sensorValue);             // Pause for sensorValue
                                  // milliseconds

  digitalWrite(ledPin, LOW);      // Turn the LED off

  delay(sensorValue);             // Pause for sensorValue
                                  // milliseconds

  // Remember that loop() repeats forever, so we'll do all this
  // again and again.
}

What You Should See

You should see the LED blink faster or slower in accordance with your potentiometer. If it isn’t working, make sure you have assembled the circuit correctly and verified and uploaded the code to your board, or see the troubleshooting section.

Galileo Pot

Real World Application

Most traditional volume knobs employ a potentiometer.

Troubleshooting

Sporadically Working

This is most likely due to a slightly dodgy connection with the potentiometer’s pins. This can usually be conquered by holding the potentiometer down.

Not Working

Make sure you haven’t accidentally connected the wiper, the resistive element in the potentiometer, to digital pin 0 rather than analog pin 0. (the row of pins beneath the power pins).

LED Not Lighting Up?

LEDs will only work in one direction. Double check your connections.

SIK Galileo - Part 3: Driving and RGB LED

Introduction

You know what’s even more fun than a blinking LED? Changing colors with one LED. RGB, or red-green-blue, LEDs have three different color-emitting diodes that can be combined to create all sorts of colors. In this circuit, you’ll learn how to use an RGB LED to create unique color combinations. Depending on how bright each diode is, nearly any color is possible!

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x Galileo
  • 1x LED - RGB Common Cathode
  • 3x 330Ω Resistors
  • 5x Jumper Wires

If you are following through all of the SIK Galileo tutorials we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

Out of stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
LED - RGB Clear Common Cathode

LED - RGB Clear Common Cathode

In stock COM-00105

Ever hear of a thing called RGB? Red, Green, Blue? How about an RGB LED? These 5mm units have four pins - Cathode is the long…

1.95
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

Out of stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

1/6 Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 330Ohm resistors make excellent…

0.95
Intel® Galileo

Intel® Galileo

In stock DEV-12720

The Intel® Galileo board is based on the Intel® Quark SoC X1000, a 32-bit Intel Pentium®-class system on a chip (SoC). It …

79.95

View the SparkFun Inventor’s Kit for Galileo wishlist, to see the parts needed to go through the all the experiments.

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram and hookup table below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components are highlighted with a yellow warning triangle, in the table. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram

Fritzing Hookup

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Hookup Table

ComponentGalileoBreadboardBreadboardBreadboardBreadboard
j2 (RED)j3 (GND)j4 (GREEN)j5 (BLUE)
330 Resistord2f2
330 Resistord4f4
330 Resistord5f5
Jumper WireGND( - )
Jumper WirePIN 9a2
Jumper Wiref3( - )
Jumper WirePIN 10a4
Jumper WirePIN 11a5

Code To Note

language:cpp
for (x = 0; x < 768; x++)
{}

A for() loop is used to repeat an action a set number of times across a range, and repeatedly runs code within the brackets {}. Here the variable “x” starts a 0, ends at 767, and increases by one each time (“x++”).

language:cpp
if (x <= 255)
{}
else
{}

“If / else” statements are used to make choices in your programs. The statement within the parenthesis () is evaluated; if it’s true, the code within the first brackets {} will run. If it’s not true, the code within the second brackets {} will run.

Copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Inventor's Kit Galileo
Example sketch 03

RGB LED

Make an RGB LED display a rainbow of colors!

Hardware connections:

An RGB LED is actually three LEDs (red, green, and blue) in
one package. When you run them at different brightnesses,
the red, green and blue mix to form new colors.

Starting at the flattened edge of the flange on the LED,
the pins are ordered RED, COMMON, GREEN, BLUE.

Connect RED to a 330 ohm resistor. Connect the other end
of the resistor to Arduino digital pin 9.

Connect COMMON pin to GND.

Connect GREEN to a 330 ohm resistor. Connect the other end
of the resistor to Arduino digital pin 10.

Connect BLUE to a 330 ohm resistor. Connect the other end
of the resistor to Arduino digital pin 11.

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/


// First we'll define the pins by name to make the sketch
// easier to follow.

// Here's a new trick: putting the word "const" in front of a
// variable indicates that this is a "constant" value that will
// never change. (You don't have to do this, but if you do, the
// Arduino will give you a friendly warning if you accidentally
// try to change the value, so it's considered good form.)

const int RED_PIN = 9;
const int GREEN_PIN = 10;
const int BLUE_PIN = 11;

// This variable controls how fast we loop through the colors.
// (Try changing this to make the fading faster or slower.)

int DISPLAY_TIME = 100;  // In milliseconds


void setup()
{
// Here we'll configure the Arduino pins we're using to
// drive the LED to be outputs:

pinMode(RED_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
pinMode(BLUE_PIN, OUTPUT);
}


void loop()
{
// In this sketch, we'll start writing our own functions.
// This makes the sketch easier to follow by dividing up
// the sketch into sections, and not having everything in
// setup() or loop().

// We'll show you two ways to run the RGB LED.

// The first way is to turn the individual LEDs (red, blue,
// and green) on and off in various combinations. This gives you
// a total of eight colors (if you count "black" as a color).

// We've written a function called mainColors() that steps
// through all eight of these colors. We're only "calling" the
// function here (telling it to run). The actual function code
// is further down in the sketch.

mainColors();

// The above function turns the individual LEDs full-on and
// full-off. If you want to generate more than eight colors,
// you can do so by varying the brightness of the individual
// LEDs between full-on and full-off.

// The analogWrite() function lets us do this. This function
// lets you dim a LED from full-off to full-on over 255 steps.

// We've written a function called showSpectrum() that smoothly
// steps through all the colors. Again we're just calling it
// here; the actual code is further down in this sketch.

showSpectrum();
}


// Here's the mainColors() function we've written.

// This function displays the eight "main" colors that the RGB LED
// can produce. If you'd like to use one of these colors in your
// own sketch, you cancopy and paste that section into your code.

void mainColors()
{
// Off (all LEDs off):

digitalWrite(RED_PIN, LOW);
digitalWrite(GREEN_PIN, LOW);
digitalWrite(BLUE_PIN, LOW);

delay(1000);

// Red (turn just the red LED on):

digitalWrite(RED_PIN, HIGH);
digitalWrite(GREEN_PIN, LOW);
digitalWrite(BLUE_PIN, LOW);

delay(1000);

// Green (turn just the green LED on):

digitalWrite(RED_PIN, LOW);
digitalWrite(GREEN_PIN, HIGH);
digitalWrite(BLUE_PIN, LOW);

delay(1000);

// Blue (turn just the blue LED on):

digitalWrite(RED_PIN, LOW);
digitalWrite(GREEN_PIN, LOW);
digitalWrite(BLUE_PIN, HIGH);

delay(1000);

// Yellow (turn red and green on):

digitalWrite(RED_PIN, HIGH);
digitalWrite(GREEN_PIN, HIGH);
digitalWrite(BLUE_PIN, LOW);

delay(1000);

// Cyan (turn green and blue on):

digitalWrite(RED_PIN, LOW);
digitalWrite(GREEN_PIN, HIGH);
digitalWrite(BLUE_PIN, HIGH);

delay(1000);

// Purple (turn red and blue on):

digitalWrite(RED_PIN, HIGH);
digitalWrite(GREEN_PIN, LOW);
digitalWrite(BLUE_PIN, HIGH);

delay(1000);

// White (turn all the LEDs on):

digitalWrite(RED_PIN, HIGH);
digitalWrite(GREEN_PIN, HIGH);
digitalWrite(BLUE_PIN, HIGH);

delay(1000);
}


// Below are two more functions we've written,
// showSpectrum() and showRGB().

// showRGB() displays a single color on the RGB LED.
// You call showRGB() with the number of a color you want
// to display.

// showSpectrum() steps through all the colors of the RGB LED,
// displaying a rainbow. showSpectrum() actually calls showRGB()
// over and over to do this.

// We'll often break tasks down into individual functions like
// this, which makes your sketches easier to follow, and once
// you have a handy function, you can reuse it in your other
// programs.


// showSpectrum()

// This function steps through all the colors of the RGB LED.
// It does this by stepping a variable from 0 to 768 (the total
// number of colors), and repeatedly calling showRGB() to display
// the individual colors.

// In this function, we're using a "for() loop" to step a variable
// from one value to another, and perform a set of instructions
// for each step. For() loops are a very handy way to get numbers
// to count up or down.

// Every for() loop has three statements separated by semicolons:

//   1. Something to do before starting

//   2. A test to perform; as long as it's true,
//      it will keep looping

//   3. Something to do after each loop (usually
//      increase a variable)

// For the for() loop below, these are the three statements:

//   1. x = 0;     Before starting, make x = 0.

//   2. x < 768;   While x is less than 768, run the
//                 following code.

//   3. x++        Putting "++" after a variable means
//                 "add one to it". (You can also use "x = x + 1")

// Every time you go through the loop, the statements following
// the loop (those within the brackets) will run.

// And when the test in statement 2 is finally false, the sketch
// will continue.


void showSpectrum()
{
int x;  // define an integer variable called "x"

// Now we'll use a for() loop to make x count from 0 to 767
// (Note that there's no semicolon after this line!
// That's because the for() loop will repeat the next
// "statement", which in this case is everything within
// the following brackets {} )

for (x = 0; x < 768; x++)

// Each time we loop (with a new value of x), do the following:

{
showRGB(x);  // Call RGBspectrum() with our new x
delay(10);   // Delay for 10 ms (1/100th of a second)
}
}


// showRGB()

// This function translates a number between 0 and 767 into a
// specific color on the RGB LED. If you have this number count
// through the whole range (0 to 767), the LED will smoothly
// change color through the entire spectrum.

// The "base" numbers are:
// 0   = pure red
// 255 = pure green
// 511 = pure blue
// 767 = pure red (again)

// Numbers between the above colors will create blends. For
// example, 640 is midway between 512 (pure blue) and 767
// (pure red). It will give you a 50/50 mix of blue and red,
// resulting in purple.

// If you count up from 0 to 767 and pass that number to this
// function, the LED will smoothly fade between all the colors.
// (Because it starts and ends on pure red, you can start over
// at 0 without any break in the spectrum).


void showRGB(int color)
{
int redIntensity;
int greenIntensity;
int blueIntensity;

// Here we'll use an "if / else" statement to determine which
// of the three (R,G,B) zones x falls into. Each of these zones
// spans 255 because analogWrite() wants a number from 0 to 255.

// In each of these zones, we'll calculate the brightness
// for each of the red, green, and blue LEDs within the RGB LED.

if (color <= 255)          // zone 1
{
redIntensity = 255 - color;    // red goes from on to off
greenIntensity = color;        // green goes from off to on
blueIntensity = 0;             // blue is always off
}
else if (color <= 511)     // zone 2
{
redIntensity = 0;                     // red is always off
greenIntensity = 255 - (color - 256); // green on to off
blueIntensity = (color - 256);        // blue off to on
}
else // color >= 512       // zone 3
{
redIntensity = (color - 512);         // red off to on
greenIntensity = 0;                   // green is always off
blueIntensity = 255 - (color - 512);  // blue on to off
}

// Now that the brightness values have been set, command the LED
// to those values

analogWrite(RED_PIN, redIntensity);
analogWrite(BLUE_PIN, blueIntensity);
analogWrite(GREEN_PIN, greenIntensity);
}

What You Should See

You should see your LED turn on, but this time in new, crazy colors! If it isn’t, make sure you have assembled the circuit correctly and verified and uploaded the code to your board or see the troubleshooting section.

Galileo RGB

Real World Application

Many electronics such as video game consoles use RGB LEDs to have the versatility to show different colors in the same area. Often times the different colors represent different states of working condition.

Troubleshooting

LED Remains Dark or Shows Incorrect Color

With the four pins of the LED so close together, it’s sometimes easy to misplace one. Double check each pin is where it should be.

Seeing Red

The red diode within the RGB LED may be a bit brighter than the other two. To make your colors more balanced, use a higher ohm resistor. Or adjust in code.

analogWrite(RED_PIN, redIntensity);

to

analogWrite(RED_PIN, redIntensity/3);

SIK Galileo - Part 4: Driving Multiple LEDs

Introduction

Now that you’ve gotten your LED to blink on and off, it’s time to up the stakes a little bit – by connecting eight LEDs at once. We’ll also give our Galileo a little test by creating various lighting sequences. This circuit is a great setup to start practicing writing your own programs and getting a feel for the way Galileo works.

Along with controlling the LEDs, you’ll learn about a couple programming tricks that keep your code neat and tidy:

for() loops - used when you want to run a piece of code several times

arrays[ ] - used to make managing variables easier by grouping them together

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x Galileo
  • 8x LEDs
  • 8x 330Ω Resistors
  • 9x Jumper Wires

If you are following through all of the SIK Galileo tutorials we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

Out of stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

Out of stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

1/6 Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 330Ohm resistors make excellent…

0.95
LED - Assorted (20 pack)

LED - Assorted (20 pack)

In stock COM-12062

We all know that you can never get too many LEDs. Don't worry, we've got you covered. This is a pack of basic red, yellow, bl…

2.95
Intel® Galileo

Intel® Galileo

In stock DEV-12720

The Intel® Galileo board is based on the Intel® Quark SoC X1000, a 32-bit Intel Pentium®-class system on a chip (SoC). It …

79.95

View the SparkFun Inventor’s Kit for Galileo wishlist, to see the parts needed to go through the all the experiments.

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram and hookup table below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram

Fritzing diagram

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Code To Note

int ledPins[] = {2,3,4,5,6,7,8,9};

When you have to manage a lot of variables, an “array” is a handy way to group them together. Here we’re creating an array of integers, called ledPins, with eight elements.

digitalWrite(ledPins[0], HIGH);

You refer to the elements in an array by their position. The first element is at position 0, the second is at position 1, etc. You refer to an element using “ledPins[x]” where x is the position. Here we’re making digital pin 2 HIGH, since the array element at position 0 is “2”.

index = random(8);

Computers like to do the same things each time they run. But sometimes you want to do things randomly, such as simulating the roll of a dice. The random() function is a great way to do this. See http://arduino.cc/en/reference/random for more information.

Copy and paste the following code into the Arduino IDE. Hit upload and see what happens!

language:cpp
/*
SparkFun Inventor's Kit Galileo
Example sketch 04

MULTIPLE LEDs

  Make eight LEDs dance. Dance LEDs, dance!

Hardware connections:

  You'll need eight LEDs, and eight 330 Ohm resistors
  (orange-orange-brown).

    For each LED, connect the negative side (shorter leg)
    to a 330 Ohm resistor.

    Connect the other side of the resistors to GND.

    Connect the positive side (longer leg) of the LEDs
    to Arduino digital pins 2 through 9.

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/


// To keep track of all the LED pins, we'll use an "array".
// An array lets you store a group of variables, and refer to them
// by their position, or "index". Here we're creating an array of
// eight integers, and initializing them to a set of values:

int ledPins[] = {2,3,4,5,6,7,8,9};

// The first element of an array is index 0.
// We've put the value "2" in index 0, "3" in index 1, etc.
// The final index in the above array is 7, which contains
// the value "9".

// We're using the values in this array to specify the pin numbers
// that the eight LEDs are connected to. LED 0 is connected to
// pin 2, LED 1 is connected to pin 3, etc.


void setup()
{
  int index;

  // In this sketch, we'll use "for() loops" to step variables from
  // one value to another, and perform a set of instructions for
  // each step. For() loops are a very handy way to get numbers to
  // count up or down.

  // Every for() loop has three statements separated by
  // semicolons (;):

  //   1. Something to do before starting
  //   2. A test to perform; as long as it's true, keep looping
  //   3. Something to do after each loop (increase a variable)

  // For the for() loop below, these are the three statements:

  //   1. index = 0;    Before starting, make index = 0.
  //   2. index <= 7;   If index is less or equal to 7,
  //                    run the following code.
  //            (When index = 8, continue with the sketch.)
  //   3. index++   Putting "++" after a variable means
  //                    "add one to it".
  //            (You can also use "index = index + 1".)

  // Every time you go through the loop, the statements following
  // the for() (within the brackets) will run.

  // When the test in statement 2 is finally false, the sketch
  // will continue.


  // Here we'll use a for() loop to initialize all the LED pins
  // to outputs. This is much easier than writing eight separate
  // statements to do the same thing.

  // This for() loop will make index = 0, then run the pinMode()
  // statement within the brackets. It will then do the same thing
  // for index = 2, index = 3, etc. all the way to index = 7.

  for(index = 0; index <= 7; index++)
  {
    pinMode(ledPins[index],OUTPUT);
    // ledPins[index] is replaced by the value in the array.
    // For example, ledPins[0] is 2
  }
}


void loop()
{
  // This loop() calls functions that we've written further below.
  // We've disabled some of these by commenting them out (putting
  // "//" in front of them). To try different LED displays, remove
  // the "//" in front of the ones you'd like to run, and add "//"
  // in front of those you don't to comment out (and disable) those
  // lines.

  oneAfterAnotherNoLoop();  // Light up all the LEDs in turn

  //oneAfterAnotherLoop();  // Same as oneAfterAnotherNoLoop,
                            // but with much less typing

  //oneOnAtATime();         // Turn on one LED at a time,
                            // scrolling down the line

  //pingPong();             // Light the LEDs middle to the edges

  //marquee();              // Chase lights like you see on signs

  //randomLED();            // Blink LEDs randomly
}


/*
oneAfterAnotherNoLoop()

This function will light one LED, delay for delayTime, then light
the next LED, and repeat until all the LEDs are on. It will then
turn them off in the reverse order.

This function does NOT use a for() loop. We've done it the hard way
to show you how much easier life can be when you use for() loops.
Take a look at oneAfterAnotherLoop() further down, which does
exactly the same thing with much less typing.
*/

void oneAfterAnotherNoLoop()
{
  int delayTime = 100; // time (milliseconds) to pause between LEDs
                       // make this smaller for faster switching

  // turn all the LEDs on:

  digitalWrite(ledPins[0], HIGH);  //Turns on LED #0 (pin 2)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[1], HIGH);  //Turns on LED #1 (pin 3)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[2], HIGH);  //Turns on LED #2 (pin 4)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[3], HIGH);  //Turns on LED #3 (pin 5)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[4], HIGH);  //Turns on LED #4 (pin 6)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[5], HIGH);  //Turns on LED #5 (pin 7)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[6], HIGH);  //Turns on LED #6 (pin 8)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[7], HIGH);  //Turns on LED #7 (pin 9)
  delay(delayTime);                //wait delayTime milliseconds

  // turn all the LEDs off:

  digitalWrite(ledPins[7], LOW);   //Turn off LED #7 (pin 9)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[6], LOW);   //Turn off LED #6 (pin 8)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[5], LOW);   //Turn off LED #5 (pin 7)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[4], LOW);   //Turn off LED #4 (pin 6)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[3], LOW);   //Turn off LED #3 (pin 5)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[2], LOW);   //Turn off LED #2 (pin 4)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[1], LOW);   //Turn off LED #1 (pin 3)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[0], LOW);   //Turn off LED #0 (pin 2)
  delay(delayTime);                //wait delayTime milliseconds
}


/*
oneAfterAnotherLoop()

This function does exactly the same thing as oneAfterAnotherNoLoop(),
but it takes advantage of for() loops and the array to do it with
much less typing.
*/

void oneAfterAnotherLoop()
{
  int index;
  int delayTime = 100; // milliseconds to pause between LEDs
                       // make this smaller for faster switching

  // Turn all the LEDs on:

  // This for() loop will step index from 0 to 7
  // (putting "++" after a variable means add one to it)
  // and will then use digitalWrite() to turn that LED on.

  for(index = 0; index <= 7; index++)
  {
    digitalWrite(ledPins[index], HIGH);
    delay(delayTime);
  }

  // Turn all the LEDs off:

  // This for() loop will step index from 7 to 0
  // (putting "--" after a variable means subtract one from it)
  // and will then use digitalWrite() to turn that LED off.

  for(index = 7; index >= 0; index--)
  {
    digitalWrite(ledPins[index], LOW);
    delay(delayTime);
  }
}


/*
oneOnAtATime()

This function will step through the LEDs,
lighting only one at at time.
*/

void oneOnAtATime()
{
  int index;
  int delayTime = 100; // milliseconds to pause between LEDs
                       // make this smaller for faster switching

  // step through the LEDs, from 0 to 7

  for(index = 0; index <= 7; index++)
  {
    digitalWrite(ledPins[index], HIGH);  // turn LED on
    delay(delayTime);                    // pause to slow down
    digitalWrite(ledPins[index], LOW);   // turn LED off
  }
}


/*
pingPong()

This function will step through the LEDs,
lighting one at at time in both directions.
*/

void pingPong()
{
  int index;
  int delayTime = 100; // milliseconds to pause between LEDs
                       // make this smaller for faster switching

  // step through the LEDs, from 0 to 7

  for(index = 0; index <= 7; index++)
  {
    digitalWrite(ledPins[index], HIGH);  // turn LED on
    delay(delayTime);                    // pause to slow down
    digitalWrite(ledPins[index], LOW);   // turn LED off
  }

  // step through the LEDs, from 7 to 0

  for(index = 7; index >= 0; index--)
  {
    digitalWrite(ledPins[index], HIGH);  // turn LED on
    delay(delayTime);                    // pause to slow down
    digitalWrite(ledPins[index], LOW);   // turn LED off
  }
}


/*
marquee()

This function will mimic "chase lights" like those around signs.
*/

void marquee()
{
  int index;
  int delayTime = 200; // milliseconds to pause between LEDs
                       // Make this smaller for faster switching

  // Step through the first four LEDs
  // (We'll light up one in the lower 4 and one in the upper 4)

  for(index = 0; index <= 3; index++) // Step from 0 to 3
  {
    digitalWrite(ledPins[index], HIGH);    // Turn a LED on
    digitalWrite(ledPins[index+4], HIGH);  // Skip four, and turn that LED on
    delay(delayTime);                      // Pause to slow down the sequence
    digitalWrite(ledPins[index], LOW);     // Turn the LED off
    digitalWrite(ledPins[index+4], LOW);   // Skip four, and turn that LED off
  }
}


/*
randomLED()

This function will turn on random LEDs. Can you modify it so it
also lights them for random times?
*/

void randomLED()
{
  int index;
  int delayTime;

  // The random() function will return a semi-random number each
  // time it is called. See http://arduino.cc/en/Reference/Random
  // for tips on how to make random() even more random.

  index = random(8);    // pick a random number between 0 and 7
  delayTime = 100;

  digitalWrite(ledPins[index], HIGH);  // turn LED on
  delay(delayTime);                    // pause to slow down
  digitalWrite(ledPins[index], LOW);   // turn LED off
}

What You Should See

This is similar to circuit number one, but instead of one LED, you should see all the LEDs blink. If they aren’t, make sure you have assembled the circuit correctly and verified and uploaded the code to your board, or see the troubleshooting section.

Galileo LEDs

Real World Application

Scrolling marquee displays are generally used to spread short segments of important information. They are built out of many LEDs.

Troubleshooting

Some LEDs Fail to Light

It is easy to insert an LED backwards. Check the LEDs that aren’t working and ensure they are in the correct orientation.

Operating out of sequence

With eight wires it’s easy to cross a couple. Double check that the first LED is plugged into pin 2 and each pin thereafter.

Starting Fresh

It’s easy to accidentally misplace a wire without noticing. Pulling everything out and starting with a fresh slate is often easier than trying to track down the problem.

SIK Galileo - Part 5: Push Buttons

Introduction

Up until now, we’ve focused mostly on outputs. Now we’re going to go to the other end of spectrum and play around with inputs. In Circuit 2, we used an analog input to read the potentiometer. In this circuit, we’ll be reading in one of the most common and simple inputs – a push button – by using a digital input. The way a push button works with Galileo is that when the button is pushed, the voltage goes LOW. The Galileo reads this and reacts accordingly.

In this circuit, you will also use a pull-up resistor, which keeps the voltage HIGH when you’re not pressing the button.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x Galileo
  • 1x LED
  • 1x 330Ω Resistor
  • 7x Jumper Wires
  • 2x Push Buttons
  • 2x 10k Resistors

If you are following through all of the SIK Galileo tutorials we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

Out of stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Tactile Button Assortment

Tactile Button Assortment

In stock COM-10302

These tactile buttons are great for all sorts of projects. This assortment comes with 2 of each of 6 different colors for a t…

4.95
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

Out of stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

1/6 Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 330Ohm resistors make excellent…

0.95
LED - Assorted (20 pack)

LED - Assorted (20 pack)

In stock COM-12062

We all know that you can never get too many LEDs. Don't worry, we've got you covered. This is a pack of basic red, yellow, bl…

2.95
Resistor 10K Ohm 1/6th Watt PTH - 20 pack

Resistor 10K Ohm 1/6th Watt PTH - 20 pack

In stock COM-11508

1/6th Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 10K resistors make excellent …

0.95
Intel® Galileo

Intel® Galileo

In stock DEV-12720

The Intel® Galileo board is based on the Intel® Quark SoC X1000, a 32-bit Intel Pentium®-class system on a chip (SoC). It …

79.95

View the SparkFun Inventor’s Kit for Galileo wishlist, to see the parts needed to go through the all the experiments.

Suggested Reading

Before continuing on with this tutorial, we recommend you be somewhat familiar with the concepts in these tutorials:

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram

Fritzing

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Code To Note

pinMode(button2Pin, INPUT);

The digital pins can be used as inputs as well as outputs. Before you do either, you need to tell the Galileo which direction you’re going.

button1State = digitalRead(button1Pin);

To read a digital input, you use the digitalRead() function. It will return HIGH if there’s 5V present at the pin, or LOW if there’s 0V present at the pin.

if (button1State == LOW)

Because we’ve connected the button to GND, it will read LOW when it’s being pressed. Here we’re using the “equivalence” operator (“==”) to see if the button is being pressed.

Copy and paste the following code into the Arduino IDE. Hit upload and see what happens!

language:cpp
/*
SparkFun Inventor's Kit Galileo
Example sketch 05

PUSH BUTTONS

  Use pushbuttons for digital input

  Previously we've used the analog pins for input, now we'll use
  the digital pins for input as well. Because digital pins only
  know about HIGH and LOW signals, they're perfect for interfacing
  to pushbuttons and switches that also only have "on" and "off"
  states.

  We'll connect one side of the pushbutton to GND, and the other
  side to a digital pin. When we press down on the pushbutton,
  the pin will be connected to GND, and therefore will be read
  as "LOW" by the Arduino.

  But wait - what happens when you're not pushing the button?
  In this state, the pin is disconnected from everything, which
  we call "floating". What will the pin read as then, HIGH or LOW?
  It's hard to say, because there's no solid connection to either
  5 Volts or GND. The pin could read as either one.

  To deal with this issue, we'll connect a small (10K, or 10,000 Ohm)
  resistance between the pin and 5 Volts. This "pullup" resistor
  will ensure that when you're NOT pushing the button, the pin will
  still have a weak connection to 5 Volts, and therefore read as
  HIGH.

  (Advanced: when you get used to pullup resistors and know when
  they're required, you can activate internal pullup resistors
  on the ATmega processor in the Arduino. See
  http://arduino.cc/en/Tutorial/DigitalPins for information.)

Hardware connections:

  Pushbuttons:

    Pushbuttons have two contacts that are connected if you're
    pushing the button, and disconnected if you're not.

    The pushbuttons we're using have four pins, but two pairs
    of these are connected together. The easiest way to hook up
    the pushbutton is to connect two wires to any opposite corners.

    Connect any pin on pushbutton 1 to ground (GND).
    Connect the opposite diagonal pin of the pushbutton to
    digital pin 2.

    Connect any pin on pushbutton 2 to ground (GND).
    Connect the opposite diagonal pin of the pushbutton to
    digital pin 3.

    Also connect 10K resistors (brown/black/red) between
    digital pins 2 and 3 and GND. These are called "pullup"
    resistors. They ensure that the input pin will be either
    5V (unpushed) or GND (pushed), and not somewhere in between.
    (Remember that unlike analog inputs, digital inputs are only
    HIGH or LOW.)

  LED:

    Most Arduinos, including the Uno, already have an LED
    and resistor connected to pin 13, so you don't need any
    additional circuitry.

    But if you'd like to connect a second LED to pin 13,

    Connect the positive side of your LED to Arduino digital pin 13
    Connect the negative side of your LED to a 330 Ohm resistor
    Connect the other side of the resistor to ground

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/


// First we'll set up constants for the pin numbers.
// This will make it easier to follow the code below.

const int button1Pin = 2;  // pushbutton 1 pin
const int button2Pin = 3;  // pushbutton 2 pin
const int ledPin =  13;    // LED pin


void setup()
{
  // Set up the pushbutton pins to be an input:
  pinMode(button1Pin, INPUT);
  pinMode(button2Pin, INPUT);

  // Set up the LED pin to be an output:
  pinMode(ledPin, OUTPUT);
}


void loop()
{
  int button1State, button2State;  // variables to hold the pushbutton states

  // Since a pushbutton has only two states (pushed or not pushed),
  // we've run them into digital inputs. To read an input, we'll
  // use the digitalRead() function. This function takes one
  // parameter, the pin number, and returns either HIGH (5V)
  // or LOW (GND).

  // Here we'll read the current pushbutton states into
  // two variables:

  button1State = digitalRead(button1Pin);
  button2State = digitalRead(button2Pin);

  // Remember that if the button is being pressed, it will be
  // connected to GND. If the button is not being pressed,
  // the pullup resistor will connect it to 5 Volts.

  // So the state will be LOW when it is being pressed,
  // and HIGH when it is not being pressed.

  // Now we'll use those states to control the LED.
  // Here's what we want to do:

  // "If either button is being pressed, light up the LED"
  // "But, if BOTH buttons are being pressed, DON'T light up the LED"

  // Let's translate that into computer code. The Arduino gives you
  // special logic functions to deal with true/false logic:

  // A == B means "EQUIVALENT". This is true if both sides are the same.
  // A && B means "AND". This is true if both sides are true.
  // A || B means "OR". This is true if either side is true.
  // !A means "NOT". This makes anything after it the opposite (true or false).

  // We can use these operators to translate the above sentences
  // into logic statements (Remember that LOW means the button is
  // being pressed)

  // "If either button is being pressed, light up the LED"
  // becomes:
  // if ((button1State == LOW) || (button2State == LOW)) // light the LED

  // "If BOTH buttons are being pressed, DON'T light up the LED"
  // becomes:
  // if ((button1State == LOW) && (button2State == LOW)) // don't light the LED

  // Now let's use the above functions to combine them into one statement:

  if (((button1State == LOW) || (button2State == LOW))  // if we're pushing button 1 OR button 2
      && !                                               // AND we're NOT
      ((button1State == LOW) && (button2State == LOW))) // pushing button 1 AND button 2
                                                        // then...
  {
    digitalWrite(ledPin, HIGH);  // turn the LED on
  }
  else
  {
    digitalWrite(ledPin, LOW);  // turn the LED off
  }

  // As you can see, logic operators can be combined to make
  // complex decisions!

  // Don't forget that we use = when we're assigning a value,
  // and use == when we're testing a value for equivalence.
}

What You Should See

You should see the LED turn on if you press either button, and off if you press both buttons. (See the code to find out why!) If it isn’t working, make sure you have assembled the circuit correctly and verified and uploaded the code to your board or see the troubleshooting section.

Galileo Push Buttons

Real World Application

The buttons we used here are similar to the buttons in most video game controllers.

Troubleshooting

Light Not Turning On

The pushbutton is square, and because of this it is easy to put it in the wrong way. Give it a 90 degree twist and see if it starts working.

Underwhelmed

No worries, these circuits are all super stripped down to make playing with the components easy, but once you throw them together the sky is the limit.

SIK Galileo - Part 6: Reading a Photoresistor

Introduction

In Circuit 2, you got to use a potentiometer, which varies resistance based on the twisting of a knob. In this circuit, you’ll be using a photoresistor, which changes resistance based on how much light the sensor receives. Since the Galileo can’t directly interpret resistance (rather, it reads voltage), we need to use a voltage divider to use our photoresistor. This voltage divider will output a high voltage when it is getting a lot of light and a low voltage when little or no light is present.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x Galileo
  • 1x LED
  • 1x 330Ω Resistor
  • 6x Jumper Wires
  • 1x Photoresistor
  • 1x 10k Resistor

If you are following through all of the SIK Galileo tutorials we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

Out of stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Mini Photocell

Mini Photocell

In stock SEN-09088

This is a very small light sensor. A photocell changes (also called a [photodetector](http://en.wikipedia.org/wiki/Photodetec…

1.5
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

Out of stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

1/6 Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 330Ohm resistors make excellent…

0.95
LED - Assorted (20 pack)

LED - Assorted (20 pack)

In stock COM-12062

We all know that you can never get too many LEDs. Don't worry, we've got you covered. This is a pack of basic red, yellow, bl…

2.95
Resistor 10K Ohm 1/6th Watt PTH - 20 pack

Resistor 10K Ohm 1/6th Watt PTH - 20 pack

In stock COM-11508

1/6th Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 10K resistors make excellent …

0.95
Intel® Galileo

Intel® Galileo

In stock DEV-12720

The Intel® Galileo board is based on the Intel® Quark SoC X1000, a 32-bit Intel Pentium®-class system on a chip (SoC). It …

79.95

View the SparkFun Inventor’s Kit for Galileo wishlist, to see the parts needed to go through the all the experiments.

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram

Fritzing

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Code To Note

lightLevel = map(lightLevel, 0, 1023, 0, 255);

Parameters

map(value, fromLow, fromHigh, toLow, toHigh)

value: the number to map

fromLow: the lower bound of the value’s current range

fromHigh: the upper bound of the value’s current range

toLow: the lower bound of the value’s target range

toHigh: the upper bound of the value’s target range

When we read an analog signal using analogRead(), it will be a number from 0 to 1023. But when we want to drive a PWM pin using analogWrite(), it wants a number from 0 to 255. We can “squeeze” the larger range into the smaller range using the map() function. See Arduino’s map reference page for more info.

lightLevel = constrain(lightLevel, 0, 255);

Parameters

constrain(x, a, b)

x: the number to constrain, all data types

a: the lower end of the range, all data types

b: the upper end of the range, all data types

Because map() could still return numbers outside the “to” range, we’ll also use a function called constrain() that will “clip” numbers into a range. If the number is outside the range, it will make it the largest or smallest number. If it is within the range, it will stay the same. See Arduino’s constrain reference page for more info.

Copy and paste the following code into the Arduino IDE. Hit upload and see what happens!

language:cpp
/*
SparkFun Inventor's Kit Galileo
Example sketch 06

PHOTO RESISTOR

  Use a photoresistor (light sensor) to control the brightness
  of a LED.

Hardware connections:

  Photo resistor:

    Connect one side of the photoresistor to 5 Volts (5V).
    Connect the other side of the photoresistor to ANALOG pin 0.
    Connect a 10K resistor between ANALOG pin 0 and GND.

    This creates a voltage divider, with the photoresistor one
    of the two resistors. The output of the voltage divider
    (connected to A0) will vary with the light level.

  LED:

    Connect the positive side (long leg) of the LED to
    digital pin 9. (To vary the brightness, this pin must
    support PWM, which is indicated by "~" or "PWM" on the
    Arduino itself.)

    Connect the negative side of the LED (short leg) to a
    330 Ohm resistor.

    Connect the other side of the resistor to GND.

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/


// As usual, we'll create constants to name the pins we're using.
// This will make it easier to follow the code below.

const int sensorPin = 0;
const int ledPin = 9;

// We'll also set up some global variables for the light level:

int lightLevel, high = 0, low = 1023;


void setup()
{
  // We'll set up the LED pin to be an output.
  // (We don't need to do anything special to use the analog input.)

  pinMode(ledPin, OUTPUT);
}


void loop()
{
  // Just as we've done in the past, we'll use the analogRead()
  // function to measure the voltage coming from the photoresistor
  // resistor pair. This number can range between 0 (0 Volts) and
  // 1023 (5 Volts), but this circuit will have a smaller range
  // between dark and light.

  lightLevel = analogRead(sensorPin);

  // We now want to use this number to control the brightness of
  // the LED. But we have a problem: the analogRead() function
  // returns values between 0 and 1023, and the analogWrite()
  // function wants values from 0 to 255.

  // We can solve this by using two handy functions called map()
  // and constrain(). Map will change one range of values into
  // another range. If we tell map() our "from" range is 0-1023,
  // and our "to" range is 0-255, map() will squeeze the larger
  // range into the smaller. (It can do this for any two ranges.)

  // lightLevel = map(lightLevel, 0, 1023, 0, 255);

  // Because map() could still return numbers outside the "to"
  // range, (if they're outside the "from" range), we'll also use
  // a function called constrain() that will "clip" numbers into
  // a given range. If the number is above the range, it will reset
  // it to be the highest number in the range. If the number is
  // below the range, it will reset it to the lowest number.
  // If the number is within the range, it will stay the same.

  // lightLevel = constrain(lightLevel, 0, 255);

  // Here's one last thing to think about. The circuit we made
  // won't have a range all the way from 0 to 5 Volts. It will
  // be a smaller range, such as 300 (dark) to 800 (light).
  // If we just pass this number directly to map(), the LED will
  // change brightness, but it will never be completely off or
  // completely on.

  // You can fix this two ways, each of which we'll show
  // in the functions below. Uncomment ONE of them to
  // try it out:

  manualTune();  // manually change the range from light to dark

  //autoTune();  // have the Arduino do the work for us!

  // The above functions will alter lightLevel to be cover the
  // range from full-on to full-off. Now we can adjust the
  // brightness of the LED:

  analogWrite(ledPin, lightLevel);

  // The above statement will brighten the LED along with the
  // light level. To do the opposite, replace "lightLevel" in the
  // above analogWrite() statement with "255-lightLevel".
  // Now you've created a night-light!
}


void manualTune()
{
  // As we mentioned above, the light-sensing circuit we built
  // won't have a range all the way from 0 to 1023. It will likely
  // be more like 300 (dark) to 800 (light). If you run this sketch
  // as-is, the LED won't fully turn off, even in the dark.

  // You can accommodate the reduced range by manually
  // tweaking the "from" range numbers in the map() function.
  // Here we're using the full range of 0 to 1023.
  // Try manually changing this to a smaller range (300 to 800
  // is a good guess), and try it out again. If the LED doesn't
  // go completely out, make the low number larger. If the LED
  // is always too bright, make the high number smaller.

  // Remember you're JUST changing the 0, 1023 in the line below!

  lightLevel = map(lightLevel, 0, 1023, 0, 255);
  lightLevel = constrain(lightLevel, 0, 255);

  // Now we'll return to the main loop(), and send lightLevel
  // to the LED.
}


void autoTune()
{
  // As we mentioned above, the light-sensing circuit we built
  // won't have a range all the way from 0 to 1023. It will likely
  // be more like 300 (dark) to 800 (light).

  // In the manualTune() function above, you need to repeatedly
  // change the values and try the program again until it works.
  // But why should you have to do that work? You've got a
  // computer in your hands that can figure things out for itself!

  // In this function, the Arduino will keep track of the highest
  // and lowest values that we're reading from analogRead().

  // If you look at the top of the sketch, you'll see that we've
  // initialized "low" to be 1023. We'll save anything we read
  // that's lower than that:

  if (lightLevel < low)
  {
    low = lightLevel;
  }

  // We also initialized "high" to be 0. We'll save anything
  // we read that's higher than that:

  if (lightLevel > high)
  {
    high = lightLevel;
  }

  // Once we have the highest and lowest values, we can stick them
  // directly into the map() function. No manual tweaking needed!

  // One trick we'll do is to add a small offset to low and high,
  // to ensure that the LED is fully-off and fully-on at the limits
  // (otherwise it might flicker a little bit).

  lightLevel = map(lightLevel, low+30, high-30, 0, 255);
  lightLevel = constrain(lightLevel, 0, 255);

  // Now we'll return to the main loop(), and send lightLevel
  // to the LED.
}

What You Should See

You should see the LED grow brighter or dimmer in accordance with how much light your photoresistor is reading. If it isn’t working, make sure you have assembled the circuit correctly and verified and uploaded the code to your board or see the troubleshooting section.

Galileo Photoresistor

Real World Application

Some street lamps as well as solar walkway lights use photoresistors to detect the absence of the sun and turn on the lights.

Troubleshooting

LED Remains Dark

This is a mistake we continue to make time and time again, if only they could make an LED that worked both ways. Pull it up and give it a twist.

It Isn’t Responding to Changes in Light

Given that the spacing of the wires on the photoresistor is not standard, it is easy to misplace it. Double check it’s in the right place.

Still Not Quite Working

You may be in a room which is either too bright or dark. Try turning the lights on or off to see if this helps. Or if you have a flashlight near by give that a try.

SIK Galileo - Part 7: Reading a Temperature Sensor

Introduction

A temperature sensor is exactly what it sounds like – a sensor used to measure ambient temperature. This particular sensor has three pins – a positive, a ground, and a signal. This is a linear temperature sensor. A change in temperature of one degree centigrade is equal to a change of 10 millivolts at the sensor output.

The TMP36 sensor has a nominal 750 mV at 25°C (about room temperature). In this circuit, you’ll learn how to integrate the temperature sensor with your Galileo, and use the Arduino IDE’s serial monitor to display the temperature.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x Galileo
  • 5x Jumper Wires
  • 1x Temperature Sensor

If you are following through all of the SIK Galileo tutorials we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

Out of stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

Out of stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Temperature Sensor - TMP36

Temperature Sensor - TMP36

In stock SEN-10988

This is the same temperature sensor that is included in our [SparkFun Inventor's Kit](http://www.sparkfun.com/products/10173)…

1.5
Intel® Galileo

Intel® Galileo

In stock DEV-12720

The Intel® Galileo board is based on the Intel® Quark SoC X1000, a 32-bit Intel Pentium®-class system on a chip (SoC). It …

79.95

View the SparkFun Inventor’s Kit for Galileo wishlist, to see the parts needed to go through the all the experiments.

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Please note: The temperature sensor can only be connected to a circuit in one direction. See below for the pin outs of the temperature sensor - TMP36

Temperature Sensor<-

Fritzing Diagram

Fritzing

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Code To Note

Serial.begin(9600);

Before using the serial monitor, you must call Serial.begin() to initialize it. 9600 is the “baud rate”, or communications speed. When two devices are communicating with each other, both must be set to the same speed.

Serial.print(degreesC);

The Serial.print() command is very smart. It can print out almost anything you can throw at it, including variables of all types, quoted text (AKA “strings”), etc. See http://arduino.cc/en/serial/print for more info.

Serial.println(degreesF);

Serial.print() will print everything on the same line.

Serial.println() will move to the next line. By using both of these commands together, you can create easy-to-read printouts of text and data.

Copy and paste the following code into the Arduino IDE. Hit upload and see what happens!

language:cpp
/*
SparkFun Inventor's Kit Galileo
Example sketch 07

TEMPERATURE SENSOR

  Use the "serial monitor" window to read a temperature sensor.

  The TMP36 is an easy-to-use temperature sensor that outputs
  a voltage that's proportional to the ambient temperature.
  You can use it for all kinds of automation tasks where you'd
  like to know or control the temperature of something.

  More information on the sensor is available in the datasheet:
  http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Sensors/Temp/TMP35_36_37.pdf

  Even more exciting, we'll start using the Arduino's serial port
  to send data back to your main computer! Up until now, we've
  been limited to using simple LEDs for output. We'll see that
  the Arduino can also easily output all kinds of text and data.

Hardware connections:

  Be careful when installing the temperature sensor, as it is
  almost identical to the transistors! The one you want has
  a triangle logo and "TMP" in very tiny letters. The
  ones you DON'T want will have "222" on them.

  When looking at the flat side of the temperature sensor
  with the pins down, from left to right the pins are:
  5V, SIGNAL, and GND.

  Connect the 5V pin to 5 Volts (5V).
  Connect the SIGNAL pin to ANALOG pin 0.
  Connect the GND pin to ground (GND).

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/

// We'll use analog input 0 to measure the temperature sensor's
// signal pin.

const int temperaturePin = 0;


void setup()
{
  // In this sketch, we'll use the Arduino's serial port
  // to send text back to the main computer. For both sides to
  // communicate properly, they need to be set to the same speed.
  // We use the Serial.begin() function to initialize the port
  // and set the communications speed.

  // The speed is measured in bits per second, also known as
  // "baud rate". 9600 is a very commonly used baud rate,
  // and will transfer about 10 characters per second.

  Serial.begin(9600);
}


void loop()
{
  // Up to now we've only used integer ("int") values in our
  // sketches. Integers are always whole numbers (0, 1, 23, etc.).
  // In this sketch, we'll use floating-point values ("float").
  // Floats can be fractional numbers such as 1.42, 2523.43121, etc.

  // We'll declare three floating-point variables
  // (We can declare multiple variables of the same type on one line:)

  float voltage, degreesC, degreesF;

  // First we'll measure the voltage at the analog pin. Normally
  // we'd use analogRead(), which returns a number from 0 to 1023.
  // Here we've written a function (further down) called
  // getVoltage() that returns the true voltage (0 to 5 Volts)
  // present on an analog input pin.

  voltage = getVoltage(temperaturePin);

  // Now we'll convert the voltage to degrees Celsius.
  // This formula comes from the temperature sensor datasheet:

  degreesC = (voltage - 0.5) * 100.0;

  // While we're at it, let's convert degrees Celsius to Fahrenheit.
  // This is the classic C to F conversion formula:

  degreesF = degreesC * (9.0/5.0) + 32.0;

  // Now we'll use the serial port to print these values
  // to the serial monitor!

  // To open the serial monitor window, upload your code,
  // then click the "magnifying glass" button at the right edge
  // of the Arduino IDE toolbar. The serial monitor window
  // will open.

  // (NOTE: remember we said that the communication speed
  // must be the same on both sides. Ensure that the baud rate
  // control at the bottom of the window is set to 9600. If it
  // isn't, change it to 9600.)

  // Also note that every time you upload a new sketch to the
  // Arduino, the serial monitor window will close. It does this
  // because the serial port is also used to upload code!
  // When the upload is complete, you can re-open the serial
  // monitor window.

  // To send data from the Arduino to the serial monitor window,
  // we use the Serial.print() function. You can print variables
  // or text (within quotes).

  Serial.print("voltage: ");
  Serial.print(voltage);
  Serial.print("  deg C: ");
  Serial.print(degreesC);
  Serial.print("  deg F: ");
  Serial.println(degreesF);

  // These statements will print lines of data like this:
  // "voltage: 0.73 deg C: 22.75 deg F: 72.96"

  // Note that all of the above statements are "print", except
  // for the last one, which is "println". "Print" will output
  // text to the SAME LINE, similar to building a sentence
  // out of words. "Println" will insert a "carriage return"
  // character at the end of whatever it prints, moving down
  // to the NEXT line.

  delay(1000); // repeat once per second (change as you wish!)
}


float getVoltage(int pin)
{
  // This function has one input parameter, the analog pin number
  // to read. You might notice that this function does not have
  // "void" in front of it; this is because it returns a floating-
  // point value, which is the true voltage on that pin (0 to 5V).

  // You can write your own functions that take in parameters
  // and return values. Here's how:

    // To take in parameters, put their type and name in the
    // parenthesis after the function name (see above). You can
    // have multiple parameters, separated with commas.

    // To return a value, put the type BEFORE the function name
    // (see "float", above), and use a return() statement in your code
    // to actually return the value (see below).

    // If you don't need to get any parameters, you can just put
    // "()" after the function name.

    // If you don't need to return a value, just write "void" before
    // the function name.

  // Here's the return statement for this function. We're doing
  // all the math we need to do within this statement:

  return (analogRead(pin) * 0.004882814);

  // This equation converts the 0 to 1023 value that analogRead()
  // returns, into a 0.0 to 5.0 value that is the true voltage
  // being read at that pin.
}

// Other things to try with this code:

//   Turn on an LED if the temperature is above or below a value.

//   Read that threshold value from a potentiometer - now you've
//   created a thermostat!

What You Should See

You should be able to read the temperature your temperature sensor is detecting on the serial monitor in the Arduino IDE. If it isn’t working, make sure you have assembled the circuit correctly and verified and uploaded the code to your board or see the troubleshooting section.

Galileo Temperature Sensor

Example of what you should see in the Arduino IDE’s serial monitor:

voltage: 0.73 deg C: 23.24 deg F: 73.84

voltage: 0.73 deg C: 23.24 deg F: 73.84

voltage: 0.73 deg C: 22.75 deg F: 72.96

voltage: 0.73 deg C: 23.24 deg F: 73.84

voltage: 0.73 deg C: 23.24 deg F: 73.84

voltage: 0.73 deg C: 23.24 deg F: 73.84

voltage: 0.73 deg C: 22.75 deg F: 72.96

voltage: 0.73 deg C: 23.24 deg F: 73.84

voltage: 0.73 deg C: 22.75 deg F: 72.96

voltage: 0.73 deg C: 22.75 deg F: 72.96

voltage: 0.73 deg C: 23.24 deg F: 73.84

voltage: 0.73 deg C: 22.75 deg F: 72.96

voltage: 0.73 deg C: 23.24 deg F: 73.84

Real World Application

Building climate control systems use a temperature sensor to monitor and maintain their settings.

Troubleshooting

Nothing Seems to Happen

This program has no outward indication it is working. To see the results you must open the Arduino IDE’s serial monitor (instructions on previous page).

Gibberish is Displayed

This happens because the serial monitor is receiving data at a different speed than expected. To fix this, click the pull-down box that reads “*** baud” and change it to “9600 baud”.

Temperature Value is Unchanging

Try pinching the sensor with your fingers to heat it up or pressing a bag of ice against it to cool it down.

SIK Galileo - Part 8: Driving a Servo Motor

Introduction

Servos are ideal for embedded electronics applications because they do one thing very well that motors cannot – they can move to a position accurately. By varying the pulse width of the output voltage to a servo, you can move a servo to a specific position. For example, a pulse of 1.5 milliseconds will move the servo 90 degrees. In this circuit, you’ll learn how to use PWM (pulse width modulation) to control and rotate a servo.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x Galileo
  • 1x Servo
  • 8x Jumper Wires

If you are following through all of the SIK Galileo tutorials we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

Out of stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Servo - Generic (Sub-Micro Size)

Servo - Generic (Sub-Micro Size)

In stock ROB-09065

Here is a simple, low-cost, high quality servo for all your mechatronic needs. This servo is very similar in size and specifi…

8.95
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

Out of stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Intel® Galileo

Intel® Galileo

In stock DEV-12720

The Intel® Galileo board is based on the Intel® Quark SoC X1000, a 32-bit Intel Pentium®-class system on a chip (SoC). It …

79.95

View the SparkFun Inventor’s Kit for Galileo wishlist, to see the parts needed to go through the all the experiments.

Suggested Reading

Before continuing on with this experiment, we recommend you be familiar with the concepts in the following tutorial:

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Connect 3x jumper wires to the female 3 pin header on the servo. This will make it easier to breadboard the servo.

Servo Jumpers

Fritzing Diagram

Fritzing Motors

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image. Please kept in mind your servo will have a white wire instead of yellow.

Code To Note

#include <Servo.h>

#include is a special “preprocessor” command that inserts a library (or any other file) into your sketch. You can type this command yourself, or choose an installed library from the “sketch / import library” menu.

Servo servo1;

servo1.attach(9);

The servo library adds new commands that let you control a servo. To prepare the Galileo to control a servo, you must first create a Servo “object” for each servo (here we’ve named it “servo1”), and then “attach” it to a digital pin (here we’re using pin 9).

servo1.write(180);

The servos in this kit don’t spin all the way around, but they can be commanded to move to a specific position. We use the servo library’s write() command to move a servo to a specified number of degrees(0 to 180). Remember that the servo requires time to move, so give it a short delay() if necessary.

Copy and paste the following code into the Arduino IDE. Hit upload and see what happens!

language:cpp
/*
SparkFun Inventor's Kit Galileo
Example sketch 08

SINGLE SERVO

  Sweep a servo back and forth through its full range of motion.

  A "servo", short for servomotor, is a motor that includes
  feedback circuitry that allows it to be commanded to move to
  specific positions. This one is very small, but larger servos
  are used extensively in robotics to control mechanical arms,
  hands, etc. You could use it to make a (tiny) robot arm,
  aircraft control surface, or anywhere something needs to be
  moved to specific positions.

Hardware connections:

  The servo has a cable attached to it with three wires.
  Because the cable ends in a socket, you can use jumper wires
  to connect between the Arduino and the servo. Just plug the
  jumper wires directly into the socket.

  Connect the RED wire (power) to 5 Volts (5V)
  Connect the WHITE wire (signal) to digital pin 9
  Connect the BLACK wire (ground) to ground (GND)

  Note that servos can use a lot of power, which can cause your
  Arduino to reset or behave erratically. If you're using large
  servos or many of them, it's best to provide them with their
  own separate 5V supply. See this Arduino Forum thread for info:
  http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1239464763

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/


// If we had to write a sketch to control a servo from scratch,
// it would be a lot of work. Fortunately, others have done the
// hard work for you. We're going to include a "library"
// that has the functions needed to drive servos.

// A library is an set of additional functions you can add to
// your sketch. Numerous libraries are available for many uses,
// see http://arduino.cc/en/Reference/Libraries for information
// on the standard libraries, and Google for others. When you're
// using a new part, chances are someone has written a library
// for it.

#include <Servo.h>  // servo library

// Once you "include" a library, you'll have access to those
// functions. You can find a list of the functions in the servo
// library at: http://arduino.cc/en/Reference/Servo
// Most libraries also have example sketches you can load from
// the "file/examples" menu.

// Now we'll create a servo "object", called myservo. You should
// create one of these for each servo you want to control.
// You can control a maximum of twelve servos on the Uno
// using this library. (Other servo libraries may let you
// control more). Note that this library disables PWM on
// pins 9 and 10!

Servo servo1;  // servo control object


void setup()
{
  // We'll now "attach" the servo1 object to digital pin 9.
  // If you want to control more than one servo, attach more
  // servo objects to the desired pins (must be digital).

  // Attach tells the Arduino to begin sending control signals
  // to the servo. Servos require a continuous stream of control
  // signals, even if you're not currently moving them.
  // While the servo is being controlled, it will hold its
  // current position with some force. If you ever want to
  // release the servo (allowing it to be turned by hand),
  // you can call servo1.detach().

  servo1.attach(9);
}


void loop()
{
  int position;

  // To control a servo, you give it the angle you'd like it
  // to turn to. Servos cannot turn a full 360 degrees, but you
  // can tell it to move anywhere between 0 and 180 degrees.

  // Change position at full speed:

  servo1.write(90);    // Tell servo to go to 90 degrees

  delay(1000);         // Pause to get it time to move

  servo1.write(180);   // Tell servo to go to 180 degrees

  delay(1000);         // Pause to get it time to move

  servo1.write(0);     // Tell servo to go to 0 degrees

  delay(1000);         // Pause to get it time to move

  // Change position at a slower speed:

  // To slow down the servo's motion, we'll use a for() loop
  // to give it a bunch of intermediate positions, with 20ms
  // delays between them. You can change the step size to make
  // the servo slow down or speed up. Note that the servo can't
  // move faster than its full speed, and you won't be able
  // to update it any faster than every 20ms.

  // Tell servo to go to 180 degrees, stepping by two degrees

  for(position = 0; position < 180; position += 2)
  {
    servo1.write(position);  // Move to next position
    delay(20);               // Short pause to allow it to move
  }

  // Tell servo to go to 0 degrees, stepping by one degree

  for(position = 180; position >= 0; position -= 1)
  {
    servo1.write(position);  // Move to next position
    delay(20);               // Short pause to allow it to move
  }
}

What You Should See

You should see your servo motor move to various locations at several speeds. If the motor doesn’t move, check your connections and make sure you have verified and uploaded the code, or see the troubleshooting section.

Galileo Servo Motor

Real World Application

Robotic arms you might see in an assembly line or sci-fi movie probably have servos in them.

Troubleshooting

Servo Not Twisting

Even with colored wires it is still shockingly easy to plug a servo in backward. This might be the case.

Still Not Working

A mistake we made a time or two was simply forgetting to connect the power (red and brown wires) to +5 volts and ground.

Fits and Starts

If the servo begins moving then twitches, and there’s a flashing light on your Galileo, the power supply you are using is not quite up to the challenge. Using a wall adapter instead of USB should solve this problem.

SIK Galileo - Part 9: Using a Flex Sensor

Introduction

In this circuit, we will use a flex sensor to measure, well, flex! A flex sensor uses carbon on a strip of plastic to act like a variable resistor, but instead of changing the resistance by turning a knob, you change it by flexing (bending) the component. We use a “voltage divider” again to detect this change in resistance.

The sensor bends in one direction and the more it bends, the higher the resistance gets; it has a range from about 10K ohm to 35K ohm. In this circuit we will use the amount of bend of the flex sensor to control the position of a servo.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x Galileo
  • 1x Flex Sensor
  • 1x Servo
  • 1x 10k resistor
  • 11x Jumper Wires

If you are following through all of the SIK Galileo tutorials we suggest getting using parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

Out of stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Flex Sensor 2.2"

Flex Sensor 2.2"

Out of stock SEN-10264

A simple flex sensor 2.2" in length. As the sensor is flexed, the resistance across the sensor increases. Patented technology…

7.95
Servo - Generic (Sub-Micro Size)

Servo - Generic (Sub-Micro Size)

In stock ROB-09065

Here is a simple, low-cost, high quality servo for all your mechatronic needs. This servo is very similar in size and specifi…

8.95
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

Out of stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Resistor 10K Ohm 1/6th Watt PTH - 20 pack

Resistor 10K Ohm 1/6th Watt PTH - 20 pack

In stock COM-11508

1/6th Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 10K resistors make excellent …

0.95
Intel® Galileo

Intel® Galileo

In stock DEV-12720

The Intel® Galileo board is based on the Intel® Quark SoC X1000, a 32-bit Intel Pentium®-class system on a chip (SoC). It …

79.95

View the SparkFun Inventor’s Kit for Galileo wishlist, to see the parts needed to go through the all the experiments.

Suggested Reading

Before continuing on with this experiment, we recommend you be familiar with the concepts in the following tutorial:

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Connect 3x jumper wires to the female 3 pin header on the servo. This will make it easier to breadboard the servo.

Fritzing

Fritzing Flex Sensor

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image. Please kept in mind your servo will have a white wire instead of yellow.

Code To Note

servoposition = map(flexposition, 600, 900, 0, 180);

map(value, fromLow, fromHigh, toLow, toHigh)

Because the flex sensor / resistor combination won’t give us a full 0 to 5 volt range, we’re using the map() function as a handy way to reduce that range. Here we’ve told it to only expect values from 600 to 900, rather than 0 to 1023.

servoposition = constrain(servoposition, 0, 180);

constrain(x, a, b)

Because map() could still return numbers outside the “to” range, we’ll also use a function called constrain() that will “clip” numbers into a range. If the number is outside the range, it will make it the largest or smallest number. If it is within the range, it will stay the same.

Copy and paste the following code into the Arduino IDE. Hit upload and see what happens!

language:cpp
/*
SparkFun Inventor's Kit Galileo
Example sketch 09

FLEX SENSOR

  Use the "flex sensor" to change the position of a servo

  In the previous sketch, we learned how to command a servo to
  mode to different positions. In this sketch, we'll introduce
  a new sensor, and use it to control the servo.

  A flex sensor is a plastic strip with a conductive coating.
  When the strip is straight, the coating will be a certain
  resistance. When the strip is bent, the particles in the coating
  get further apart, increasing the resistance. You can use this
  sensor to sense finger movement in gloves, door hinges, stuffed
  animals, etc. See http://www.sparkfun.com/tutorials/270 for
  more information.

Hardware connections:

  Flex sensor:

    The flex sensor is the plastic strip with black stripes.
    It senses bending away from the striped side.

    The flex sensor has two pins, and since it's a resistor,
    the pins are interchangable.

    Connect one of the pins to ANALOG IN pin 0 on the Arduino.
    Connect the same pin, through a 10K Ohm resistor (brown
    black orange) to GND.
    Connect the other pin to 5V.

  Servo:

    The servo has a cable attached to it with three wires.
    Because the cable ends in a socket, you can use jumper wires
    to connect between the Arduino and the servo. Just plug the
    jumper wires directly into the socket.

    Connect the RED wire (power) to 5 Volts (5V)
    Connect the WHITE wire (signal) to digital pin 9
    Connect the BLACK wire (ground) to ground (GND)

    Note that servos can use a lot of power, which can cause your
    Arduino to reset or behave erratically. If you're using large
    servos or many of them, it's best to provide them with their
    own separate 5V supply. See this Arduino Forum thread for info:
    http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1239464763

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/


// Include the servo library to add servo-control functions:

#include <Servo.h>

// Create a servo "object", called servo1. Each servo object
// controls one servo (you can have a maximum of 12):

Servo servo1;

// Define the analog input pin to measure flex sensor position:

const int flexpin = 0;


void setup()
{
  // Use the serial monitor window to help debug our sketch:

  Serial.begin(9600);

  // Enable control of a servo on pin 9:

  servo1.attach(9);
}


void loop()
{
  int flexposition;    // Input value from the analog pin.
  int servoposition;   // Output value to the servo.

  // Read the position of the flex sensor (0 to 1023):

  flexposition = analogRead(flexpin);

  // Because the voltage divider circuit only returns a portion
  // of the 0-1023 range of analogRead(), we'll map() that range
  // to the servo's range of 0 to 180 degrees. The flex sensors
  // we use are usually in the 600-900 range:

  servoposition = map(flexposition, 600, 900, 0, 180);
  servoposition = constrain(servoposition, 0, 180);

  // Now we'll command the servo to move to that position:

  servo1.write(servoposition);

  // Because every flex sensor has a slightly different resistance,
  // the 600-900 range may not exactly cover the flex sensor's
  // output. To help tune our program, we'll use the serial port to
  // print out our values to the serial monitor window:

  Serial.print("sensor: ");
  Serial.print(flexposition);
  Serial.print("  servo: ");
  Serial.println(servoposition);

  // Note that all of the above lines are "print" except for the
  // last line which is "println". This puts everything on the
  // same line, then sends a final carriage return to move to
  // the next line.

  // After you upload the sketch, turn on the serial monitor
  // (the magnifying-glass icon to the right of the icon bar).
  // You'll be able to see the sensor values. Bend the flex sensor
  // and note its minimum and maximum values. If you replace the
  // 600 and 900 in the map() function above, you'll exactly match
  // the flex sensor's range with the servo's range.

  delay(20);  // wait 20ms between servo updates
}

What You Should See

You should see the servo motor move in accordance with how much you are flexing the flex sensor. If it isn’t working, make sure you have assembled the circuit correctly and verified and uploaded the code to your board or see the troubleshooting section.

Galileo Flex Sensor

Real World Application

Controller accessories for video game consoles like Nintendo’s “Power Glove” use flex-sensing technology. It was the first video game controller attempting to mimic hand movement on a screen in real time.

Troublshooting

Servo Not Twisting

Even with colored wires it is still shockingly easy to plug a servo in backwards. This might be the case.

Servo Not Moving as Expected

The sensor is only designed to work in one direction. Try flexing it the other way (where the striped side faces out on a convex curve).

Servo Doesn’t Move very Far

You need to modify the range of values in the call to the map() function.

SIK Galileo - Part 10: Reading a Soft Potentiometer

Introduction

In this circuit, we are going to use yet another kind of variable resistor – this time, a soft potentiometer (or soft pot). This is a thin and flexible strip that can detect where pressure is being applied. By pressing down on various parts of the strip, you can vary the resistance from 100 to 10k ohms. You can use this ability to track movement on the soft pot, or simply as a button. In this circuit, we’ll get the soft pot up and running to control an RGB LED.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x Galileo
  • 1x Soft Potentiometer
  • 1x 10k resistor
  • 3x 330Ω resistors
  • 1x RGB LED
  • 9x Jumper Wires

If you are following through all of the SIK Galileo tutorials we suggest getting using parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

Out of stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
LED - RGB Clear Common Cathode

LED - RGB Clear Common Cathode

In stock COM-00105

Ever hear of a thing called RGB? Red, Green, Blue? How about an RGB LED? These 5mm units have four pins - Cathode is the long…

1.95
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

Out of stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

1/6 Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 330Ohm resistors make excellent…

0.95
Resistor 10K Ohm 1/6th Watt PTH - 20 pack

Resistor 10K Ohm 1/6th Watt PTH - 20 pack

In stock COM-11508

1/6th Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 10K resistors make excellent …

0.95
SoftPot Membrane Potentiometer - 50mm

SoftPot Membrane Potentiometer - 50mm

In stock SEN-08680

These are very thin variable potentiometers. By pressing down on various parts of the strip, the resistance linearly changes …

4.95
Intel® Galileo

Intel® Galileo

In stock DEV-12720

The Intel® Galileo board is based on the Intel® Quark SoC X1000, a 32-bit Intel Pentium®-class system on a chip (SoC). It …

79.95

View the SparkFun Inventor’s Kit for Galileo wishlist, to see the parts needed to go through the all the experiments.

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram

Fritzing Soft pot

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Code To Note

language:cpp
redValue = constrain(map(RGBposition, 0, 341, 255, 0), 0, 255)
 + constrain(map(RGBposition, 682, 1023, 0, 255), 0, 255);


greenValue = constrain(map(RGBposition, 0, 341, 0, 255), 0, 255)
 - constrain(map(RGBposition, 341, 682, 0,255), 0, 255);


blueValue = constrain(map(RGBposition, 341, 682, 0, 255), 0, 255)
- constrain(map(RGBposition, 682, 1023, 0, 255), 0, 255);

These big, scary functions take a single Value (RGBposition) and calculate the three RGB values necessary to create a rainbow of color. The functions create three “peaks” for the red, green, and blue values, which overlap to mix and create new colors. See the code for more information! Even if you’re not 100% clear how it works, you can copy and paste this (or any) function into your own code and use it yourself.

Copy and paste the following code into the Arduino IDE. Hit upload and see what happens!

language:cpp
/*
SparkFun Inventor's Kit Galileo
Example sketch 10

SOFT POTENTIOMETER

  Use the soft potentiometer to change the color
  of the RGB LED

  The soft potentiometer is a neat input device that detects
  pressure along its length. When you press it down with a finger
  (it works best on a flat surface), it will change resistance
  depending on where you're pressing it. You might use it to make
  a piano or light dimmer; here we're going to use it to control
  the color of an RGB LED.

Hardware connections:

  Soft potentiometer:

    The soft potentiometer is the large plastic strip with three
    pins. We'll be connecting it as a voltage divider, just like
    we did with the knob-type potentiometer back in circuit #2.

    Connect the middle pin to ANALOG IN pin 0 on the Arduino.
    Connect one side to 5V.
    Connect the other side to GND.
    Also connect a 10K resistor from the middle pin to GND.

    TIP: the soft pot will only work while you're actively
    pressing on it; at other times it will "float" to random
    values. To prevent this, we've added a 10K pull-down resistor
    to the middle pin (output voltage). This will keep the output
    at zero volts when the pot is not being pressed.

  RGB LED:

    An RGB LED is actually three LEDs (red, green, and blue)
    in one package. When we run them at different brightnesses,
    they mix to form new colors.

    Starting at the flattened edge of the flange on the LED,
    the pins are ordered RED, COMMON, GREEN, BLUE.

    Connect RED to a 330 Ohm resistor.
    Connect the other end of the resistor to Arduino digital pin 9.

    Connect COMMON to GND.

    Connect GREEN through a 330 Ohm resistor.
    Connect the other end of the resistor to Arduino digital pin 10.

    Connect BLUE through a 330 Ohm resistor.
    Connect the other end of the resistor to Arduino digital pin 11.

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/


// Constants for LED connections (note that these must be
// PWM pins, which are marked with "PWM" or have a "~" symbol
// next to them on the board).

const int RED_LED_PIN = 9;    // Red LED Pin
const int GREEN_LED_PIN = 10; // Green LED Pin
const int BLUE_LED_PIN = 11;  // Blue LED Pin

const int SENSOR_PIN = 0;      // Analog input pin

// Global PWM brightness values for the RGB LED.
// These are global so both loop() and setRGB() can see them.

int redValue, greenValue, blueValue;


void setup()
{
  // No need for any code here
  // analogWrite() sets up the pins as outputs
}


void loop()
{
  int sensorValue;

  // Read the voltage from the softpot (0-1023)

  sensorValue = analogRead(0);

  // We've written a new function called setRGB() (further down
  // in the sketch) that decodes sensorValue into a position
  // on the RGB "rainbow", and sets the RGB LED to that color.

  setRGB(sensorValue);
}


// setRGB()
// Set a RGB LED to a position on the "rainbow" of all colors.
// RGBposition should be in the range of 0 to 1023 (such as
// from an analog input).

void setRGB(int RGBposition)
{
  int mapRGB1, mapRGB2, constrained1, constrained2;

  // Here we take RGBposition and turn it into three RGB values.

  // The three values are computed so that the colors mix and
  // produce a rainbow of colors across the 0-1023 input range.

  // For each channel (red green blue), we're creating a "peak"
  // a third of the way along the 0-1023 range. By overlapping
  // these peaks with each other, the colors are mixed together.
  // This is most easily shown with a diagram:
  // http://sfecdn.s3.amazonaws.com/education/SIK/SchematicImages/Misc/RGB_function.jpg

  // Create the red peak, which is centered at 0.
  // (Because it's centered at 0, half is after 0, and half
  // is before 1023):

  mapRGB1 = map(RGBposition, 0, 341, 255, 0);
  constrained1 = constrain(mapRGB1, 0, 255);

  mapRGB2 = map(RGBposition, 682, 1023, 0, 255);
  constrained2 = constrain(mapRGB2, 0, 255);

  redValue = constrained1 + constrained2;

  // Create the green peak, which is centered at 341
  // (one-third of the way to 1023):

  // Note that we've nested the functions by putting the map()
  // function inside the constrain() function. This can make your
  // code more compact, and requires fewer variabls:

  greenValue = constrain(map(RGBposition, 0, 341, 0, 255), 0, 255)
             - constrain(map(RGBposition, 341, 682, 0,255), 0, 255);

  // Create the blue peak, which is centered at 682
  // (two-thirds of the way to 1023):

  blueValue = constrain(map(RGBposition, 341, 682, 0, 255), 0, 255)
            - constrain(map(RGBposition, 682, 1023, 0, 255), 0, 255);

  // Now we have all three brightnesses,
  // we just need to display the computed color:

  analogWrite(RED_LED_PIN, redValue);
  analogWrite(GREEN_LED_PIN, greenValue);
  analogWrite(BLUE_LED_PIN, blueValue);

  // Feel free to use this function in your own code!
}

What You Should See

You should see the RGB LED change colors in accordance with how you interact with the soft potentiometer. If it isn’t working, make sure you have assembled the circuit correctly and verified and uploaded the code to your board, or see the troubleshooting section.

Galileo Soft Pot

Real World Application

The knobs found on many objects, like a radio for instance, are using similar concepts to the one you just completed for this circuit.

Troubleshooting

LED Remains Dark or Shows Incorrect Color

With the four pins of the LED so close together, it’s sometimes easy to misplace one. Try double checking each pin is where it should be.

Bizarre Results

The most likely cause of this is if you’re pressing the potentiometer in more than one position. This is normal and can actually be used to create some neat results.

SIK Galileo - Part 11: Using a Piezo Buzzer

Introduction

In this circuit, we’ll again bridge the gap between the digital world and the analog world. We’ll be using a piezo buzzer that makes a small “click” when you apply voltage to it (try it!). By itself that isn’t terribly exciting, but if you turn the voltage on and off hundreds of times a second, the piezo buzzer will produce a tone. And if you string a bunch of tones together, you’ve got music! This circuit and sketch will play a classic tune. We’ll never let you down!

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x Galileo
  • 1x Piezo Buzzer
  • 3x Jumper Wires

If you are following through all of the SIK Galileo tutorials we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

Out of stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

Out of stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Piezo Speaker - PC Mount 12mm 2.048kHz

Piezo Speaker - PC Mount 12mm 2.048kHz

In stock COM-07950

This is a small 12mm round speaker that operates around the audible 2kHz range. You can use these speakers to create simple m…

1.95
Intel® Galileo

Intel® Galileo

In stock DEV-12720

The Intel® Galileo board is based on the Intel® Quark SoC X1000, a 32-bit Intel Pentium®-class system on a chip (SoC). It …

79.95

View the SparkFun Inventor’s Kit for Galileo wishlist, to see the parts needed to go through the all the experiments.

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram

Fritzing Buzzer

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Code To Note

char notes[] = "cdfda ag cdfdg gf ";

char names[] = {'c','d','e','f','g','a','b','C'};

Up until now we’ve been working solely with numerical data, but the Arduino can also work with text. Characters (single, printable, letters, numbers and other symbols) have their own type, called “char”. When you have an array of characters, it can be defined between double-quotes (also called a “string”), OR as a list of single-quoted characters.

tone(pin, frequency, duration);

One of Arduino’s many useful built-in commands is the tone() function. This function drives an output pin at a certain frequency, making it perfect for driving buzzers and speakers. If you give it a duration (in milliseconds), it will play the tone then stop. If you don’t give it a duration, it will keep playing the tone forever (but you can stop it with another function, noTone() ).

Copy and paste the following code into the Arduino IDE. Hit upload and see what happens!

/*
SparkFun Inventor's Kit Galileo
Example sketch 11

BUZZER

  Use the buzzer to play a song!

  The buzzer in your Inventor's Kit is an electromechanical
  component you can use to make noise. Inside the buzzer is a
  coil of wire and a small magnet. When current flows through
  the coil, it becomes magnetized and pulls towards the magnet,
  creating a tiny "click". When you do this thousands of times
  per second, you create tones.

  The Arduino has a built-in command called tone() which clicks
  the buzzer at a certain frequency. This sketch knows the
  frequencies of the common notes, allowing you to create songs.
  We're never going to let you down!

Hardware connections:

  The buzzer has two pins. One is positive and one is negative.
  The postitive pin is marked by a "+" symbol on both the top
  and bottom of the buzzer.

  Connect the positive pin to Arduino digital pin 9.
  (Note that this must be a PWM pin.)
  Connect the negative pin to GND.

  Tip: if the buzzer doesn't fit into the breadboard easily,
  try rotating it slightly to fit into diagonal holes.

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
(This sketch was originally developed by D. Cuartielles for K3)
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/

/*
This sketch uses the buzzer to play songs.
The Arduino's tone() command will play notes of a given frequency.
We'll provide a function that takes in note characters (a-g),
and returns the corresponding frequency from this table:

  note  frequency
  c     262 Hz
  d     294 Hz
  e     330 Hz
  f     349 Hz
  g     392 Hz
  a     440 Hz
  b     494 Hz
  C     523 Hz

For more information, see http://arduino.cc/en/Tutorial/Tone
*/

const int buzzerPin = 9;

// We'll set up an array with the notes we want to play
// change these values to make different songs!

// Length must equal the total number of notes and spaces

const int songLength = 18;

// Notes is an array of text characters corresponding to the notes
// in your song. A space represents a rest (no tone)

char notes[] = "cdfda ag cdfdg gf "; // a space represents a rest

// Beats is an array of values for each note and rest.
// A "1" represents a quarter-note, 2 a half-note, etc.
// Don't forget that the rests (spaces) need a length as well.

int beats[] = {1,1,1,1,1,1,4,4,2,1,1,1,1,1,1,4,4,2};

// The tempo is how fast to play the song.
// To make the song play faster, decrease this value.

int tempo = 150;


void setup()
{
  pinMode(buzzerPin, OUTPUT);
}


void loop()
{
  int i, duration;

  for (i = 0; i < songLength; i++) // step through the song arrays
  {
    duration = beats[i] * tempo;  // length of note/rest in ms

    if (notes[i] == ' ')          // is this a rest?
    {
      delay(duration);            // then pause for a moment
    }
    else                          // otherwise, play the note
    {
      tone(buzzerPin, frequency(notes[i]), duration);
      delay(duration);            // wait for tone to finish
    }
    delay(tempo/10);              // brief pause between notes
  }

  // We only want to play the song once, so we'll pause forever:
  while(true){}
  // If you'd like your song to play over and over,
  // remove the above statement
}


int frequency(char note)
{
  // This function takes a note character (a-g), and returns the
  // corresponding frequency in Hz for the tone() function.

  int i;
  const int numNotes = 8;  // number of notes we're storing

  // The following arrays hold the note characters and their
  // corresponding frequencies. The last "C" note is uppercase
  // to separate it from the first lowercase "c". If you want to
  // add more notes, you'll need to use unique characters.

  // For the "char" (character) type, we put single characters
  // in single quotes.

  char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
  int frequencies[] = {262, 294, 330, 349, 392, 440, 494, 523};

  // Now we'll search through the letters in the array, and if
  // we find it, we'll return the frequency for that note.

  for (i = 0; i < numNotes; i++)  // Step through the notes
  {
    if (names[i] == note)         // Is this the one?
    {
      return(frequencies[i]);     // Yes! Return the frequency
    }
  }
  return(0);  // We looked through everything and didn't find it,
              // but we still need to return a value, so return 0.
}

What You Should See

You should see - well, nothing! But you should be able to hear a song. If it isn’t working, make sure you have assembled the circuit correctly and verified and uploaded the code to your board or see the troubleshooting section.

Galileo Buzzer

Real World Application

Many modern megaphones have settings that use a loud amplified buzzer. They are usually very loud and quite good at getting people’s attention.

Troubleshooting

No Sound

Given the size and shape of the piezo buzzer it is easy to miss the right holes on the breadboard. Try double checking its placement.

Can’t Think While the Melody is Playing

Just pull up the piezo buzzer whilst you think, upload your program then plug it back in.

Feeling Let Down and Deserted

The code is written so you can easily add your own songs.

SIK Galileo - Part 12: Driving a Motor

Introduction

Back in Circuit 8, you got to work with a servo motor. Now, we are going to tackle spinning a motor. This requires the use of a transistor, which can switch a larger amount of current than the Galileo can.

When using a transistor, you just need to make sure its maximum specs are high enough for your use case. The transistor we are using for this circuit is rated at 40V max and 200 milliamps max – perfect for our toy motor! When the motor is spinning and suddenly turned off, the magnetic field inside it collapses, generating a voltage spike. This can damage the transistor. To prevent this, we use a “flyback diode”, which diverts the voltage spike around the transistor.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x Galileo
  • 1x Motor
  • 1x 330Ω Resistor
  • 1x NPN transistor
  • 1x Diode 1N4148
  • 6x Jumper Wires

If you are following through all of the SIK Galileo tutorials we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

Out of stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Transistor - NPN (P2N2222A)

Transistor - NPN (P2N2222A)

In stock COM-12852

This is the P2N2222A, an NPN silicon BJT (Bipolar Junction Transistor). This little transistor can help in your project by be…

0.5
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

Out of stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

1/6 Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 330Ohm resistors make excellent…

0.95
Diode Small Signal - 1N4148

Diode Small Signal - 1N4148

In stock COM-08588

This is a very common signal diode - 1N4148. Use this for signals up to 200mA of current. If you need a bunch of these, you…

0.15
Hobby Motor - Gear

Hobby Motor - Gear

In stock ROB-11696

This is our new Hobby Motor now with a 6mm, 10 tooth, gear to make your basic projects a little simpler to manage. It works w…

1.95
Intel® Galileo

Intel® Galileo

In stock DEV-12720

The Intel® Galileo board is based on the Intel® Quark SoC X1000, a 32-bit Intel Pentium®-class system on a chip (SoC). It …

79.95

View the SparkFun Inventor’s Kit for Galileo wishlist, to see the parts needed to go through the all the experiments.

Suggested Reading

Before continuing on with this experiment, we recommend you be familiar with the concepts in the following tutorial:

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Please note: When you’re building the circuit be careful not to mix up the transistor and the temperature sensor, they’re almost identical. Look for “P2N2222A” on the body of the transistor.

Fritzing Diagram

Fritzing Image

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Code To Note

while (Serial.available() > 0)

The Galileo’s serial port can be used to receive as well as send data. Because data could arrive at any time, the Galileostores, or “buffers” data coming into the port until you’re ready to use it. The Serial.available() command returns the number of characters that the port has received, but haven’t been used by your sketch yet. Zero means no data has arrived.

speed = Serial.parseInt();

If the port has data waiting for you, there are a number of ways for you to use it. Since we’re typing numbers into the port, we can use the handy Serial.parseInt() command to extract, or “parse” integer numbers from the characters it’s received. If you type “1” “0” “0” to the port, this function will return the number 100.

Copy and paste the following code into the Arduino IDE. Hit upload and see what happens!

language:cpp
/*
SparkFun Inventor's Kit Galileo
Example sketch 12

SPINNING A MOTOR

  Use a transistor to spin a motor at different speeds.
  We'll also show you how to input data from the serial port
  (see the serialSpeed() function below).

  Motors are the basis for thousands of things in our daily lives,
  and the Arduino can control them. Here we'll use pulse-width
  modulation (PWM) to vary the speed of a motor.

  The Arduino pins are strong enough to light small LEDs (up to
  40 milliAmps), but they're not strong enough to run motors and
  other power-hungry parts. (This motor needs 50-100mA).
  Because the motor needs more current than an Arduino pin can
  provide, we'll use a transistor to do the heavy lifting.
  A transistor is a solid-state switch. When we give it a small
  amount of current, it can switch a much larger current.
  The transistors in your kit (2N2222) can switch up to 200mA.

  You can turn a transistor on and off using the digitalWrite()
  function, but you can also use the analogWrite() function to
  vary the speed of the motor. The analogWrite() function pulses
  a pin, varying the width of the pulse from 0% to 100%. We call
  this technique "PWM", for "Pulse-Width Modulation".

  One thing to keep in mind is that when you lower the speed of
  a motor using PWM, you're also reducing the torque (strength)
  of the motor. For PWM values below 50 or so, the motor won't have
  enough torque to start spinning. It will start spinning when you
  raise the speed a bit.

Hardware connections:

  Transistor:

    The transistor has three pins. Looking at the flat side with the
    pins down, the order is COLLECTOR, BASE, EMITTER.

    Connect the black wire on the motor to the
    COLLECTOR pin on the transistor.

    Connect the BASE pin through a 330 Ohm resistor to
    digital pin 9.

    Connect the EMITTER pin to GND.

  Motor:

    You've already connected the black wire on the motor to the
    COLLECTOR pin on the transistor.

    Connect the other (red) wire on the motor to 5V.

  Flyback diode:

    When the motor is spinning and suddenly turned off, the
    magnetic field inside it collapses, generating a voltage spike.
    This can damage the transistor. To prevent this, we use a
    "flyback diode", which diverts the voltage spike "around" the
    transistor.

    Connect the side of the diode with the band (cathode) to 5V
    Connect the other side of the diode (anode) to the black wire
    on the motor.

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/

// We'll be controlling the motor from pin 9.
// This must be one of the PWM-capable pins.

const int motorPin = 9;


void setup()
{
  // Set up the motor pin to be an output:

  pinMode(motorPin, OUTPUT);

  // Set up the serial port:

  Serial.begin(9600);
}


void loop()
{
  // Here we've used comments to disable some of the examples.
  // To try different things, uncomment one of the following lines
  // and comment the other ones. See the functions below to learn
  // what they do and how they work.

  // motorOnThenOff();
  // motorOnThenOffWithSpeed();
  // motorAcceleration();
     serialSpeed();
}


// This function turns the motor on and off like the blinking LED.
// Try different values to affect the timing.

void motorOnThenOff()
{
  int onTime = 3000;  // milliseconds to turn the motor on
  int offTime = 3000; // milliseconds to turn the motor off

  digitalWrite(motorPin, HIGH); // turn the motor on (full speed)
  delay(onTime);                // delay for onTime milliseconds
  digitalWrite(motorPin, LOW);  // turn the motor off
  delay(offTime);               // delay for offTime milliseconds
}


// This function alternates between two speeds.
// Try different values to affect the timing and speed.

void motorOnThenOffWithSpeed()
{
  int Speed1 = 200;  // between 0 (stopped) and 255 (full speed)
  int Time1 = 3000;  // milliseconds for speed 1

  int Speed2 = 50;   // between 0 (stopped) and 255 (full speed)
  int Time2 = 3000;  // milliseconds to turn the motor off

  analogWrite(motorPin, Speed1);  // turns the motor On
  delay(Time1);                   // delay for onTime milliseconds
  analogWrite(motorPin, Speed2);  // turns the motor Off
  delay(Time2);                   // delay for offTime milliseconds
}


// This function slowly accelerates the motor to full speed,
// then back down to zero.

void motorAcceleration()
{
  int speed;
  int delayTime = 20; // milliseconds between each speed step

  // accelerate the motor

  for(speed = 0; speed <= 255; speed++)
  {
    analogWrite(motorPin,speed);    // set the new speed
    delay(delayTime);               // delay between speed steps
  }

  // decelerate the motor

  for(speed = 255; speed >= 0; speed--)
  {
    analogWrite(motorPin,speed);    // set the new speed
    delay(delayTime);               // delay between speed steps
  }
}


// This function will let you type a speed into the serial
// monitor window. Open the serial monitor using the magnifying-
// glass icon at the top right of the Arduino window. Then
// type your desired speed into the small text entry bar at the
// top of the window and click "Send" or press return. The motor
// will then operate at that speed. The valid range is 0 to 255.

void serialSpeed()
{
  int speed;

  Serial.println("Type a speed (0-255) into the box above,");
  Serial.println("then click [send] or press [return]");
  Serial.println();  // Print a blank line

  // In order to type out the above message only once,
  // we'll run the rest of this function in an infinite loop:

  while(true)  // "true" is always true, so this will loop forever.
  {
    // First we check to see if incoming data is available:

    while (Serial.available() > 0)
    {
      // If it is, we'll use parseInt() to pull out any numbers:

      speed = Serial.parseInt();

      // Because analogWrite() only works with numbers from
      // 0 to 255, we'll be sure the input is in that range:

      speed = constrain(speed, 0, 255);

      // We'll print out a message to let you know that the
      // number was received:

      Serial.print("Setting speed to ");
      Serial.println(speed);

      // And finally, we'll set the speed of the motor!

      analogWrite(motorPin, speed);
    }
  }
}

What You Should See

The DC Motor should spin if you have assembled the circuit’s components correctly, and also verified/uploaded the correct code. If your circuit is not working check the troubleshooting section.

Fritzing Motor

Real World Application

Radio Controlled (RC) cars use Direct Current (DC) motors to turn the wheels for propulsion.

Troubleshooting

Motor Not Spinning

If you sourced your own transistor, double check with the data sheet that the pinout is compatible with a P2N2222AG (many are reversed).

Still No Luck

If you sourced your own motor, double check that it will work with 5 volts and that it does not draw too much power.

Still Not Working

Sometimes the Galileo will disconnect from the computer. Try un-plugging and then re-plugging it into your USB port.

SIK Galileo - Part 13: Using Relays

Introduction

In this circuit, we are going to use some of the lessons we learned in Circuit 12 to control a relay. A relay is basically an electrically controlled mechanical switch. Inside that harmless looking plastic box is an electromagnet that, when it gets a jolt of energy, causes a switch to trip. In this circuit, you’ll learn how to control a relay like a pro – giving your Galileo even more powerful abilities!

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x Galileo
  • 2x LEDs
  • 2x 330Ω Resistors
  • 1x Relay (SPDT)
  • 1x Diode 1N4148
  • 1x NPN Transistor
  • 14x Jumper Wires

If you are following through all of the SIK Galileo tutorials we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

Out of stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Transistor - NPN (P2N2222A)

Transistor - NPN (P2N2222A)

In stock COM-12852

This is the P2N2222A, an NPN silicon BJT (Bipolar Junction Transistor). This little transistor can help in your project by be…

0.5
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

Out of stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

1/6 Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 330Ohm resistors make excellent…

0.95
LED - Assorted (20 pack)

LED - Assorted (20 pack)

In stock COM-12062

We all know that you can never get too many LEDs. Don't worry, we've got you covered. This is a pack of basic red, yellow, bl…

2.95
Diode Small Signal - 1N4148

Diode Small Signal - 1N4148

In stock COM-08588

This is a very common signal diode - 1N4148. Use this for signals up to 200mA of current. If you need a bunch of these, you…

0.15
Relay SPDT Sealed

Relay SPDT Sealed

In stock COM-00100

These are high quality Single Pole - Double Throw (SPDT) sealed relays. Use them to switch high voltage, and/or high current …

1.95
Intel® Galileo

Intel® Galileo

In stock DEV-12720

The Intel® Galileo board is based on the Intel® Quark SoC X1000, a 32-bit Intel Pentium®-class system on a chip (SoC). It …

79.95

View the SparkFun Inventor’s Kit for Galileo wishlist, to see the parts needed to go through the all the experiments.

Suggested Reading

Before continuing on with this experiment, we recommend you be familiar with the concepts in the following tutorial:

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram

Fritzing Relay

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Code To Note

digitalWrite(relayPin, HIGH);

When we turn on the transistor, which in turn energizes the relay’s coil, the relay’s switch contacts are closed. This connects the relay’s COM pin to the NO (Normally Open) pin. Whatever you’ve connected using these pins will turn on. (Here we’re using LEDs, but this could be almost anything.)

digitalWrite(relayPin, LOW);

The relay has an additional contact called NC (Normally Closed). The NC pin is connected to the COM pin when the relay is OFF. You can use either pin depending on whether something should be normally on or normally off. You can also use both pins to alternate power to two devices, much like railroad crossing warning lights.

Copy and paste the following code into the Arduino IDE. Hit upload and see what happens!

language:cpp
/*
SparkFun Inventor's Kit Galileo
Example sketch 13

RELAYS

  Use a transistor to drive a relay

  A relay is a electrically-controlled mechanical switch.
  It can control much more voltage and current than an Arduino pin
  (or the transistor included in your kit) can. If you want to use
  the Arduino to control a 120V bulb, coffee maker, or other high-
  power device, a relay is an excellent way to do that. Because
  the relay needs more power to switch than an Arduino pin can
  provide, we'll use a transistor to drive the relay in exactly
  the same way we used a transistor to drive a motor in circuit 12.

  A relay consists of a coil of wire, and switch contacts. When
  you apply power to the coil, it becomes magnetized, and pulls
  the switch contacts closed. Since the switch contacts are
  completely isolated from the Arduino, you can safely use a
  relay to control normally dangerous voltages (but please only do
  this if you already know how to safely work with high voltage!).

  The relay has three contact pins, COM (common), NC (Normally
  Closed), and NO (Normally Open). When the relay is turned off,
  the COM pin is connected to the NC (Normally Closed) pin. When
  the relay is turned on, the COM pin is connected to the NO
  (Normally Open) pin.

  This code is very simple - it turns the relay on for one second,
  and off for one second, the same as the blink sketch!

Hardware connections:

  Transistor:

    The transistor has three pins. Looking at the flat side with
    the pins down, the order is COLLECTOR, BASE, EMITTER.

    Connect the BASE pin through a 1K resistor to digital pin 2.

    Connect the EMITTER pin to GND.

  Relay coil:

    The relay has pins for a coil (which you use to control the
    relay), and contacts (which you connect to the device you'd
    like to switch). The top or bottom of the relay should have
    a symbol indicating the coil pins.

    Connect one side of the coil to the COLLECTOR pin
    on the transistor.

    Connect other side of the coil to 5V.

  Diode:

    The relay has a coil that you energize to close the switch.
    When you disconnect power from a coil, the coil will generate
    a voltage spike that can damage the transistor. This diode
    protects the transistor from the voltage spike.

    Connect the side of the diode with the band (cathode) to 5V

    Connect the other side of the diode (anode) to the COLLECTOR
    pin of the transistor.

  Relay contacts and LEDs:

    We'll use the relay contacts to turn LEDs on and off, but you
    can use them to switch almost anything on and off.

    Connect the COMMON side of the switch to a 330 Ohm resistor.
    Connect the other side of the above resistor to 5V.

    Connect the NC (Normally Closed) side of the switch to the
    positive (longer) leg of LED 1.

    Connect the NO (Normally Open) side of the switch to the
    positive (longer) leg of LED 2.

    Connect the negative sides (shorter leg) of both LEDs to GND.

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/


const int relayPin = 2;     // use this pin to drive the transistor
const int timeDelay = 1000; // delay in ms for on and off phases

// You can make timeDelay shorter, but note that relays, being
// mechanical devices, will wear out quickly if you try to drive
// them too fast.


void setup()
{
  pinMode(relayPin, OUTPUT);  // set pin as an output
}


void loop()
{
  digitalWrite(relayPin, HIGH);  // turn the relay on

  delay(timeDelay);              // wait for one second

  digitalWrite(relayPin, LOW);   // turn the relay off

  delay(timeDelay);              // wait for one second
}

What You Should See

You should be able to hear the relay contacts click, and see the two LEDs alternate illuminating at 1-second intervals. If you don’t, double-check that you have assembled the circuit correctly, and uploaded the correct sketch to the board. Also, see the troubleshooting section.

Galileo Relay

Real World Application

Garage door openers use relays to operate. You might be able to hear the clicking if you listen closely.

Troubleshooting

LEDs Not Lighting

Double-check that you’ve plugged them in correctly. The longer lead (and non-flat edge of the plastic flange) is the positive lead.

No Clicking Sound

The transistor or coil portion of the circuit isn’t quite working. Check the transistor is plugged in the right way.

Not Quite Working

The included relays are designed to be soldered rather than used in a breadboard. As such you may need to press it in to ensure it works (and it may pop out occasionally).

When you’re building the circuit be careful not to mix up the temperature sensor and the transistor, they’re almost identical.

SIK Galileo - Part 14: Using a Shift Register

Introduction

Now we are going to step into the world of ICs (integrated circuits). In this circuit, you’ll learn all about using a shift register (also called a serial-to-parallel converter). The shift register will give your Galileo an additional eight outputs, using only three pins on your board. For this circuit, you’ll practice by using the shift register to control eight LEDs.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x Galileo
  • 8x LEDs
  • 8x 330Ω Resistors
  • 1x Shift Register 8-Bit - 74HC595
  • 19x Jumper Wires

If you are following through all of the SIK Galileo tutorials we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

Out of stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

Out of stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

1/6 Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 330Ohm resistors make excellent…

0.95
LED - Assorted (20 pack)

LED - Assorted (20 pack)

In stock COM-12062

We all know that you can never get too many LEDs. Don't worry, we've got you covered. This is a pack of basic red, yellow, bl…

2.95
Shift Register 8-Bit - 74HC595

Shift Register 8-Bit - 74HC595

In stock COM-00733

Simple shift register IC. Clock in data and latch it to free up IO pins on your micro. Check out this [tutorial](http://dln…

1.5
Intel® Galileo

Intel® Galileo

In stock DEV-12720

The Intel® Galileo board is based on the Intel® Quark SoC X1000, a 32-bit Intel Pentium®-class system on a chip (SoC). It …

79.95

View the SparkFun Inventor’s Kit for Galileo wishlist, to see the parts needed to go through the all the experiments.

Suggested Reading

Before continuing on with this experiment, we recommend you be familiar with the concepts in the following tutorial:

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

For the shift register, align notch on top, in-between “e1” and “f1” on the breadboard. The notch indicates where pin 1 is.

Fritzing Diagram

Fritzing Shift Register

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Code To Note

shiftOut(datapin, clockpin, MSBFIRST, data);

You’ll communicate with the shift register (and a lot of other parts) using an interface called SPI, or Serial Peripheral Interface. This interface uses a data line and a separate clock line that work together to move data in or out of the Galileo at high speed. The MSBFIRST parameter specifies the order in which to send the individual bits, in this case we’re sending the Most Significant Bit first.

bitWrite(data, desiredPin, desiredState);

Bits are the smallest possible piece of memory in a computer; each one can store either a “1” or a “0”. Larger numbers are stored as arrays of bits. Sometimes we want to manipulate these bits directly, for example now when we’re sending eight bits to the shift register and we want to make them 1 or 0 to turn the LEDs on or off. The Galileo has several commands, such as bitWrite(), that make this easy to do.

Copy and paste the following code into the Arduino IDE. Hit upload and see what happens!

language:cpp
/*
SparkFun Inventor's Kit Galileo
Example sketch 13

SHIFT REGISTER

  Use a shift register to turn three pins into eight (or more!)
  outputs

  An integrated circuit ("IC"), or "chip", is a self-contained
  circuit built into a small plastic package. (If you look closely
  at your Arduino board you'll see a number of ICs.) There are
  thousands of different types of ICs available that you can use
  to perform many useful functions.

  The 74HC595 shift register in your kit is an IC that has eight
  digital outputs. To use these outputs, we'll use a new interface
  called SPI (Serial Peripheral Interface). It's like the TX and
  RX you're used to, but has an additional "clock" line that
  controls the speed of the data transfer. Many parts use SPI
  for communications, so the Arduino offers simple commands called
  shiftIn() and shiftOut() to access these parts.

  This IC lets you use three digital pins on your Arduino to
  control eight digital outputs on the chip. And if you need
  even more outputs, you can daisy-chain multiple shift registers
  together, allowing an almost unlimited number of outputs from
  the same three Arduino pins! See the shift register datasheet
  for details:

  http://www.sparkfun.com/datasheets/IC/SN74HC595.pdf

Hardware connections:

  Shift register:

    Plug in the chip so it bridges the center "canyon"
    on the breadboard.

    The shift register has 16 pins. They are numbered
    counterclockwise starting at the pin 1 mark (notch
    in the end of the chip). See the datasheet above
    for a diagram.

    74HC595 pin     LED pin     Arduino pin

    1  (QB)     LED 2 +
    2  (QC)     LED 3 +
    3  (QD)     LED 4 +
    4  (QE)     LED 5 +
    5  (QF)     LED 6 +
    6  (QG)     LED 7 +
    7  (QH)     LED 8 +
    8  (GND)                GND

    9  (QH*)
    10 (SRCLR*)             5V
    11 (SRCLK)              Digital 3
    12 (RCLK)               Digital 4
    13 (OE*)                GND
    14 (SER)                Digital 2
    15 (QA)     LED 1 +
    16 (VCC)                5V

  LEDs:

    After making the above connections to the positive (longer)
    legs of the LEDs, connect the negative side (short lead) of
    each LED to a 330 Ohm resistor, and connect the other side
    of each resistor to GND.

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/


// Pin definitions:
// The 74HC595 uses a type of serial connection called SPI
// (Serial Peripheral Interface) that requires three pins:

int datapin = 2;
int clockpin = 3;
int latchpin = 4;

// We'll also declare a global variable for the data we're
// sending to the shift register:

byte data = 0;


void setup()
{
  // Set the three SPI pins to be outputs:

  pinMode(datapin, OUTPUT);
  pinMode(clockpin, OUTPUT);
  pinMode(latchpin, OUTPUT);
}


void loop()
{
  // We're going to use the same functions we played with back
  // in circuit 04, "Multiple LEDs", we've just replaced
  // digitalWrite() with a new function called shiftWrite()
  // (see below). We also have a new function that demonstrates
  // binary counting.

  // To try the different functions below, uncomment the one
  // you want to run, and comment out the remaining ones to
  // disable them from running.

  oneAfterAnother();      // All on, all off

  //oneOnAtATime();       // Scroll down the line

  //pingPong();           // Like above, but back and forth

  //randomLED();          // Blink random LEDs

  //marquee();

  //binaryCount();        // Bit patterns from 0 to 255
}


void shiftWrite(int desiredPin, boolean desiredState)

// This function lets you make the shift register outputs
// HIGH or LOW in exactly the same way that you use digitalWrite().

// Like digitalWrite(), this function takes two parameters:

//    "desiredPin" is the shift register output pin
//    you want to affect (0-7)

//    "desiredState" is whether you want that output
//    to be HIGH or LOW

// Inside the Arduino, numbers are stored as arrays of "bits",
// each of which is a single 1 or 0 value. Because a "byte" type
// is also eight bits, we'll use a byte (which we named "data"
// at the top of this sketch) to send data to the shift register.
// If a bit in the byte is "1", the output will be HIGH. If the bit
// is "0", the output will be LOW.

// To turn the individual bits in "data" on and off, we'll use
// a new Arduino commands called bitWrite(), which can make
// individual bits in a number 1 or 0.
{
  // First we'll alter the global variable "data", changing the
  // desired bit to 1 or 0:

  bitWrite(data,desiredPin,desiredState);

  // Now we'll actually send that data to the shift register.
  // The shiftOut() function does all the hard work of
  // manipulating the data and clock pins to move the data
  // into the shift register:

  shiftOut(datapin, clockpin, MSBFIRST, data);

  // Once the data is in the shift register, we still need to
  // make it appear at the outputs. We'll toggle the state of
  // the latchPin, which will signal the shift register to "latch"
  // the data to the outputs. (Latch activates on the high-to
  // -low transition).

  digitalWrite(latchpin, HIGH);
  digitalWrite(latchpin, LOW);
}


/*
oneAfterAnother()

This function will light one LED, delay for delayTime, then light
the next LED, and repeat until all the LEDs are on. It will then
turn them off in the reverse order.
*/

void oneAfterAnother()
{
  int index;
  int delayTime = 100; // Time (milliseconds) to pause between LEDs
                       // Make this smaller for faster switching

  // Turn all the LEDs on:

  // This for() loop will step index from 0 to 7
  // (putting "++" after a variable means add one to it)
  // and will then use digitalWrite() to turn that LED on.

  for(index = 0; index <= 7; index++)
  {
    shiftWrite(index, HIGH);
    delay(delayTime);
  }

  // Turn all the LEDs off:

  // This for() loop will step index from 7 to 0
  // (putting "--" after a variable means subtract one from it)
  // and will then use digitalWrite() to turn that LED off.

  for(index = 7; index >= 0; index--)
  {
    shiftWrite(index, LOW);
    delay(delayTime);
  }
}


/*
oneOnAtATime()

This function will step through the LEDs, lighting one at at time.
*/

void oneOnAtATime()
{
  int index;
  int delayTime = 100; // Time (milliseconds) to pause between LEDs
                       // Make this smaller for faster switching

  // step through the LEDs, from 0 to 7

  for(index = 0; index <= 7; index++)
  {
    shiftWrite(index, HIGH);    // turn LED on
    delay(delayTime);       // pause to slow down the sequence
    shiftWrite(index, LOW); // turn LED off
  }
}


/*
pingPong()

This function will step through the LEDs, lighting one at at time,
in both directions.
*/

void pingPong()
{
  int index;
  int delayTime = 100; // time (milliseconds) to pause between LEDs
                       // make this smaller for faster switching

  // step through the LEDs, from 0 to 7

  for(index = 0; index <= 7; index++)
  {
    shiftWrite(index, HIGH);    // turn LED on
    delay(delayTime);       // pause to slow down the sequence
    shiftWrite(index, LOW); // turn LED off
  }

  // step through the LEDs, from 7 to 0

  for(index = 7; index >= 0; index--)
  {
    shiftWrite(index, HIGH);    // turn LED on
    delay(delayTime);       // pause to slow down the sequence
    shiftWrite(index, LOW); // turn LED off
  }
}


/*
randomLED()

This function will turn on random LEDs. Can you modify it so it
also lights them for random times?
*/

void randomLED()
{
  int index;
  int delayTime = 100; // time (milliseconds) to pause between LEDs
                       // make this smaller for faster switching

  // The random() function will return a semi-random number each
  // time it is called. See http://arduino.cc/en/Reference/Random
  // for tips on how to make random() more random.

  index = random(8);    // pick a random number between 0 and 7

  shiftWrite(index, HIGH);  // turn LED on
  delay(delayTime);     // pause to slow down the sequence
  shiftWrite(index, LOW);   // turn LED off
}


/*
marquee()

This function will mimic "chase lights" like those around signs.
*/

void marquee()
{
  int index;
  int delayTime = 200; // Time (milliseconds) to pause between LEDs
                       // Make this smaller for faster switching

  // Step through the first four LEDs
  // (We'll light up one in the lower 4 and one in the upper 4)

  for(index = 0; index <= 3; index++)
  {
    shiftWrite(index, HIGH);    // Turn a LED on
    shiftWrite(index+4, HIGH);  // Skip four, and turn that LED on
    delay(delayTime);       // Pause to slow down the sequence
    shiftWrite(index, LOW); // Turn both LEDs off
    shiftWrite(index+4, LOW);
  }
}


/*
binaryCount()

Numbers are stored internally in the Arduino as arrays of "bits",
each of which is a 1 or 0. Just like the base-10 numbers we use
every day, The position of the bit affects the magnitude of its
contribution to the total number:

Bit position   Contribution
0              1
1              2
2              4
3              8
4              16
5              32
6              64
7              128

To build any number from 0 to 255 from the above 8 bits, just
select the contributions you need to make. The bits will then be
1 if you use that contribution, and 0 if you don't.

This function will increment the "data" variable from 0 to 255
and repeat. When we send this value to the shift register and LEDs,
you can see the on-off pattern of the eight bits that make up the
byte. See http://www.arduino.cc/playground/Code/BitMath for more
information on binary numbers.
*/

void binaryCount()
{
  int delayTime = 1000; // time (milliseconds) to pause between LEDs
                        // make this smaller for faster switching

  // Send the data byte to the shift register:

  shiftOut(datapin, clockpin, MSBFIRST, data);

  // Toggle the latch pin to make the data appear at the outputs:

  digitalWrite(latchpin, HIGH);
  digitalWrite(latchpin, LOW);

  // Add one to data, and repeat!
  // (Because a byte type can only store numbers from 0 to 255,
  // if we add more than that, it will "roll around" back to 0
  // and start over).

  data++;

  // Delay so you can see what's going on:

  delay(delayTime);
}

What You Should See

You should see the LEDs light up similarly to SIK Galileo - Part 4 (but this time, you’re using a shift register). If they aren’t, make sure you have assembled the circuit correctly and verified and uploaded the code to your board. See the troubleshooting section.

Fritzing Shift Register

Real World Application

Similar to SIK Galileo - Part 4, a scrolling marquee display delivers a message with multiple LEDs. Essentially the same task the shift register achieves here in SIK Galileo - Part 14.

Troubleshooting

The Galileo’s power LED goes out

This happened to us a couple of times, it happens when the chip is inserted backward. If you fix it quickly nothing will break.

Not Quite Working

Sorry to sound like a broken record but it is probably something as simple as a crossed wire.

Frustration

Shoot us an e-mail, this circuit is both simple and complex at the same time. We want to hear about problems you have so we can address them in future editions: techsupport@sparkfun.com

SIK Galileo - Part 15: Using an LCD

Introduction

In this circuit, you’ll learn about how to use an LCD. An LCD, or liquid crystal display, is a simple screen that can display commands, bits of information, or readings from your sensor - all depending on how you program your board. In this circuit, you’ll learn the basics of incorporating an LCD into your project.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x Galileo
  • 1x Potentiometer
  • 1x LCD
  • 16x Jumper Wires

If you are following through all of the SIK Galileo tutorials we suggest using these parts:

Trimpot 10K with Knob

Trimpot 10K with Knob

In stock COM-09806

There are lots of trimpots out there. Some are very large, some so small they require a screwdriver. Here at SparkFun, we jus…

0.95
Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

Out of stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

Out of stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Basic 16x2 Character LCD - White on Black 5V

Basic 16x2 Character LCD - White on Black 5V

In stock LCD-00709

This is a basic 16 character by 2 line display with a snazzy black background with white characters. Utilizes the extremely c…

15.95
Intel® Galileo

Intel® Galileo

In stock DEV-12720

The Intel® Galileo board is based on the Intel® Quark SoC X1000, a 32-bit Intel Pentium®-class system on a chip (SoC). It …

79.95

View the SparkFun Inventor’s Kit for Galileo wishlist, to see the parts needed to go through the all the experiments.

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram

Fritzing LCD

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Code To Note

#include <LiquidCrystal.h>

This bit of code tells your Arduino IDE to include the library for a simple LCD display. Without it, none of the commands will work, so make sure you include it!

lcd.print(“hello, world!”);

This is the first time you’ll fire something up on your screen. You may need to adjust the contrast to make it visible. Twist the potentiometer until you can clearly see the text!

Copy and paste the following code into the Arduino IDE. Hit upload and see what happens!

language:cpp
/*
SparkFun Inventor's Kit Galileo
Example sketch 15

LIQUID CRYSTAL DISPLAY (LCD)

  A Liquid Crystal Display (LCD) is a sophisticated module
  that can be used to display text or numeric data. The display
  included in your SIK features two lines of 16 characters, and
  a backlight so it can be used at night.

  If you've been using the Serial Monitor to output data,
  you'll find that a LCD provides many of the same benefits
  without needing to drag a large computer around.

  This sketch will show you how to connect an LCD to your Arduino
  and display any data you wish.

Hardware connections:

  The LCD has a 16-pin male header attached to it along the top
  edge. Pin 1 is the pin closest to the corner of the LCD.
  Pin 16 is the pin closest to the center of the LCD.

  Plug the LCD into your breadboard.

  As usual, you will want to connect the + and - power rails
  on the side of the breadboard to 5V and GND on your Arduino.

  Plug your 10K potentiometer into three unused rows on your
  breadboard. Connect one side of the potentiometer to 5V,
  and the other side to GND (it doesn't matter which). When you
  run this sketch, you'll use the potentiometer to adjust the
  contrast of the LCD so you can see the display.

  Now connect the LCD pins. Remember that pin 1 on the LCD
  is the one closest to the corner. Start there and work your
  way up.

  1 to GND
  2 to 5V
  3 to the center pin on the potentiometer
  4 to Galileo digital pin 12
  5 to GND
  6 to Galileo  digital pin 11
  7 (no connection)
  8 (no connection)
  9 (no connection)
  10 (no connection)
  11 to Galileo  digital pin 5
  12 to Galileo  digital pin 4
  13 to Galileo  digital pin 3
  14 to Galileo  digital pin 2
  15 to 5V
  16 to GND

  Once everything is connected, load this sketch into the
  Galileo, and adjust the potentiometer until the display
  is clear.

Library

  The LCD has a chip built into it that controls all the
  individual dots that make up the display, and obeys commands
  sent to it by the the Arduino. The chip knows the dot patterns
  that make up all the text characters, saving you a lot of work.

  To communicate with this chip, we'll use the LiquidCrystal
  library, which is one of the standard libraries that comes
  with the Arduino. This library does most of the hard work
  of interfacing to the LCD; all you need to pick a location
  on the display and send your data!

Tips

  The LCD comes with a protective film over the display that
  you can peel off (but be careful of the display surface as
  it scratches easily).

  The LCD has a backlight that will light up when you turn on
  your Arduino. If the backlight doesn't turn on, check your
  connections.

  As we said above, the potentiometer adjusts the contrast of
  the display. If you can't see anything when you run the sketch,
  turn the potentiometer's knob until the text is clear.

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 1.0 2/2013 MDG
*/

// Load the LiquidCrystal library, which will give us
// commands to interface to the LCD:

#include <LiquidCrystal.h>

// Initialize the library with the pins we're using.
// (Note that you can use different pins if needed.)
// See http://arduino.cc/en/Reference/LiquidCrystal
// for more information:

LiquidCrystal lcd(12,11,5,4,3,2);

void setup()
{
  // The LiquidCrystal library can be used with many different
  // LCD sizes. We're using one that's 2 lines of 16 characters,
  // so we'll inform the library of that:

  lcd.begin(16, 2);

  // Data sent to the display will stay there until it's
  // overwritten or power is removed. This can be a problem
  // when you upload a new sketch to the Arduino but old data
  // remains on the display. Let's clear the LCD using the
  // clear() command from the LiquidCrystal library:

  lcd.clear();

  // Now we'll display a message on the LCD!

  // Just as with the Arduino IDE, there's a cursor that
  // determines where the data you type will appear. By default,
  // this cursor is invisible, though you can make it visible
  // with other library commands if you wish.

  // When the display powers up, the invisible cursor starts
  // on the top row and first column.

  lcd.print("hello, world!");

  // Adjusting the contrast (IMPORTANT!)

  // When you run the sketch for the first time, there's a
  // very good chance you won't see anything on the LCD display.
  // This is because the contrast likely won't be set correctly.
  // Don't worry, it's easy to set, and once you set it you won't
  // need to change it again.

  // Run the sketch, then turn the potentiometer until you can
  // clearly see the "hello, world!" text. If you still can't
  // see anything, check all of your connections, and ensure that
  // the sketch was successfully uploaded to the Arduino.
}

void loop()
{
  // You can move the invisible cursor to any location on the
  // LCD before sending data. Counting starts from 0, so the top
  // line is line 0 and the bottom line is line 1. Columns range
  // from 0 on the left side, to 15 on the right.

  // In additon to the "hello, world!" printed above, let's
  // display a running count of the seconds since the Arduino
  // was last reset. Note that the data you send to the display
  // will stay there unless you erase it by overwriting it or
  // sending a lcd.clear() command.

  // Here we'll set the invisible cursor to the first column
  // (column 0) of the second line (line 1):

  lcd.setCursor(0,1);

  // Now we'll print the number of seconds (millis() / 1000)
  // since the Arduino last reset:

  lcd.print(millis()/1000);

  // TIP: Since the numeric data we're sending is always growing
  // in length, new values will always overwrite the previous ones.
  // However, if you want to display varying or decreasing numbers
  // like a countdown, you'll find that the display will leave
  // "orphan" characters when the new value is shorter than the
  // old one.

  // To prevent this, you'll need to erase the old number before
  // writing the new one. You can do this by overwriting the
  // last number with spaces. If you erase the old number and
  // immediately write the new one, the momentary erase won't
  // be noticeable. Here's a typical sequence of code:

  // lcd.setCursor(0,1);   // Set the cursor to the position
  // lcd.print(""); // Erase the largest possible number
  // lcd.setCursor(0,1);   // Reset the cursor to the original position
  // lcd.print(millis()/1000); // Print our value

  // NEXT STEPS:

  // Now you know the basics of hooking up an LCD to the Arduino,
  // and sending text and numeric data to the display!

  // The LCD library has many commands for turning the
  // cursor on and off, scrolling the screen, etc. See:
  // http://arduino.cc/en/Reference/LiquidCrystal
  // for more information.

  // Arduino also comes with a number of built-in examples
  // showing off the features of the LiquidCrystal library.
  // These are locted in the file/examples/LiquidCrystal menu.

  // Have fun, and let us know what you create!
  // Your friends at SparkFun.
}

What You Should See

Initially, you should see the words “hello, world!” pop up on your LCD. Remember you can adjust the contrast using the potentiometer if you can’t make out the words clearly. If you have any issues, make sure your code is correct and double-check your connections.

Galileo LCD

Real World Application

LCDs are everywhere! From advanced LCDs like your television, to simple notification screens, this is a very common and useful display!

The Screen is Blank or Completely Lit?

Fiddle with the contrast by twisting the potentiometer. If it’s incorrectly adjusted, you won’t be able to read the text.

Not Working At All?

Double check the code, specifically that you include the LCD library.

Screen Is Flickering

Double check your connections to your breadboard and Galileo.

SIK Galileo - Part 16: Simon Says

Introduction

Now that we’ve learned all the basics behind the components in the SIK Galileo tutorials, let’s put them all together to make some fun. This circuit will show you how to create your own Simon Says game. Using some LEDs, some buttons, a buzzer, and some resistors, you can create this and other exciting games with the Galileo.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x Galileo
  • 4x LEDs
  • 1x Piezo Buzzer
  • 4x 330Ω Resistors
  • 4x Push Buttons
  • 17x Jumper Wires

If you are following through all of the SIK Galileo tutorials we suggest using these parts:

Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

Out of stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

1/6 Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 330Ohm resistors make excellent…

0.95
Momentary Push Button Switch - 12mm Square

Momentary Push Button Switch - 12mm Square

In stock COM-09190

This is a standard 12mm square momentary button. What we really like is the large button head and good tactile feel (it 'clic…

0.5
LED - Assorted (20 pack)

LED - Assorted (20 pack)

In stock COM-12062

We all know that you can never get too many LEDs. Don't worry, we've got you covered. This is a pack of basic red, yellow, bl…

2.95
Piezo Speaker - PC Mount 12mm 2.048kHz

Piezo Speaker - PC Mount 12mm 2.048kHz

In stock COM-07950

This is a small 12mm round speaker that operates around the audible 2kHz range. You can use these speakers to create simple m…

1.95

View the SparkFun Inventor’s Kit for Galileo wishlist, to see the parts needed to go through the all the experiments.

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram

Fritzing

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Code To Note

#define

The #define statement is used to create constants in your code. Constants are variables that will likely only have one value during the lifespan of your code. Thus, you can assign constants a value, and then use them throughout your code wherever. Then, if you need to change that value, you can change that one line instead of going through all the code to find every instance of that variable.

byte

Bytes are another variable type. In the world of computing, a byte is a chunk of space that contains 8 bits, and a bit is a single binary value. Binary is another way of counting and uses only 1’s and 0’s. So a byte can hold all 1’s: 11111111, all 0’s: 00000000, or a combination of the two: 10010110.

Copy and paste the following code into the Arduino IDE. Hit upload and see what happens!

language:cpp
/*
 SparkFun Inventor's Kit
 Example sketch 16
 Spark Fun Electronics
 Oct. 7, 2014

 Simon Says is a memory game. Start the game by pressing one of the four buttons. When a button lights up,
 press the button, repeating the sequence. The sequence will get longer and longer. The game is won after
 13 rounds.

 Generates random sequence, plays music, and displays button lights.

 Simon tones from Wikipedia
 - A (red, upper left) - 440Hz - 2.272ms - 1.136ms pulse
 - a (green, upper right, an octave higher than A) - 880Hz - 1.136ms,
 0.568ms pulse
 - D (blue, lower left, a perfect fourth higher than the upper left)
 587.33Hz - 1.702ms - 0.851ms pulse
 - G (yellow, lower right, a perfect fourth higher than the lower left) -
 784Hz - 1.276ms - 0.638ms pulse

 Simon Says game originally written in C for the PIC16F88.
 Ported for the ATmega168, then ATmega328, then Arduino 1.0.
 Fixes and cleanup by Joshua Neal <joshua[at]trochotron.com>

 This sketch was written by SparkFun Electronics,
 with lots of help from the Arduino community.
 This code is completely free for any use.
 Visit http://www.arduino.cc to learn about the Arduino.
 */

/*************************************************
* Public Constants
*************************************************/
#define NOTE_B0 31
#define NOTE_C1 33
#define NOTE_CS1 35
#define NOTE_D1 37
#define NOTE_DS1 39
#define NOTE_E1 41
#define NOTE_F1 44
#define NOTE_FS1 46
#define NOTE_G1 49
#define NOTE_GS1 52
#define NOTE_A1 55
#define NOTE_AS1 58
#define NOTE_B1 62
#define NOTE_C2 65
#define NOTE_CS2 69
#define NOTE_D2 73
#define NOTE_DS2 78
#define NOTE_E2 82
#define NOTE_F2 87
#define NOTE_FS2 93
#define NOTE_G2 98
#define NOTE_GS2 104
#define NOTE_A2 110
#define NOTE_AS2 117
#define NOTE_B2 123
#define NOTE_C3 131
#define NOTE_CS3 139
#define NOTE_D3 147
#define NOTE_DS3 156
#define NOTE_E3 165
#define NOTE_F3 175
#define NOTE_FS3 185
#define NOTE_G3 196
#define NOTE_GS3 208
#define NOTE_A3 220
#define NOTE_AS3 233
#define NOTE_B3 247
#define NOTE_C4 262
#define NOTE_CS4 277
#define NOTE_D4 294
#define NOTE_DS4 311
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_FS4 370
#define NOTE_G4 392
#define NOTE_GS4 415
#define NOTE_A4 440
#define NOTE_AS4 466
#define NOTE_B4 494
#define NOTE_C5 523
#define NOTE_CS5 554
#define NOTE_D5 587
#define NOTE_DS5 622
#define NOTE_E5 659
#define NOTE_F5 698
#define NOTE_FS5 740
#define NOTE_G5 784
#define NOTE_GS5 831
#define NOTE_A5 880
#define NOTE_AS5 932
#define NOTE_B5 988
#define NOTE_C6 1047
#define NOTE_CS6 1109
#define NOTE_D6 1175
#define NOTE_DS6 1245
#define NOTE_E6 1319
#define NOTE_F6 1397
#define NOTE_FS6 1480
#define NOTE_G6 1568
#define NOTE_GS6 1661
#define NOTE_A6 1760
#define NOTE_AS6 1865
#define NOTE_B6 1976
#define NOTE_C7 2093
#define NOTE_CS7 2217
#define NOTE_D7 2349
#define NOTE_DS7 2489
#define NOTE_E7 2637
#define NOTE_F7 2794
#define NOTE_FS7 2960
#define NOTE_G7 3136
#define NOTE_GS7 3322
#define NOTE_A7 3520
#define NOTE_AS7 3729
#define NOTE_B7 3951
#define NOTE_C8 4186
#define NOTE_CS8 4435
#define NOTE_D8 4699
#define NOTE_DS8 4978

#define CHOICE_OFF      0 //Used to control LEDs
#define CHOICE_NONE     0 //Used to check buttons
#define CHOICE_RED  (1 << 0)
#define CHOICE_GREEN    (1 << 1)
#define CHOICE_BLUE (1 << 2)
#define CHOICE_YELLOW   (1 << 3)

#define LED_RED     10
#define LED_GREEN   3
#define LED_BLUE    13
#define LED_YELLOW  5

// Button pin definitions
#define BUTTON_RED    9
#define BUTTON_GREEN  2
#define BUTTON_BLUE   12
#define BUTTON_YELLOW 6

// Buzzer pin definitions
#define BUZZER1  4
#define BUZZER2  7

// Define game parameters
#define ROUNDS_TO_WIN      13 //Number of rounds to succesfully remember before you win. 13 is do-able.
#define ENTRY_TIME_LIMIT   3000 //Amount of time to press a button before game times out. 3000ms = 3 sec

#define MODE_MEMORY  0
#define MODE_BATTLE  1
#define MODE_BEEGEES 2

// Game state variables
byte gameMode = MODE_MEMORY; //By default, let's play the memory game
byte gameBoard[32]; //Contains the combination of buttons as we advance
byte gameRound = 0; //Counts the number of succesful rounds the player has made it through

void setup()
{
  //Setup hardware inputs/outputs. These pins are defined in the hardware_versions header file

  //Enable pull ups on inputs
  pinMode(BUTTON_RED, INPUT_PULLUP);
  pinMode(BUTTON_GREEN, INPUT_PULLUP);
  pinMode(BUTTON_BLUE, INPUT_PULLUP);
  pinMode(BUTTON_YELLOW, INPUT_PULLUP);

  pinMode(LED_RED, OUTPUT);
  pinMode(LED_GREEN, OUTPUT);
  pinMode(LED_BLUE, OUTPUT);
  pinMode(LED_YELLOW, OUTPUT);

  pinMode(BUZZER1, OUTPUT);
  pinMode(BUZZER2, OUTPUT);

  //Mode checking
  gameMode = MODE_MEMORY; // By default, we're going to play the memory game

  // Check to see if the lower right button is pressed
  if (checkButton() == CHOICE_YELLOW) play_beegees();

  // Check to see if upper right button is pressed
  if (checkButton() == CHOICE_GREEN)
  {
    gameMode = MODE_BATTLE; //Put game into battle mode

    //Turn on the upper right (green) LED
    setLEDs(CHOICE_GREEN);
    toner(CHOICE_GREEN, 150);

    setLEDs(CHOICE_RED | CHOICE_BLUE | CHOICE_YELLOW); // Turn on the other LEDs until you release button

    while(checkButton() != CHOICE_NONE) ; // Wait for user to stop pressing button

    //Now do nothing. Battle mode will be serviced in the main routine
  }

  play_winner(); // After setup is complete, say hello to the world
}

void loop()
{
  attractMode(); // Blink lights while waiting for user to press a button

  // Indicate the start of game play
  setLEDs(CHOICE_RED | CHOICE_GREEN | CHOICE_BLUE | CHOICE_YELLOW); // Turn all LEDs on
  delay(1000);
  setLEDs(CHOICE_OFF); // Turn off LEDs
  delay(250);

  if (gameMode == MODE_MEMORY)
  {
    // Play memory game and handle result
    if (play_memory() == true)
      play_winner(); // Player won, play winner tones
    else
      play_loser(); // Player lost, play loser tones
  }

  if (gameMode == MODE_BATTLE)
  {
    play_battle(); // Play game until someone loses

    play_loser(); // Player lost, play loser tones
  }
}

//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//The following functions are related to game play only

// Play the regular memory game
// Returns 0 if player loses, or 1 if player wins
boolean play_memory(void)
{
  randomSeed(millis()); // Seed the random generator with random amount of millis()

  gameRound = 0; // Reset the game to the beginning

  while (gameRound < ROUNDS_TO_WIN)
  {
    add_to_moves(); // Add a button to the current moves, then play them back

    playMoves(); // Play back the current game board

    // Then require the player to repeat the sequence.
    for (byte currentMove = 0 ; currentMove < gameRound ; currentMove++)
    {
      byte choice = wait_for_button(); // See what button the user presses

      if (choice == 0) return false; // If wait timed out, player loses

      if (choice != gameBoard[currentMove]) return false; // If the choice is incorect, player loses
    }

    delay(1000); // Player was correct, delay before playing moves
  }

  return true; // Player made it through all the rounds to win!
}

// Play the special 2 player battle mode
// A player begins by pressing a button then handing it to the other player
// That player repeats the button and adds one, then passes back.
// This function returns when someone loses
boolean play_battle(void)
{
  gameRound = 0; // Reset the game frame back to one frame

  while (1) // Loop until someone fails
  {
    byte newButton = wait_for_button(); // Wait for user to input next move
    gameBoard[gameRound++] = newButton; // Add this new button to the game array

    // Then require the player to repeat the sequence.
    for (byte currentMove = 0 ; currentMove < gameRound ; currentMove++)
    {
      byte choice = wait_for_button();

      if (choice == 0) return false; // If wait timed out, player loses.

      if (choice != gameBoard[currentMove]) return false; // If the choice is incorect, player loses.
    }

    delay(100); // Give the user an extra 100ms to hand the game to the other player
  }

  return true; // We should never get here
}

// Plays the current contents of the game moves
void playMoves(void)
{
  for (byte currentMove = 0 ; currentMove < gameRound ; currentMove++)
  {
    toner(gameBoard[currentMove], 150);

    // Wait some amount of time between button playback
    // Shorten this to make game harder
    delay(150); // 150 works well. 75 gets fast.
  }
}

// Adds a new random button to the game sequence, by sampling the timer
void add_to_moves(void)
{
  byte newButton = random(0, 4); //min (included), max (exluded)

  // We have to convert this number, 0 to 3, to CHOICEs
  if(newButton == 0) newButton = CHOICE_RED;
  else if(newButton == 1) newButton = CHOICE_GREEN;
  else if(newButton == 2) newButton = CHOICE_BLUE;
  else if(newButton == 3) newButton = CHOICE_YELLOW;

  gameBoard[gameRound++] = newButton; // Add this new button to the game array
}

//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//The following functions control the hardware

// Lights a given LEDs
// Pass in a byte that is made up from CHOICE_RED, CHOICE_YELLOW, etc
void setLEDs(byte leds)
{
  if ((leds & CHOICE_RED) != 0)
    digitalWrite(LED_RED, HIGH);
  else
    digitalWrite(LED_RED, LOW);

  if ((leds & CHOICE_GREEN) != 0)
    digitalWrite(LED_GREEN, HIGH);
  else
    digitalWrite(LED_GREEN, LOW);

  if ((leds & CHOICE_BLUE) != 0)
    digitalWrite(LED_BLUE, HIGH);
  else
    digitalWrite(LED_BLUE, LOW);

  if ((leds & CHOICE_YELLOW) != 0)
    digitalWrite(LED_YELLOW, HIGH);
  else
    digitalWrite(LED_YELLOW, LOW);
}

// Wait for a button to be pressed.
// Returns one of LED colors (LED_RED, etc.) if successful, 0 if timed out
byte wait_for_button(void)
{
  long startTime = millis(); // Remember the time we started the this loop

  while ( (millis() - startTime) < ENTRY_TIME_LIMIT) // Loop until too much time has passed
  {
    byte button = checkButton();

    if (button != CHOICE_NONE)
    {
      toner(button, 150); // Play the button the user just pressed

      while(checkButton() != CHOICE_NONE) ;  // Now let's wait for user to release button

      delay(10); // This helps with debouncing and accidental double taps

      return button;
    }

  }

  return CHOICE_NONE; // If we get here, we've timed out!
}

// Returns a '1' bit in the position corresponding to CHOICE_RED, CHOICE_GREEN, etc.
byte checkButton(void)
{
  if (digitalRead(BUTTON_RED) == 0) return(CHOICE_RED);
  else if (digitalRead(BUTTON_GREEN) == 0) return(CHOICE_GREEN);
  else if (digitalRead(BUTTON_BLUE) == 0) return(CHOICE_BLUE);
  else if (digitalRead(BUTTON_YELLOW) == 0) return(CHOICE_YELLOW);

  return(CHOICE_NONE); // If no button is pressed, return none
}

// Light an LED and play tone
// Red, upper left:     440Hz - 2.272ms - 1.136ms pulse
// Green, upper right:  880Hz - 1.136ms - 0.568ms pulse
// Blue, lower left:    587.33Hz - 1.702ms - 0.851ms pulse
// Yellow, lower right: 784Hz - 1.276ms - 0.638ms pulse
void toner(byte which, int buzz_length_ms)
{
  setLEDs(which); //Turn on a given LED

  //Play the sound associated with the given LED
  switch(which)
  {
  case CHOICE_RED:
    buzz_sound(buzz_length_ms, 1136);
    break;
  case CHOICE_GREEN:
    buzz_sound(buzz_length_ms, 568);
    break;
  case CHOICE_BLUE:
    buzz_sound(buzz_length_ms, 851);
    break;
  case CHOICE_YELLOW:
    buzz_sound(buzz_length_ms, 638);
    break;
  }

  setLEDs(CHOICE_OFF); // Turn off all LEDs
}

// Toggle buzzer every buzz_delay_us, for a duration of buzz_length_ms.
void buzz_sound(int buzz_length_ms, int buzz_delay_us)
{
  // Convert total play time from milliseconds to microseconds
  long buzz_length_us = buzz_length_ms * (long)1000;

  // Loop until the remaining play time is less than a single buzz_delay_us
  while (buzz_length_us > (buzz_delay_us * 2))
  {
    buzz_length_us -= buzz_delay_us * 2; //Decrease the remaining play time

    // Toggle the buzzer at various speeds
    digitalWrite(BUZZER1, LOW);
    digitalWrite(BUZZER2, HIGH);
    delayMicroseconds(buzz_delay_us);

    digitalWrite(BUZZER1, HIGH);
    digitalWrite(BUZZER2, LOW);
    delayMicroseconds(buzz_delay_us);
  }
}

// Play the winner sound and lights
void play_winner(void)
{
  setLEDs(CHOICE_GREEN | CHOICE_BLUE);
  winner_sound();
  setLEDs(CHOICE_RED | CHOICE_YELLOW);
  winner_sound();
  setLEDs(CHOICE_GREEN | CHOICE_BLUE);
  winner_sound();
  setLEDs(CHOICE_RED | CHOICE_YELLOW);
  winner_sound();
}

// Play the winner sound
// This is just a unique (annoying) sound we came up with, there is no magic to it
void winner_sound(void)
{
  // Toggle the buzzer at various speeds
  for (byte x = 250 ; x > 70 ; x--)
  {
    for (byte y = 0 ; y < 3 ; y++)
    {
      digitalWrite(BUZZER2, HIGH);
      digitalWrite(BUZZER1, LOW);
      delayMicroseconds(x);

      digitalWrite(BUZZER2, LOW);
      digitalWrite(BUZZER1, HIGH);
      delayMicroseconds(x);
    }
  }
}

// Play the loser sound/lights
void play_loser(void)
{
  setLEDs(CHOICE_RED | CHOICE_GREEN);
  buzz_sound(255, 1500);

  setLEDs(CHOICE_BLUE | CHOICE_YELLOW);
  buzz_sound(255, 1500);

  setLEDs(CHOICE_RED | CHOICE_GREEN);
  buzz_sound(255, 1500);

  setLEDs(CHOICE_BLUE | CHOICE_YELLOW);
  buzz_sound(255, 1500);
}

// Show an "attract mode" display while waiting for user to press button.
void attractMode(void)
{
  while(1)
  {
    setLEDs(CHOICE_RED);
    delay(100);
    if (checkButton() != CHOICE_NONE) return;

    setLEDs(CHOICE_BLUE);
    delay(100);
    if (checkButton() != CHOICE_NONE) return;

    setLEDs(CHOICE_GREEN);
    delay(100);
    if (checkButton() != CHOICE_NONE) return;

    setLEDs(CHOICE_YELLOW);
    delay(100);
    if (checkButton() != CHOICE_NONE) return;
  }
}

//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// The following functions are related to Beegees Easter Egg only

// Notes in the melody. Each note is about an 1/8th note, "0"s are rests.
int melody[] = {
  NOTE_G4, NOTE_A4, 0, NOTE_C5, 0, 0, NOTE_G4, 0, 0, 0,
  NOTE_E4, 0, NOTE_D4, NOTE_E4, NOTE_G4, 0,
  NOTE_D4, NOTE_E4, 0, NOTE_G4, 0, 0,
  NOTE_D4, 0, NOTE_E4, 0, NOTE_G4, 0, NOTE_A4, 0, NOTE_C5, 0};

int noteDuration = 115; // This essentially sets the tempo, 115 is just about right for a disco groove :)
int LEDnumber = 0; // Keeps track of which LED we are on during the beegees loop

// Do nothing but play bad beegees music
// This function is activated when user holds bottom right button during power up
void play_beegees()
{
  //Turn on the bottom right (yellow) LED
  setLEDs(CHOICE_YELLOW);
  toner(CHOICE_YELLOW, 150);

  setLEDs(CHOICE_RED | CHOICE_GREEN | CHOICE_BLUE); // Turn on the other LEDs until you release button

  while(checkButton() != CHOICE_NONE) ; // Wait for user to stop pressing button

  setLEDs(CHOICE_NONE); // Turn off LEDs

  delay(1000); // Wait a second before playing song

  digitalWrite(BUZZER1, LOW); // setup the "BUZZER1" side of the buzzer to stay low, while we play the tone on the other pin.

  while(checkButton() == CHOICE_NONE) //Play song until you press a button
  {
    // iterate over the notes of the melody:
    for (int thisNote = 0; thisNote < 32; thisNote++) {
      changeLED();
      tone(BUZZER2, melody[thisNote],noteDuration);
      // to distinguish the notes, set a minimum time between them.
      // the note's duration + 30% seems to work well:
      int pauseBetweenNotes = noteDuration * 1.30;
      delay(pauseBetweenNotes);
      // stop the tone playing:
      noTone(BUZZER2);
    }
  }
}

// Each time this function is called the board moves to the next LED
void changeLED(void)
{
  setLEDs(1 << LEDnumber); // Change the LED

  LEDnumber++; // Goto the next LED
  if(LEDnumber > 3) LEDnumber = 0; // Wrap the counter if needed
}

What You Should See

Once the code is uploaded, the buzzer will beep a few times, and all four LEDs should begin blinking. The game begins once you press any of the four buttons. Once the game has been started, a random LED will blink. Press the button associated with that color LED to replicate the pattern. With a successful guess, the pattern will repeat, this time adding another random LED. The player is to follow the pattern for as long as possible, with each successful guess resulting in an additional layer of complexity added to the original pattern.

Galileo Simon Says

Real World Application

Toys and Games, such as the original Simon from Milton Bradley, have relied on electronics to provide fun and entertainment to children across the world.

Troubleshooting

Only Half the Circuit Works

If only half of you circuit is working, make sure you added the additional wire from one ground rail to the other. Remember that breadboards have two power rails on each side and that these can be connected, or bussed, together to provide the power to both sides of the same circuit.

No Sound

Once the piezo buzzer is in the breadboard, it’s hard to see the legs and to which row they are connected. If you aren’t hearing any sound, make sure your wires are on the same row as the piezo buzzer legs.

Game is Not Working

If everything starts up ok, but you’re having trouble when it comes time to play the game, you may have a button or two misplaced. Pay close attention to which pin is connected to each button as it matters which button is pressed when a particular color lights up.

Resources and Going Further

If you’ve gotten this far, you should be prepared enough to start designing your own Arduino/Intel® Galileo project. If you need a bit more, here are some of the resources we’ve found handy in experimenting with the board:

Going Further

If you’re looking for a little project inspiration, or just need more tutorials to devour, here are some related tutorials we’d suggest checking out:


learn.sparkfun.com |CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

e-Textile Mask

$
0
0

e-Textile Mask a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t306

Introduction

E-Textiles are a great way to add flair to your clothing and costumes but crafting on a garment can be a challenge for your first project. Making an accessory is a great way to explore sewing circuits on a smaller scale. This tutorial shows a mask with three LEDs but feel free to try other designs and patterns using more or less lights for a customized crafty creation!

More masks

Suggested Reading

If you’ve never worked with e-textiles before, you may want to have a look at these other tutorials.

Materials and Tools

Let’s go over all of the things you’ll need to sew your project together:

Supplies

You will also need:

  • Mask template - download and print the mask template. Template PDF
  • Felt - a 9x12 sheet of craft felt will make one mask. Try mixing colors for a more festive mask.
  • Scissors
  • Hot glue gun
  • Elastic cord or ribbon
  • Optional - extra craft supplies to decorate (feathers, sequins, buttons, etc).

Step One: Cut Out Template

Cut out the mask template pieces. Hold the template up to your face to make any adjustments to the eye or nose shapes so that it fits the way you like. Then trace the template pieces onto felt.

There are two layers - one for sewing on the electronics and a larger mask shape that will be glued on at the end to give it some extra support. Set aside the bigger mask shape for now. We’ll be sewing all of the electronics onto the top (smaller) mask shape.

Mask Template

To light up the mask we will be connecting the LEDs to the battery holder with conductive thread using a parallel circuit layout. This isn’t just a choice based on the look of the boards, it is actually an electrical plan as well! In a parallel circuit all of the components are aligned so that they get the same amount of voltage running through them. Each LED gets the same amount of power and shines just as brightly as the others. Use your printed template as a guideline for placement of the components.

Learn more about parallel circuits here: LDK Experiment 2: Multiple LED Circuits

Step Two: Place Components

Use a dot of hot glue on the back of the battery holder and glue to the top right corner of your mask, making sure the opening for the battery is facing up (see template). Arrange three LilyPad LEDs in a line across the top of the mask with all of the positive ends facing down and all of the negative ends facing up so that they line up with the positive and negative holes on the battery holder. Space them out over the eyebrow region of your mask to make an even pattern. Use a tiny dot of hot glue in the middle of the boards to help hold them onto your felt for sewing. Be careful not to cover the holes at the end of the boards or you won’t be able to get a needle through the dried glue.

Glue LEDsPlace LEDs

To help plan where the stitches will go you can use a marker to draw lines between the LEDs.Draw Lines

Step Three: Ready, Set, Sew!

If you need help sewing with conductive thread this tutorial covers the basics.

good and bad examples

Green = correct traces, Red = incorrect traces.

Using a long piece of conductive thread (~2 ft) begin sewing the positive ends of the LED to your battery holder in a line. You can use one piece of thread and sew along to the first LED, sew 3-4 stitches through the hole to secure and instead of knotting and cutting, continue on to the next LED and repeat until you’ve reached the end of the row. Then tie off and cut.

Sewing LEDs

Repeat for the negative sides with a separate piece of thread. Make sure each LED has 3-4 stitches around the hole to secure tightly before moving on.

Finished Sewing

Try a ‘wiggle test’ – if you can easily wiggle the LED back and forth after stitching it, the stitches are too loose and your connection isn’t secure.

Step Four: Test Your Circuit

Insert the coin cell battery into the battery holder with the positive (labeled) side facing up. Turn on the switch and see if your LED row shines brightly! If any of the LEDs aren’t illuminating, check your stitches to make sure they are tight. If not you can go in and sew with a bit of conductive thread over the connection point, holding the piece down tighter and making sure that your thread is touching both the board and the original sewn line.

This image from another tutorial shows how to place a battery in a LilyPad Battery Holder.alt text

Troubleshooting

With any electronics project there are times you will have to troubleshoot if your circuit isn’t working. If your circuit isn’t lighting up, try a new battery or check that your project is switched on. Check your sewing for any loose threads or ends that may be touching other parts of your circuit and causing a short circuit. See the picture for examples of conductive thread short circuits – practice tidy stitching to keep your thread from causing problems.

alt text

Read more about short circuits here - What Is a Circuit: Short and Open Circuits

Step Five: Customize Your Character

After you’ve checked your circuit it’s time to get creative with adding some details to your mask. First, glue the second layer of felt on the back of the mask to add some extra stability and to insulate the back of the circuit.

alt text

Cut small holes on either side of the mask with scissors or a hole punch and tie a string or piece of elastic to hold the mask on.

alt text

If you have craft supplies such as glitter, paint or other decorative accents you can add them to enhance or hide your LEDs and stitching. If you want to cover the battery holder on the front of the mask, using feathers or big buttons can be a nice flourish that adds pizzazz and hides the board. Make sure you leave a bit of room so you can replace the battery when necessary. Congratulations, you just created a blingin' e-textile accessory!

e-Textile Mask

Resources and Going Further

Things to try:

  • Brainstorm ways you could add LEDs in a parallel circuit without being in a straight line. Can you extend your traces so that you have LEDs around the eyes while still keeping the parallel circuit design?
  • Try this project with more than three LEDs. How bright can you get while still having room to sew the traces?

Further Reading:


learn.sparkfun.com |CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

FemtoBuck Constant Current LED Driver Hookup Guide

$
0
0

FemtoBuck Constant Current LED Driver Hookup Guide a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t307

Introduction

Product Image

The FemtoBuck is a small-size, single-output constant current LED driver. By default, the FemtoBuck is driven at 350mA. That current can be reduced by either presenting an analog voltage or a PWM signal to the board.

Suggested Reading

Here are some topics you should know before using the FemtoBuck. Have a look if you need more information.

FemtoBuck Overview

Connecting the FemtoBuck

For the FemtoBuck, we’ve increased the voltage ratings on the parts to allow the input voltage to cover the full 36V range of the AL8805. Note that the supply voltage must be at least 7V, and should be at least 2-3V higher than the forward voltage of the LED(s) to be driven.

Since the FemtoBuck is a constant current driver, the current drawn from the supply will drop as supply voltage rises. In general, efficiency of the FemtoBuck is around 95%, depending on the input voltage.

Signal hook-up diagram

One signal input is provided for dimming control. A ground pin (DGND) is provided to reference against the controlling module for accuracy. Dimming can be done by an analog voltage (20%-100% of max current by varying voltage from .5V-2.5V) or by PWM (so long as PWM minimum voltage is less than .4V and maximum voltage is more than 2.4V) for a full 0-100% range.

Another ground (PGND) pin is available next to the power supply pin to provide a high-current return path. The spacing on the four holes on the input side is 0.1" for standard headers.

The output side has a 0.1" spaced hole pair as well as a 3.5mm spaced hole pair, to allow the user to attach our 3.5mm screw terminals.

It is possible to increase the maximum current of the FemtoBuck board up to 1A per channel. To do so, replace the current sense resistor with smaller values. To calculate the new value for the resistor, use this formula:

ILED = 0.1 / Rset

Thus, for a 1A current, you’d want a 0.1Ω resistor. Don’t forget to be wary of current ratings; at 1A, the sense resistor will be dissipating 1/10W, so you probably want a resistor of at least 1/8W rating. The package is a standard 0805.

The “ears” on either end of the board allow you to use a zip tie to secure the wires to the board after soldering them down.

Finally, take note of the size of the FemtoBuck. If desired, the entire board can be slid into a piece of 9mm heat shrink tubing to provide insulation and strain relief.

Resources and Going Further

Consider checking out these other tutorials for more information about concepts in this guide:

  • Light - Covers some useful concepts, such as why doubling the current doesn’t appear to double the brightness.
  • Diodes - Diodes are a slightly more complex beast than resistors. Our diodes tutorial will help you understand why we need a special device to power them.
  • Pico Buck Hookup Guide - Need to control more LEDs? The PicoBuck is just like the FemtoBuck except it has three channels, each capable of providing 350mA. Perfect for controlling high powered RGB LEDS that require control of each color individually.

learn.sparkfun.com |CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

SIK Experiment Guide for Arduino - V3.2

$
0
0

SIK Experiment Guide for Arduino - V3.2 a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t310

Introduction: SIK RedBoard & Starter Kit

The SparkFun Inventor’s Guide is your map for navigating the waters of beginning embedded electronics. This guide contains all the information you will need to explore the 16 circuits of the SparkFun Inventor’s Kit for Arduino V3.2. At the center of this guide is one core philosophy - that anyone can (and should) play around with electronics. When you’re done with this guide, you’ll have the know-how to start creating your own projects and experiments. Now enough talking - let’s get inventing!

For Starter Kit for RedBoard - Programmed with Arduino users: For those who have Starter Kit for RedBoard - Programmed with Arduino, you are able to follow through experiments 1, 2, 3, 6, 7, 9, 10, and 11.

SparkFun Inventor’s Kit - V3.2

alt text

Here is all the parts in the SparkFun Inventor’s Kit for Arduino:

  • SparkFun RedBoard - Programmed with Arduino - The SparkFun RedBoard, fully assembled and tested
  • Arduino and Breadboard Holder - A nice holder for your RedBoard and breadboard
  • SparkFun Inventor’s Kit Guidebook - A printed manual that you follow along through all the experiments
  • Breadboard - Excellent for making circuits and connections off the Arduino.
  • Carrying Case - Take your kit anywhere with ease
  • SparkFun Mini Screwdriver - To help you screw on your RedBoard to the holder
  • 16x2 White on Black LCD (with headers) - This is a basic 16 character by 2 line display with a snazzy black background with white characters.
  • 74HC595 Shift Register- Simple shift register IC. Clock in data and latch it to free up IO pins on your RedBoard.
  • 2N2222 Transistors - This little transistor can help in your project by being used to help drive large loads or amplifying or switching applications.
  • 1N4148 Diodes - This is a very common signal diode - 1N4148. Use this for signals up to 200mA of current.
  • DC Motor with Gear - It works well for basic things like making a fan or spinning something pretty fast without much resistance.
  • Small Servo - Here is a simple, low-cost, high quality servo for all your mechatronic needs.
  • SPDT 5V Relay - This is a high quality Single Pole - Double Throw (SPDT) sealed relay. Use it to switch high voltage, and/or high current devices. This relay’s coil is rated up to 12V, with a minimum switching voltage of 5V.
  • TMP36 Temp Sensor - A sensor for detecting temperature changes.
  • Flex sensor - As the sensor is flexed, the resistance across the sensor increases.
  • Softpot - By pressing down on various parts of the strip, the resistance linearly changes from 100Ohms to 10,000Ohms allowing you to very accurately calculate the relative position on the strip.
  • SparkFun USB Mini-B Cable - This 6' cable provides you with a USB-A connector at the host end and mini-B connector at the device end.
  • Male to Male jumper wires - These are high quality wires that allow you to connect the female headers on the Arduino to the components and breadboard.
  • Photocell - A sensor to detect ambient light. Perfect for detecting when a drawer is opened or when night-time approaches.
  • Tri-Color LED - Because everyone loves a blinky.
  • Red, Blue, Yellow, and Green LEDs - Light emitting diodes make great general indicators.
  • Red, Blue, Yellow, and Green Tactile Buttons - Go crazy with different colored buttons
  • 10K Trimpot - Also known as a variable resistor, this is a device commonly used to control volume, contrast, and makes a great general user control input.
  • Piezo Buzzer - Use this to make sounds and play songs
  • 330 Ohm Resistors - Great current limiting resistors for LEDs, and strong pull-up resistors.
  • 10k Ohm Resistors - These make excellent pull-ups, pull-downs, and current limiters.

Starter Kit for RedBoard - Programmed with Arduino

If you’re new to electronics and programming, the Starter Kit for RedBoard is a great way for beginners to get their foot in the door. This little guy is essentially a mini SparkFun Inventor’s Kit (minus the manual which you can find below) and can be taken straight out of the box to help you make a slew of basic circuits.

Here is all the parts in the Starter Kit for RedBoard - V2:

Please note: This product is in the works, however you are able to follow along if you already have the Starter Kit for RedBoard for a lot of the experiments.

  • RedBoard - Programmed with Arduino - The SparkFun RedBoard, fully assembled and tested.
  • SparkFun USB Mini-B Cable - This 6' cable provides you with a USB-A connector at the host end and mini-B connector at the device end.
  • Breadboard - Excellent for making circuits and connections off the Arduino.
  • Male to Male jumper wires - These are high quality wires that allow you to connect the female headers on the Arduino to the components and breadboard.
  • Photocell - A sensor to detect ambient light. Perfect for detecting when a drawer is opened or when night-time approaches.
  • TMP36 Temp Sensor - A sensor for detecting temperature changes.
  • Tri-Color LED - Because everyone loves a blinky. Use this LED to PWM mix any color you need.
  • Basic LEDs - Light emitting diodes make great general indicators.
  • 10K Trimpot - Also known as a variable resistor, this is a device commonly used to control volume, contrast, and makes a great general user control input.
  • 12mm button - Because big buttons are easier to hit.
  • Small Servo - Here is a simple, low-cost, high quality servo for all your mechatronic needs.
  • 330 Ohm Resistors - Great current limiting resistors for LEDs, and strong pull-up resistors.
  • 10k Ohm Resistors - These make excellent pull-ups, pull-downs, and current limiters.

Experiment List

Please note: Experiments marked with **double asterisks** are for both the Starter Kit for RedBoard - Programmed with Arduino V2 (which is a future release) and the RedBoard SIK V3.2. Experiments without asterisks will only be available to those who purchased the RedBoard SIK V3.2.

In this SparkFun Inventor’s Kit for Arduino guide, you will learn the following:

What is the RedBoard platform?

The DIY Revolution

We live in a unique time where we have access to resources that allow us to create our own solutions and inventions. The DIY revolution is composed of hobbyists, tinkerers and inventors who would rather craft their own projects than let someone do it for them.

A Computer for the Physical World

The RedBoard in your hand (or on your desk) is your development platform. At its roots, the RedBoard is essentially a small portable computer. It is capable of taking inputs (such as the push of a button or a reading from a light sensor) and interpreting that information to control various outputs (like a blinking LED light or an electric motor).

That’s where the term “physical computing” is born - this board is capable of taking the world of electronics and relating it to the physical world in a real and tangible way. Trust us - this will all make more sense soon.

The SparkFun RedBoard is one of a multitude of development boards based on the ATmega328. It has 14 digital input/output pins (6 of which can be PWM outputs), 6 analog inputs, a 16 MHz crystal oscillator, a USB connection, a power jack, an ISP header, and a reset button. Check out our RedBoard Hookup Guide, to get yourself familiar with the RedBoard.

Download the Arduino IDE

In order to get your RedBoard up and running, you’ll need to download the newest version of the Arduino software first from www.arduino.cc (it’s free and open source!). This software, known as the Arduino IDE, will allow you to program the board to do exactly what you want. It’s like a word processor for writing programs. With an internet-capable computer, open up your favorite browser and go to Arduino download page.

Check out our Installing Arduino IDE tutorial, to see in detail on how to install the Arduino IDE on your computer.

Connect your RedBoard to your Computer

Use the USB cable provided in the SIK kit to connect the RedBoard to one of your computer’s USB inputs.

Install FTDI Drivers

Depending on your computer’s operating system, you will need to follow specific instructions. Please go to How to Install FTDI Drivers, for specific instructions on how to install the FTDI drivers onto your RedBoard.

Getting Started in the Arduino IDE

Now, it’s finally time to open up the Arduino software. You’ll be presented with a window that looks a little something like this:

Arduino IDE annotated

  1. Verify: Compiles and approves your code. It will catch errors in syntax (like missing semi-colons or parenthesis).
  2. Upload: Sends your code to the RedBoard. When you click it, you should see the lights on your board blink rapidly.
  3. New: This buttons opens up a new code window tab.
  4. Open: This button will let you open up an existing sketch.
  5. Save: This saves the currently active sketch.
  6. Serial Monitor: This will open a window that displays any serial information your RedBoard is transmitting. It is very useful for debugging.
  7. Sketch Name: This shows the name of the sketch you are currently working on.
  8. Code Area: This is the area where you compose the code for your sketch.
  9. Message Area: This is where the IDE tells you if there were any errors in your code.
  10. Text Console: The text console shows complete error messages. When debugging, the text console is very useful.
  11. Board and Serial Port: Shows you what board and the serial port selections

Select your board: Arduino Uno

Before we can start jumping into the experiments, there are a couple adjustments we need to make. This step is required to tell the Arduino IDE which of the many Arduino boards we have. Go up to the Tools menu. Then hover over Board and make sure Arduino Uno is selected.

Please note: Your SparkFun RedBoard and the Arduino UNO are interchangeable but you won’t find the RedBoard listed in the Arduino Software. Select “Arduino Uno” instead.

Arduino Select Arduino Uno board

Select a Serial Port

Next up we need to tell the Arduino IDE which of our computer’s serial ports the RedBoard is connected to. For this, again go up to Tools, then hover over Serial Port and select your RedBoard’s serial port.

Window Users: This is likely to be com3 or higher (COM1 and COM2 are usually reserved for hardware serial ports). To find out, you can disconnect your RedBoard and re-open the menu; the entry that disappears should be the RedBoard. Reconnect the board and select that serial port.

Port Selection

Mac Users: Select the serial device of the RedBoard from the Tools, then hover over Serial Port. On the Mac, this should be something with /dev/tty.usbmodem or /dev/tty.usbserial in it.

Mac user Arduino Serial Port

Linux Users: Please visit the Arduino Learning Linux section, to learn more about Arduino on Linux.

Download Arduino Code

You are so close to to being done with setup! Download the SIK Guide Code. Click the following link to download the code:

SIK Guide Code

Copy “SIK Guide Code” into “examples” folder in the Arduino folder.

Window Users: Unzip the file “SIK Guide Code”. It should be located in your browser’s “Downloads” folder. Right click the zipped folder and choose “unzip”. Copy the “SIK Guide Code” folder into Arduino’s folder named “examples”.

Mac Users: Unzip the file “SIK Guide Code”. It should be located in your browser’s “Downloads” folder. Right click the zipped folder and choose “unzip”. Find “Arduino” in your applications folder. Right click (ctrl + click) on “Arduino”. Select “Show Package Contents”. Then, click through folders Contents > Resources > Java > examples. Copy the “SIK Guide Code” folder into Arduino’s folder named “examples”.

Suggested Reading

Before continuing on with this tutorial, we recommend you be somewhat familiar with the concepts in the following tutorial:

  • How to Use a Breadboard - First time working with a breadboard? Please check out this tutorial! It will help you understand why the breadboard is a great for prototyping and how to use one.

Time for the fun part!

Continue on to the first experiment and in no time you will be blinking an LED!

Introduction: SIK Arduino Uno

The SparkFun Inventor’s Guide is your map for navigating the waters of beginning embedded electronics. This guide contains all the information you will need to explore the 16 circuits of the SparkFun Inventor’s Kit for Arduino. At the center of this guide is one core philosophy - that anyone can (and should) play around with electronics. When you’re done with this guide, you’ll have the know-how to start creating your own projects and experiments. Now enough talking - let’s get inventing!

alt text

SparkFun Inventor’s Kit with Arduino Uno R3

Here is all the parts in the SparkFun Inventor’s Kit for Arduino:

  • Arduino Uno R3 - The Arduino Uno is one of the more popular boards in the Arduino family and a great choice for beginners.
  • Arduino and Breadboard Holder - A nice holder for your RedBoard and breadboard
  • SparkFun Inventor’s Kit Guidebook - A printed manual that you follow along through all the experiments
  • Breadboard - Excellent for making circuits and connections off the Arduino.
  • Carrying Case - Take your kit anywhere with ease
  • SparkFun Mini Screwdriver - To help you screw on your RedBoard to the holder
  • 16x2 White on Black LCD (with headers) - This is a basic 16 character by 2 line display with a snazzy black background with white characters.
  • 74HC595 Shift Register- Simple shift register IC. Clock in data and latch it to free up IO pins on your RedBoard.
  • 2N2222 Transistors - This little transistor can help in your project by being used to help drive large loads or amplifying or switching applications.
  • 1N4148 Diodes - This is a very common signal diode - 1N4148. Use this for signals up to 200mA of current.
  • DC Motor with Gear - It works well for basic things like making a fan or spinning something pretty fast without much resistance.
  • Small Servo - Here is a simple, low-cost, high quality servo for all your mechatronic needs.
  • SPDT 5V Relay - This is a high quality Single Pole - Double Throw (SPDT) sealed relay. Use it to switch high voltage, and/or high current devices. This relay’s coil is rated up to 12V, with a minimum switching voltage of 5V.
  • TMP36 Temp Sensor - A sensor for detecting temperature changes.
  • Flex sensor - As the sensor is flexed, the resistance across the sensor increases
  • Softpot - By pressing down on various parts of the strip, the resistance linearly changes from 100Ohms to 10,000Ohms allowing you to very accurately calculate the relative position on the strip.
  • SparkFun USB Mini-B Cable - This 6' cable provides you with a USB-A connector at the host end and mini-B connector at the device end.
  • Male to Male jumper wires - These are high quality wires that allow you to connect the female headers on the Arduino to the components and breadboard.
  • Photocell - A sensor to detect ambient light. Perfect for detecting when a drawer is opened or when night-time approaches.
  • Tri-Color LED - Because everyone loves a blinky.
  • Red, Blue, Yellow, and Green LEDs - Light emitting diodes make great general indicators.
  • Red, Blue, Yellow, and Green Tactile Buttons - Go crazy with different colored buttons
  • 10K Trimpot - Also known as a variable resistor, this is a device commonly used to control volume, contrast, and makes a great general user control input.
  • Piezo Buzzer - Use this to make sounds and songs
  • 330 Ohm Resistors - Great current limiting resistors for LEDs, and strong pull-up resistors.
  • 10k Ohm Resistors - These make excellent pull-ups, pull-downs, and current limiters.

Experiment List

In this SparkFun Inventor’s Kit for Arduino guide, you will learn the following:

Please note: Got the Starter Kit for RedBoard - Programmed with Arduino? The experiments with the double asterisks you will want to follow along too.

What is the Arduino platform?

The DIY Revolution

We live in a unique time where we have access to resources that allow us to create our own solutions and inventions. The DIY revolution is composed of hobbyists, tinkerers and inventors who would rather craft their own projects than let someone do it for them.

A Computer for the Physical World

The Arduino in your hand (or on your desk) is your development platform. It is capable of taking inputs (such as the push of a button or a reading from a light sensor) and interpreting that information to control various outputs (like a blinking LED light or an electric motor).

That’s where the term “physical computing” is born - this board is capable of taking the world of electronics and relating it to the physical world in a real and tangible way. Trust us - this will all make more sense soon.

The Uno is a great choice for your first Arduino. It’s got everything you need to get started, and nothing you don’t. It has 14 digital input/output pins (of which 6 can be used as PWM outputs), 6 analog inputs, a USB connection, a power jack, a reset button and more. It contains everything needed to support the microcontroller; simply connect it to a computer with a USB cable or power it with a AC-to-DC adapter or battery to get started. Check out our What is an Arduino? tutorial, to learn more about Arduino.

Connect your Arduino Uno R3 to your Computer

Use the USB cable provided in the SIK kit to connect the Arduino Uno to one of your computer’s USB inputs.

Download the Arduino IDE

In order to get your Arduino Uno R3 up and running, you’ll need to download the newest version of the Arduino software first from www.arduino.cc (it’s free and open source!). This software, known as the Arduino IDE, will allow you to program the board to do exactly what you want. It’s like a word processor for writing programs. With an internet-capable computer, open up your favorite browser and go to Arduino download page.

Check out our Installing Arduino IDE tutorial, to see in detail on how to install the Arduino IDE on your computer.

Getting Started in the Arduino IDE

Now, it’s finally time to open up the Arduino software. You’ll be presented with a window that looks a little something like this:

Arduino IDE annotated

  1. Verify: Compiles and approves your code. It will catch errors in syntax (like missing semi-colons or parenthesis).
  2. Upload: Sends your code to the RedBoard. When you click it, you should see the lights on your board blink rapidly.
  3. New: This buttons opens up a new code window tab.
  4. Open: This button will let you open up an existing sketch.
  5. Save: This saves the currently active sketch.
  6. Serial Monitor: This will open a window that displays any serial information your RedBoard is transmitting. It is very useful for debugging.
  7. Sketch Name: This shows the name of the sketch you are currently working on.
  8. Code Area: This is the area where you compose the code for your sketch.
  9. Message Area: This is where the IDE tells you if there were any errors in your code.
  10. Text Console: The text console shows complete error messages. When debugging, the text console is very useful.
  11. Board and Serial Port: Shows you what board and the serial port selections

Before we can start jumping into the experiments, there are a couple adjustments we need to make.

Select your board: Arduino Uno

This step is required to tell the Arduino IDE which of the many Arduino boards we have. Go up to the Tools menu. Then hover over Board and make sure Arduino Uno is selected.

Arduino Select Arduino Uno board

Select a Serial Port

Next up we need to tell the Arduino IDE which of our computer’s serial ports the Arduino Uno R3 is connected to. For this, again go up to Tools, then hover over Serial Port and select your Arduino Uno R3’s serial port.

Port Selection

Window Users: This is likely to be com3 or higher (COM1 and COM2 are usually reserved for hardware serial ports). To find out, you can disconnect your Arduino Uno R3 and re-open the menu; the entry that disappears should be the Arduino Uno R3. Reconnect the board and select that serial port.

Mac Users: Select the serial device of the Arduino Uno R3 from the Tools, then hover over Serial Port. On the Mac, this should be something with /dev/tty.usbmodem or /dev/tty.usbserial in it.

Linux Users: Please visit the Arduino Learning Linux section, to learn more about Arduino on Linux.

Download Arduino Code

You are so close to to being done with setup! Download the SIK Guide Code. Click the following link to download the code:

SIK Guide Code

Copy “SIK Guide Code” into “examples” folder in the Arduino folder.

Window Users: Unzip the file “SIK Guide Code”. It should be located in your browser’s “Downloads” folder. Right click the zipped folder and choose “unzip”. Copy the “SIK Guide Code” folder into Arduino’s folder named “examples”.

Mac Users: Unzip the file “SIK Guide Code”. It should be located in your browser’s “Downloads” folder. Right click the zipped folder and choose “unzip”. Find “Arduino” in your applications folder. Right click (ctrl + click) on “Arduino”. Select “Show Package Contents”. Then, click through folders Contents > Resources > Java > examples. Copy the “SIK Guide Code” folder into Arduino’s folder named “examples”.

Linux Users: Please visit the Arduino Learning Linux section, to learn more about Arduino on Linux.

Suggested Reading

Before continuing on with this tutorial, we recommend you be somewhat familiar with the concepts in the following tutorial:

  • How to Use a Breadboard - First time working with a breadboard? Please check out this tutorial! It will help you understand why the breadboard is a great for prototyping and how to use one.

Time for the fun part!

Continue on to the first experiment and in no time you will be blinking an LED!

**Experiment 1: Blinking an LED**

Introduction

LEDs are small, powerful lights that are used in many different applications. To start off, we will work on blinking an LED, the Hello World of microcontrollers. That’s right - it’s as simple as turning a light on and off. It might not seem like much, but establishing this important baseline will give you a solid foundation as we work toward more complex experiments.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x RedBoard or Arduino Uno R3
  • 1x LED
  • 1x 330Ω Resistor
  • 2x Jumper Wires

Didn’t get the SIK?

If you are following through this experiment and didn’t get the SIK, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

In stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

In stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

1/6 Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 330Ohm resistors make excellent…

0.95
LED - Assorted (20 pack)

LED - Assorted (20 pack)

In stock COM-12062

We all know that you can never get too many LEDs. Don't worry, we've got you covered. This is a pack of basic red, yellow, bl…

2.95

You will also need either a RedBoard or Arduino Uno R3.

RedBoard - Programmed with Arduino

RedBoard - Programmed with Arduino

Only 5 left! DEV-12757

At SparkFun we use many Arduinos and we're always looking for the simplest, most stable one. Each board is a bit different an…

19.95
Arduino Uno- R3 SMD

Arduino Uno- R3 SMD

In stock DEV-11224

This is the new Arduino Uno R3. In addition to all the features of the previous board, the Uno now uses an ATmega16U2 instead…

29.95

Suggested Reading

Before continuing on with this experiment, we recommend you be familiar with the concepts in the following tutorial:

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram and hookup table below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components are highlighted with a yellow warning triangle, in the table. Polarized components can only be connected to a circuit in one direction.

Please note: Pay close attention to the LED. The negative side of the LED is the short leg, marked with a flat edge.

LED drawing

Components like resistors need to have their legs bent into 90° angles in order to correctly fit the breadboard sockets. You can also cut the legs shorter to make them easier to work with on the breadboard.

Bent resistor

Fritzing Diagram for RedBoard

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Fritzing Diagram for Arduino

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Hookup Table

ComponentRedBoard or Arduino Uno R3BreadboardBreadboard
c2 LED ( + )c3 LED ( - )
330 Resistora3( - )
Jumper WireGND( - )
Jumper WirePIN 13e2

In the table, polarized components are highlighted in yellow for the whole row and a warning triangle. Polarized components only be connected to a circuit in one direction.

Open Your First Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 1 by accessing the “SIK Guide Code” you downloaded and placed into your “examples” folder earlier.

To open the code go to: File > Examples > SIK Guide Code > Circuit_01

alt text

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Inventor's Kit
Example sketch 01

BLINKING A LED

  Turn an LED on for one second, off for one second,
  and repeat forever.

Hardware connections:

  Most Arduinos already have an LED and resistor connected to
  pin 13, so you may not need any additional circuitry.

  But if you'd like to connect a second LED to pin 13, or use
  a different pin, follow these steps:

    Connect the positive side of your LED (longer leg) to Arduino
    digital pin 13 (or another digital pin, don't forget to change
    the code to match).

    Connect the negative side of your LED (shorter leg) to a
    330 Ohm resistor (orange-orange-brown). Connect the other side
    of the resistor to ground.

    pin 13 _____ + LED - _____ 330 Ohm _____ GND

    (We always use resistors between the Arduino and and LEDs
    to keep the LEDs from burning out due to too much current.)

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/


// Welcome to Arduino!

// If you're brand-new to this, there will be some new things to
// learn, but we'll jump right in and explain things as we go.

// The Arduino is a tiny computer that runs programs called
// "sketches". These are text files written using instructions
// the computer understances. You're reading a sketch right now.

// Sketches have computer code in them, but also (hopefully)
// "comments" that explain what the code does. Comments and code
// will have different colors in the editor so you can tell them
// apart.

// This is a comment - anything on a line after "//" is ignored
// by the computer.

/* This is also a comment - this one can be multi-line, but it
must start and end with these characters */

// A "function" is a named block of code, that performs a specific,
// well, function. Many useful functions are already built-in to
// the Arduino; others you'll name and write yourself for your
// own purposes.

// All Arduino sketches MUST have two specific functions, named
// "setup()" and "loop()". The Arduino runs these functions
// automatically when it starts up or if you press the reset
// button. You'll typically fill these function "shells" with your
// own code. Let's get started!


// The setup() function runs once when the sketch starts.
// You'll use it for things you need to do first, or only once:


void setup()
{
  // The Arduino has 13 digital input/output pins. These pins
  // can be configured as either inputs or outputs. We set this
  // up with a built-in function called pinMode().

  // The pinMode() function takes two values, which you type in
  // the parenthesis after the function name. The first value is
  // a pin number, the second value is the word INPUT or OUTPUT.

  // Here we'll set up pin 13 (the one connected to a LED) to be
  // an output. We're doing this because we need to send voltage
  // "out" of the Arduino to the LED.

  pinMode(13, OUTPUT);

  // By the way, the Arduino offers many useful built-in functions
  // like this one. You can find information on all of them at the
  // Arduino website: http://arduino.cc/en/Reference
}


// After setup() finishes, the loop() function runs over and over
// again, forever (or until you turn off or reset the Arduino).
// This is usually where the bulk of your program lives:


void loop()
{
  // The 13 digital pins on your Arduino are great at inputting
  // and outputting on/off, or "digital" signals. These signals
  // will always be either 5 Volts (which we call "HIGH"), or
  // 0 Volts (which we call "LOW").

  // Because we have an LED connected to pin 13, if we make that
  // output HIGH, the LED will get voltage and light up. If we make
  // that output LOW, the LED will have no voltage and turn off.

  // digitalWrite() is the built-in function we use to make an
  // output pin HIGH or LOW. It takes two values; a pin number,
  // followed by the word HIGH or LOW:

  digitalWrite(13, HIGH);   // Turn on the LED

  // delay() is a function that pauses for a given amount of time.
  // It takes one value, the amount of time to wait, measured in
  // milliseconds. There are 1000 milliseconds in a second, so if
  // you delay(1000), it will pause for exactly one second:

  delay(1000);              // Wait for one second

  digitalWrite(13, LOW);    // Turn off the LED

  delay(1000);              // Wait for one second

  // All together, the above code turns the LED on, waits one
  // second, turns it off, and waits another second.

  // When the computer gets to the end of the loop() function,
  // it starts loop() over again. So this program will continue
  // blinking the LED on and off!

  // Try changing the 1000 in the above delay() functions to
  // different numbers and see how it affects the timing. Smaller
  // values will make the loop run faster. (Why?)
}

Code to Note

pinMode(13, OUTPUT);

Before you can use one of the Arduino’s pins, you need to tell the RedBoard or Arduino Uno R3 whether it is an INPUT or OUTPUT. We use a built-in “function” called pinMode() to do this.

digitalWrite(13, HIGH);

When you’re using a pin as an OUTPUT, you can command it to be HIGH (output 5 volts), or LOW (output 0 volts).

What You Should See

You should see your LED blink on and off. If it isn’t, make sure you have assembled the circuit correctly and verified and uploaded the code to your board, or see the troubleshooting section.

Real World Application

Almost all modern flat screen televisions and monitors have LED indicator lights to show they are on or off.

alt text

Troubleshooting

Program Not Uploading

This happens sometimes, the most likely cause is a confused serial port, you can change this in tools > serial port >

Still No Success?

A broken circuit is no fun, send us an e-mail and we will get back to you as soon as we can: techsupport@sparkfun.com

**Experiment 2: Reading a Potentiometer**

Introduction

In this circuit you’ll work with a potentiometer.

A potentiometer is also known as a variable resistor. When powered with 5V, the middle pin outputs a voltage between 0V and 5V, depending on the position of the knob on the potentiometer. A potentiometer is a perfect demonstration of a variable voltage divider circuit. The voltage is divided proportionate to the resistance between the middle pin and the ground pin. In this circuit, you’ll learn how to use a potentiometer to control the brightness of an LED.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x RedBoard or Arduino Uno
  • 1x LED
  • 1x 330Ω Resistor
  • 6x Jumper Wires
  • 1x Potentiometer

Didn’t get the SIK?

If you are following through this experiment and didn’t get the SIK, we suggest using these parts:

Trimpot 10K with Knob

Trimpot 10K with Knob

In stock COM-09806

There are lots of trimpots out there. Some are very large, some so small they require a screwdriver. Here at SparkFun, we jus…

0.95
Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

In stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

In stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

1/6 Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 330Ohm resistors make excellent…

0.95
LED - Assorted (20 pack)

LED - Assorted (20 pack)

In stock COM-12062

We all know that you can never get too many LEDs. Don't worry, we've got you covered. This is a pack of basic red, yellow, bl…

2.95

You will also need either the RedBoard or Arduino Uno R3.

RedBoard - Programmed with Arduino

RedBoard - Programmed with Arduino

Only 5 left! DEV-12757

At SparkFun we use many Arduinos and we're always looking for the simplest, most stable one. Each board is a bit different an…

19.95
Arduino Uno- R3 SMD

Arduino Uno- R3 SMD

In stock DEV-11224

This is the new Arduino Uno R3. In addition to all the features of the previous board, the Uno now uses an ATmega16U2 instead…

29.95

Suggested Reading

Before continuing on with this experiment, we recommend you be familiar with the concepts in the following tutorial:

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram and hookup table below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components only be connected to a circuit in one direction.

Fritzing Diagram for RedBoard

RedBoard Fritzing Potentiometer

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Fritzing Diagram for Arduino

Arduino Uno Fritzing Potentiometer

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Hookup Table

ComponentRedBoard or Arduino Uno R3BreadboardBreadboardBreadboard
330 Resistorj21( - )
h20 | LED ( + )h21 | LED ( - )
Potentiometera6a7a8
Jumper Wiree6( - )
Jumper WireA0e7
Jumper Wiree8( + )
Jumper WirePIN 13j20
Jumper Wire5V( + )
Jumper WireGND( - )

In the table, polarized components are highlighted in yellow for the whole row and a warning triangle. Polarized components only be connected to a circuit in one direction.

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 2 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > examples > SIK Guide Code > Circuit_02

Copy and paste the following code into the Arduino IDE. Hit upload and see what happens!

language:cpp
/* SparkFun Inventor's Kit
Example sketch 02

POTENTIOMETER

  Measure the position of a potentiometer and use it to
  control the blink rate of an LED. Turn the knob to make
  it blink faster or slower!

What's a potentiometer?

  A potentiometer, or "pot" for short, is a control knob.
  It's the same type of control you'd use to change volume,
  dim a lamp, etc. A potentiometer changes resistance as it
  is turned. By using it as a "voltage divider", the Arduino
  can sense the position of the knob, and use that value to
  control whatever you wish (like the blink rate of an LED,
  as we're doing here).

Hardware connections:

  Potentiometer:

    Potentiometers have three pins. When we're using it as a
    voltage divider, we connect the outside pins to power and
    ground. The middle pin will be the signal (a voltage which
    varies from 0 Volts to 5 Volts depending on the position of
    the knob).

    Connect the middle pin to ANALOG IN pin 0 on the Galileo.
    Connect one of the outside pins to 5V.
    Connect the other outside pin to GND.

    (TIP: if once your program is running, the knob feels
    "backwards", you can swap the 5V and GND pins to reverse
    the direction.)

  LED:

    Most Arduinos already have an LED and resistor connected to
    pin 13, so you may not need any additional circuitry.

    But if you'd like to connect a second LED to pin 13, or use
    a different pin, follow these steps:

      Connect the positive side of your LED (longer leg) to
      Arduino digital pin 13 (or another digital pin, but don't
      forget to change the code to match).

      Connect the negative side of your LED (shorter leg) to a
      330 Ohm resistor (orange-orange-brown).

      Connect the other side of the resistor to ground.

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/


// Welcome back! In this sketch we'll start using "variables".

// A variable is a named number. We'll often use these to store
// numbers that change, such as measurements from the outside
// world, or to make a sketch easier to understand (sometimes a
// descriptive name makes more sense than looking at a number).

// Variables can be different "data types", which is the kind of
// number we're using (can it be negative? Have a decimal point?)
// We'll introduce more data types later, but for the moment we'll
// stick with good old "integers" (called "int" in your sketch).

// Integers are whole numbers (0, 3, 5643), can be negative, and
// for reasons we won't go into right now, can range from -32768
// to 32767. (Don't worry, if you need to work with larger numbers,
// there are other data types for that. See:
// http://arduino.cc/en/Reference/VariableDeclaration
// for a list of all the data types you can use).

// You must "declare" variables before you use them, so that the
// computer knows about them. Here we'll declare two integer
// variables, and at the same time, initialize them to specific
// values. We're doing this so that further down, we can refer to
// the pins by name rather than number.

// Note that variable names are case-sensitive! If you get an
// "(variable) was not declared in this scope" error, double-check
// that you typed the name correctly.

// Here we're creating a variable called "sensorPin" of type "int"
// and initializing it to have the value "0":

int sensorPin = 0;    // The potentiometer is connected to
                      // analog pin 0

int ledPin = 13;      // The LED is connected to digital pin 13

// One more thing. If you declare variables outside of a function,
// as we have here, they are called "global variables" and can be
// seen by all the functions. If you declare variables within a
// function, they can only be seen within that function. It's good
// practice to "limit the scope" of a variable whenever possible,
// but as we're getting started, global variables are just fine.


void setup() // this function runs once when the sketch starts up
{
  // We'll be using pin 13 to light a LED, so we must configure it
  // as an output.

  // Because we already created a variable called ledPin, and
  // set it equal to 13, we can use "ledPin" in place of "13".
  // This makes the sketch easier to follow.

  pinMode(ledPin, OUTPUT);

  // The above line is the same as "pinMode(13, OUTPUT);"

  // You might be wondering why we're not also configuring
  // sensorPin as an input. The reason is that this is an
  // "analog in" pin. These pins have the special ability to
  // read varying voltages from sensors like the potentiometer.
  // Since they're always used as inputs, there is no need to
  // specifically configure them.
}


void loop() // this function runs repeatedly after setup() finishes
{
  // First we'll declare another integer variable
  // to store the value of the potentiometer:

  int sensorValue;

  // The potentiometer is set up as a voltage divider, so that
  // when you turn it, the voltage on the center pin will vary
  // from 0V to 5V. We've connected the center pin on the
  // potentiometer to the Arduino's analog input 0.

  // The Arduino can read external voltages on the analog input
  // pins using a built-in function called analogRead(). This
  // function takes one input value, the analog pin we're using
  // (sensorPin, which we earlier set to 0). It returns an integer
  // number that ranges from 0 (0 Volts) to 1023 (5 Volts).
  // We're sticking this value into the sensorValue variable:

  sensorValue = analogRead(sensorPin);

  // Now we'll blink the LED like in the first example, but we'll
  // use the sensorValue variable to change the blink speed
  // (the smaller the number, the faster it will blink).

  // Note that we're using the ledPin variable here as well:

  digitalWrite(ledPin, HIGH);     // Turn the LED on

  delay(sensorValue);             // Pause for sensorValue
                                  // milliseconds

  digitalWrite(ledPin, LOW);      // Turn the LED off

  delay(sensorValue);             // Pause for sensorValue
                                  // milliseconds

  // Remember that loop() repeats forever, so we'll do all this
  // again and again.
}

Code To Note

int sensorValue;

A “variable” is a placeholder for values that may change in your code. You must introduce, or “declare” variables before you use them; here we’re declaring a variable called sensorValue, of type “int” (integer). Don’t forget that variable names are case-sensitive!

sensorValue = analogRead(sensorPin);

We use the analogRead() function to read the value on an analog pin. analogRead() takes one parameter, the analog pin you want to use (“sensorPin”), and returns a number (“sensorValue”) between 0 (0 volts) and 1023 (5 volts).

delay(sensorValue);

Microcontrollers are very fast, capable of running thousands of lines of code each second. To slow it down so that we can see what it’s doing, we’ll often insert delays into the code. delay() counts in milliseconds; there are 1000 ms in one second.

What You Should See

You should see the LED blink faster or slower in accordance with your potentiometer. If it isn’t working, make sure you have assembled the circuit correctly and verified and uploaded the code to your board, or see the troubleshooting section.

Real World Application

Most traditional volume knobs employ a potentiometer.

Troubleshooting

Sporadically Working

This is most likely due to a slightly dodgy connection with the potentiometer’s pins. This can usually be conquered by holding the potentiometer down.

Not Working

Make sure you haven’t accidentally connected the wiper, the resistive element in the potentiometer, to digital pin 0 rather than analog pin 0. (the row of pins beneath the power pins).

LED Not Lighting Up?

LEDs will only work in one direction. Double check your connections.

**Experiment 3: Driving and RGB LED**

Introduction

You know what’s even more fun than a blinking LED? Changing colors with one LED. RGB, or red-green-blue, LEDs have three different color-emitting diodes that can be combined to create all sorts of colors. In this circuit, you’ll learn how to use an RGB LED to create unique color combinations. Depending on how bright each diode is, nearly any color is possible!

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x RedBoard or Arduino Uno
  • 1x LED - RGB Common Cathode
  • 3x 330Ω Resistors
  • 5x Jumper Wires

Didn’t get the SIK?

If you are following through this experiment and didn’t get the SIK, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

In stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
LED - RGB Clear Common Cathode

LED - RGB Clear Common Cathode

In stock COM-00105

Ever hear of a thing called RGB? Red, Green, Blue? How about an RGB LED? These 5mm units have four pins - Cathode is the long…

1.95
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

In stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

1/6 Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 330Ohm resistors make excellent…

0.95

You will also need either the RedBoard or Arduino Uno R3.

RedBoard - Programmed with Arduino

RedBoard - Programmed with Arduino

Only 5 left! DEV-12757

At SparkFun we use many Arduinos and we're always looking for the simplest, most stable one. Each board is a bit different an…

19.95
Arduino Uno- R3 SMD

Arduino Uno- R3 SMD

In stock DEV-11224

This is the new Arduino Uno R3. In addition to all the features of the previous board, the Uno now uses an ATmega16U2 instead…

29.95

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram and hookup table below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components are highlighted with a yellow warning triangle, in the table. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram for RedBoard

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Fritzing Diagram for Arduino

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Hookup Table

ComponentRedBoard or Arduino Uno R3BreadboardBreadboardBreadboardBreadboard
j2 (RED)j3 (GND)j4 (GREEN)j5 (BLUE)
330 Resistord2f2
330 Resistord4f4
330 Resistord5f5
Jumper WireGND( - )
Jumper WirePIN 9a2
Jumper Wiref3( - )
Jumper WirePIN 10a4
Jumper WirePIN 11a5

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 3 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > examples > SIK Guide Code > Circuit_03

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Inventor's Kit
Example sketch 03

RGB LED

Make an RGB LED display a rainbow of colors!

Hardware connections:

An RGB LED is actually three LEDs (red, green, and blue) in
one package. When you run them at different brightnesses,
the red, green and blue mix to form new colors.

Starting at the flattened edge of the flange on the LED,
the pins are ordered RED, COMMON, GREEN, BLUE.

Connect RED to a 330 ohm resistor. Connect the other end
of the resistor to Arduino digital pin 9.

Connect COMMON pin to GND.

Connect GREEN to a 330 ohm resistor. Connect the other end
of the resistor to Arduino digital pin 10.

Connect BLUE to a 330 ohm resistor. Connect the other end
of the resistor to Arduino digital pin 11.

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/


// First we'll define the pins by name to make the sketch
// easier to follow.

// Here's a new trick: putting the word "const" in front of a
// variable indicates that this is a "constant" value that will
// never change. (You don't have to do this, but if you do, the
// Arduino will give you a friendly warning if you accidentally
// try to change the value, so it's considered good form.)

const int RED_PIN = 9;
const int GREEN_PIN = 10;
const int BLUE_PIN = 11;

// This variable controls how fast we loop through the colors.
// (Try changing this to make the fading faster or slower.)

int DISPLAY_TIME = 100;  // In milliseconds


void setup()
{
// Here we'll configure the Arduino pins we're using to
// drive the LED to be outputs:

pinMode(RED_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
pinMode(BLUE_PIN, OUTPUT);
}


void loop()
{
// In this sketch, we'll start writing our own functions.
// This makes the sketch easier to follow by dividing up
// the sketch into sections, and not having everything in
// setup() or loop().

// We'll show you two ways to run the RGB LED.

// The first way is to turn the individual LEDs (red, blue,
// and green) on and off in various combinations. This gives you
// a total of eight colors (if you count "black" as a color).

// We've written a function called mainColors() that steps
// through all eight of these colors. We're only "calling" the
// function here (telling it to run). The actual function code
// is further down in the sketch.

mainColors();

// The above function turns the individual LEDs full-on and
// full-off. If you want to generate more than eight colors,
// you can do so by varying the brightness of the individual
// LEDs between full-on and full-off.

// The analogWrite() function lets us do this. This function
// lets you dim a LED from full-off to full-on over 255 steps.

// We've written a function called showSpectrum() that smoothly
// steps through all the colors. Again we're just calling it
// here; the actual code is further down in this sketch.

showSpectrum();
}


// Here's the mainColors() function we've written.

// This function displays the eight "main" colors that the RGB LED
// can produce. If you'd like to use one of these colors in your
// own sketch, you cancopy and paste that section into your code.

void mainColors()
{
// Off (all LEDs off):

digitalWrite(RED_PIN, LOW);
digitalWrite(GREEN_PIN, LOW);
digitalWrite(BLUE_PIN, LOW);

delay(1000);

// Red (turn just the red LED on):

digitalWrite(RED_PIN, HIGH);
digitalWrite(GREEN_PIN, LOW);
digitalWrite(BLUE_PIN, LOW);

delay(1000);

// Green (turn just the green LED on):

digitalWrite(RED_PIN, LOW);
digitalWrite(GREEN_PIN, HIGH);
digitalWrite(BLUE_PIN, LOW);

delay(1000);

// Blue (turn just the blue LED on):

digitalWrite(RED_PIN, LOW);
digitalWrite(GREEN_PIN, LOW);
digitalWrite(BLUE_PIN, HIGH);

delay(1000);

// Yellow (turn red and green on):

digitalWrite(RED_PIN, HIGH);
digitalWrite(GREEN_PIN, HIGH);
digitalWrite(BLUE_PIN, LOW);

delay(1000);

// Cyan (turn green and blue on):

digitalWrite(RED_PIN, LOW);
digitalWrite(GREEN_PIN, HIGH);
digitalWrite(BLUE_PIN, HIGH);

delay(1000);

// Purple (turn red and blue on):

digitalWrite(RED_PIN, HIGH);
digitalWrite(GREEN_PIN, LOW);
digitalWrite(BLUE_PIN, HIGH);

delay(1000);

// White (turn all the LEDs on):

digitalWrite(RED_PIN, HIGH);
digitalWrite(GREEN_PIN, HIGH);
digitalWrite(BLUE_PIN, HIGH);

delay(1000);
}


// Below are two more functions we've written,
// showSpectrum() and showRGB().

// showRGB() displays a single color on the RGB LED.
// You call showRGB() with the number of a color you want
// to display.

// showSpectrum() steps through all the colors of the RGB LED,
// displaying a rainbow. showSpectrum() actually calls showRGB()
// over and over to do this.

// We'll often break tasks down into individual functions like
// this, which makes your sketches easier to follow, and once
// you have a handy function, you can reuse it in your other
// programs.


// showSpectrum()

// This function steps through all the colors of the RGB LED.
// It does this by stepping a variable from 0 to 768 (the total
// number of colors), and repeatedly calling showRGB() to display
// the individual colors.

// In this function, we're using a "for() loop" to step a variable
// from one value to another, and perform a set of instructions
// for each step. For() loops are a very handy way to get numbers
// to count up or down.

// Every for() loop has three statements separated by semicolons:

//   1. Something to do before starting

//   2. A test to perform; as long as it's true,
//      it will keep looping

//   3. Something to do after each loop (usually
//      increase a variable)

// For the for() loop below, these are the three statements:

//   1. x = 0;     Before starting, make x = 0.

//   2. x < 768;   While x is less than 768, run the
//                 following code.

//   3. x++        Putting "++" after a variable means
//                 "add one to it". (You can also use "x = x + 1")

// Every time you go through the loop, the statements following
// the loop (those within the brackets) will run.

// And when the test in statement 2 is finally false, the sketch
// will continue.


void showSpectrum()
{
int x;  // define an integer variable called "x"

// Now we'll use a for() loop to make x count from 0 to 767
// (Note that there's no semicolon after this line!
// That's because the for() loop will repeat the next
// "statement", which in this case is everything within
// the following brackets {} )

for (x = 0; x < 768; x++)

// Each time we loop (with a new value of x), do the following:

{
showRGB(x);  // Call RGBspectrum() with our new x
delay(10);   // Delay for 10 ms (1/100th of a second)
}
}


// showRGB()

// This function translates a number between 0 and 767 into a
// specific color on the RGB LED. If you have this number count
// through the whole range (0 to 767), the LED will smoothly
// change color through the entire spectrum.

// The "base" numbers are:
// 0   = pure red
// 255 = pure green
// 511 = pure blue
// 767 = pure red (again)

// Numbers between the above colors will create blends. For
// example, 640 is midway between 512 (pure blue) and 767
// (pure red). It will give you a 50/50 mix of blue and red,
// resulting in purple.

// If you count up from 0 to 767 and pass that number to this
// function, the LED will smoothly fade between all the colors.
// (Because it starts and ends on pure red, you can start over
// at 0 without any break in the spectrum).


void showRGB(int color)
{
int redIntensity;
int greenIntensity;
int blueIntensity;

// Here we'll use an "if / else" statement to determine which
// of the three (R,G,B) zones x falls into. Each of these zones
// spans 255 because analogWrite() wants a number from 0 to 255.

// In each of these zones, we'll calculate the brightness
// for each of the red, green, and blue LEDs within the RGB LED.

if (color <= 255)          // zone 1
{
redIntensity = 255 - color;    // red goes from on to off
greenIntensity = color;        // green goes from off to on
blueIntensity = 0;             // blue is always off
}
else if (color <= 511)     // zone 2
{
redIntensity = 0;                     // red is always off
greenIntensity = 255 - (color - 256); // green on to off
blueIntensity = (color - 256);        // blue off to on
}
else // color >= 512       // zone 3
{
redIntensity = (color - 512);         // red off to on
greenIntensity = 0;                   // green is always off
blueIntensity = 255 - (color - 512);  // blue on to off
}

// Now that the brightness values have been set, command the LED
// to those values

analogWrite(RED_PIN, redIntensity);
analogWrite(BLUE_PIN, blueIntensity);
analogWrite(GREEN_PIN, greenIntensity);
}

Code To Note

language:cpp
for (x = 0; x < 768; x++)
{}

A for() loop is used to repeat an action a set number of times across a range, and repeatedly runs code within the brackets {}. Here the variable “x” starts a 0, ends at 767, and increases by one each time (“x++”).

language:cpp
if (x <= 255)
{}
else
{}

“If / else” statements are used to make choices in your programs. The statement within the parenthesis () is evaluated; if it’s true, the code within the first brackets {} will run. If it’s not true, the code within the second brackets {} will run.

What You Should See

You should see your LED turn on, but this time in new, crazy colors! If it isn’t, make sure you have assembled the circuit correctly and verified and uploaded the code to your board or see the troubleshooting section.

Real World Application

Many electronics such as video game consoles use RGB LEDs to have the versatility to show different colors in the same area. Often times the different colors represent different states of working condition.

Troubleshooting

LED Remains Dark or Shows Incorrect Color

With the four pins of the LED so close together, it’s sometimes easy to misplace one. Double check each pin is where it should be.

Seeing Red

The red diode within the RGB LED may be a bit brighter than the other two. To make your colors more balanced, use a higher ohm resistor. Or adjust in code.

analogWrite(RED_PIN, redIntensity);

to

analogWrite(RED_PIN, redIntensity/3);

**Experiment 4: Driving Multiple LEDs**

Introduction

Now that you’ve gotten your LED to blink on and off, it’s time to up the stakes a little bit – by connecting eight LEDs at once. We’ll also give your RedBoard or Arduino R3 a little test by creating various lighting sequences. This circuit is a great setup to start practicing writing your own programs and getting a feel for the way Arduino works.

Along with controlling the LEDs, you’ll learn about a couple programming tricks that keep your code neat and tidy:

for() loops - used when you want to run a piece of code several times

arrays[ ] - used to make managing variables easier by grouping them together

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x RedBoard or Arduino Uno
  • 8x LEDs
  • 8x 330Ω Resistors
  • 9x Jumper Wires

Didn’t get the SIK?

If you are following through this experiment and didn’t get the SIK, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

In stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

In stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

1/6 Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 330Ohm resistors make excellent…

0.95
LED - Assorted (20 pack)

LED - Assorted (20 pack)

In stock COM-12062

We all know that you can never get too many LEDs. Don't worry, we've got you covered. This is a pack of basic red, yellow, bl…

2.95

You will also need either a RedBoard or Arduino Uno R3.

RedBoard - Programmed with Arduino

RedBoard - Programmed with Arduino

Only 5 left! DEV-12757

At SparkFun we use many Arduinos and we're always looking for the simplest, most stable one. Each board is a bit different an…

19.95
Arduino Uno- R3 SMD

Arduino Uno- R3 SMD

In stock DEV-11224

This is the new Arduino Uno R3. In addition to all the features of the previous board, the Uno now uses an ATmega16U2 instead…

29.95

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram and hookup table below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram for RedBoard

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Fritzing Diagram for Arduino

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 4 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > examples > SIK Guide Code > Circuit_04

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Inventor's Kit
Example sketch 04

MULTIPLE LEDs

  Make eight LEDs dance. Dance LEDs, dance!

Hardware connections:

  You'll need eight LEDs, and eight 330 Ohm resistors
  (orange-orange-brown).

    For each LED, connect the negative side (shorter leg)
    to a 330 Ohm resistor.

    Connect the other side of the resistors to GND.

    Connect the positive side (longer leg) of the LEDs
    to Arduino digital pins 2 through 9.

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/


// To keep track of all the LED pins, we'll use an "array".
// An array lets you store a group of variables, and refer to them
// by their position, or "index". Here we're creating an array of
// eight integers, and initializing them to a set of values:

int ledPins[] = {2,3,4,5,6,7,8,9};

// The first element of an array is index 0.
// We've put the value "2" in index 0, "3" in index 1, etc.
// The final index in the above array is 7, which contains
// the value "9".

// We're using the values in this array to specify the pin numbers
// that the eight LEDs are connected to. LED 0 is connected to
// pin 2, LED 1 is connected to pin 3, etc.


void setup()
{
  int index;

  // In this sketch, we'll use "for() loops" to step variables from
  // one value to another, and perform a set of instructions for
  // each step. For() loops are a very handy way to get numbers to
  // count up or down.

  // Every for() loop has three statements separated by
  // semicolons (;):

  //   1. Something to do before starting
  //   2. A test to perform; as long as it's true, keep looping
  //   3. Something to do after each loop (increase a variable)

  // For the for() loop below, these are the three statements:

  //   1. index = 0;    Before starting, make index = 0.
  //   2. index <= 7;   If index is less or equal to 7,
  //                    run the following code.
  //            (When index = 8, continue with the sketch.)
  //   3. index++   Putting "++" after a variable means
  //                    "add one to it".
  //            (You can also use "index = index + 1".)

  // Every time you go through the loop, the statements following
  // the for() (within the brackets) will run.

  // When the test in statement 2 is finally false, the sketch
  // will continue.


  // Here we'll use a for() loop to initialize all the LED pins
  // to outputs. This is much easier than writing eight separate
  // statements to do the same thing.

  // This for() loop will make index = 0, then run the pinMode()
  // statement within the brackets. It will then do the same thing
  // for index = 2, index = 3, etc. all the way to index = 7.

  for(index = 0; index <= 7; index++)
  {
    pinMode(ledPins[index],OUTPUT);
    // ledPins[index] is replaced by the value in the array.
    // For example, ledPins[0] is 2
  }
}


void loop()
{
  // This loop() calls functions that we've written further below.
  // We've disabled some of these by commenting them out (putting
  // "//" in front of them). To try different LED displays, remove
  // the "//" in front of the ones you'd like to run, and add "//"
  // in front of those you don't to comment out (and disable) those
  // lines.

  oneAfterAnotherNoLoop();  // Light up all the LEDs in turn

  //oneAfterAnotherLoop();  // Same as oneAfterAnotherNoLoop,
                            // but with much less typing

  //oneOnAtATime();         // Turn on one LED at a time,
                            // scrolling down the line

  //pingPong();             // Light the LEDs middle to the edges

  //marquee();              // Chase lights like you see on signs

  //randomLED();            // Blink LEDs randomly
}


/*
oneAfterAnotherNoLoop()

This function will light one LED, delay for delayTime, then light
the next LED, and repeat until all the LEDs are on. It will then
turn them off in the reverse order.

This function does NOT use a for() loop. We've done it the hard way
to show you how much easier life can be when you use for() loops.
Take a look at oneAfterAnotherLoop() further down, which does
exactly the same thing with much less typing.
*/

void oneAfterAnotherNoLoop()
{
  int delayTime = 100; // time (milliseconds) to pause between LEDs
                       // make this smaller for faster switching

  // turn all the LEDs on:

  digitalWrite(ledPins[0], HIGH);  //Turns on LED #0 (pin 2)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[1], HIGH);  //Turns on LED #1 (pin 3)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[2], HIGH);  //Turns on LED #2 (pin 4)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[3], HIGH);  //Turns on LED #3 (pin 5)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[4], HIGH);  //Turns on LED #4 (pin 6)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[5], HIGH);  //Turns on LED #5 (pin 7)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[6], HIGH);  //Turns on LED #6 (pin 8)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[7], HIGH);  //Turns on LED #7 (pin 9)
  delay(delayTime);                //wait delayTime milliseconds

  // turn all the LEDs off:

  digitalWrite(ledPins[7], LOW);   //Turn off LED #7 (pin 9)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[6], LOW);   //Turn off LED #6 (pin 8)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[5], LOW);   //Turn off LED #5 (pin 7)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[4], LOW);   //Turn off LED #4 (pin 6)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[3], LOW);   //Turn off LED #3 (pin 5)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[2], LOW);   //Turn off LED #2 (pin 4)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[1], LOW);   //Turn off LED #1 (pin 3)
  delay(delayTime);                //wait delayTime milliseconds
  digitalWrite(ledPins[0], LOW);   //Turn off LED #0 (pin 2)
  delay(delayTime);                //wait delayTime milliseconds
}


/*
oneAfterAnotherLoop()

This function does exactly the same thing as oneAfterAnotherNoLoop(),
but it takes advantage of for() loops and the array to do it with
much less typing.
*/

void oneAfterAnotherLoop()
{
  int index;
  int delayTime = 100; // milliseconds to pause between LEDs
                       // make this smaller for faster switching

  // Turn all the LEDs on:

  // This for() loop will step index from 0 to 7
  // (putting "++" after a variable means add one to it)
  // and will then use digitalWrite() to turn that LED on.

  for(index = 0; index <= 7; index++)
  {
    digitalWrite(ledPins[index], HIGH);
    delay(delayTime);
  }

  // Turn all the LEDs off:

  // This for() loop will step index from 7 to 0
  // (putting "--" after a variable means subtract one from it)
  // and will then use digitalWrite() to turn that LED off.

  for(index = 7; index >= 0; index--)
  {
    digitalWrite(ledPins[index], LOW);
    delay(delayTime);
  }
}


/*
oneOnAtATime()

This function will step through the LEDs,
lighting only one at at time.
*/

void oneOnAtATime()
{
  int index;
  int delayTime = 100; // milliseconds to pause between LEDs
                       // make this smaller for faster switching

  // step through the LEDs, from 0 to 7

  for(index = 0; index <= 7; index++)
  {
    digitalWrite(ledPins[index], HIGH);  // turn LED on
    delay(delayTime);                    // pause to slow down
    digitalWrite(ledPins[index], LOW);   // turn LED off
  }
}


/*
pingPong()

This function will step through the LEDs,
lighting one at at time in both directions.
*/

void pingPong()
{
  int index;
  int delayTime = 100; // milliseconds to pause between LEDs
                       // make this smaller for faster switching

  // step through the LEDs, from 0 to 7

  for(index = 0; index <= 7; index++)
  {
    digitalWrite(ledPins[index], HIGH);  // turn LED on
    delay(delayTime);                    // pause to slow down
    digitalWrite(ledPins[index], LOW);   // turn LED off
  }

  // step through the LEDs, from 7 to 0

  for(index = 7; index >= 0; index--)
  {
    digitalWrite(ledPins[index], HIGH);  // turn LED on
    delay(delayTime);                    // pause to slow down
    digitalWrite(ledPins[index], LOW);   // turn LED off
  }
}


/*
marquee()

This function will mimic "chase lights" like those around signs.
*/

void marquee()
{
  int index;
  int delayTime = 200; // milliseconds to pause between LEDs
                       // Make this smaller for faster switching

  // Step through the first four LEDs
  // (We'll light up one in the lower 4 and one in the upper 4)

  for(index = 0; index <= 3; index++) // Step from 0 to 3
  {
    digitalWrite(ledPins[index], HIGH);    // Turn a LED on
    digitalWrite(ledPins[index+4], HIGH);  // Skip four, and turn that LED on
    delay(delayTime);                      // Pause to slow down the sequence
    digitalWrite(ledPins[index], LOW);     // Turn the LED off
    digitalWrite(ledPins[index+4], LOW);   // Skip four, and turn that LED off
  }
}


/*
randomLED()

This function will turn on random LEDs. Can you modify it so it
also lights them for random times?
*/

void randomLED()
{
  int index;
  int delayTime;

  // The random() function will return a semi-random number each
  // time it is called. See http://arduino.cc/en/Reference/Random
  // for tips on how to make random() even more random.

  index = random(8);    // pick a random number between 0 and 7
  delayTime = 100;

  digitalWrite(ledPins[index], HIGH);  // turn LED on
  delay(delayTime);                    // pause to slow down
  digitalWrite(ledPins[index], LOW);   // turn LED off
}

Code To Note

int ledPins[] = {2,3,4,5,6,7,8,9};

When you have to manage a lot of variables, an “array” is a handy way to group them together. Here we’re creating an array of integers, called ledPins, with eight elements.

digitalWrite(ledPins[0], HIGH);

You refer to the elements in an array by their position. The first element is at position 0, the second is at position 1, etc. You refer to an element using “ledPins[x]” where x is the position. Here we’re making digital pin 2 HIGH, since the array element at position 0 is “2”.

index = random(8);

Computers like to do the same things each time they run. But sometimes you want to do things randomly, such as simulating the roll of a dice. The random() function is a great way to do this. See http://arduino.cc/en/reference/random for more information.

What You Should See

This is similar to circuit number one, but instead of one LED, you should see all the LEDs blink. If they aren’t, make sure you have assembled the circuit correctly and verified and uploaded the code to your board, or see the troubleshooting section.

Real World Application

Scrolling marquee displays are generally used to spread short segments of important information. They are built out of many LEDs.

Troubleshooting

Some LEDs Fail to Light

It is easy to insert an LED backwards. Check the LEDs that aren’t working and ensure they are in the correct orientation.

Operating out of sequence

With eight wires it’s easy to cross a couple. Double check that the first LED is plugged into pin 2 and each pin thereafter.

Starting Fresh

It’s easy to accidentally misplace a wire without noticing. Pulling everything out and starting with a fresh slate is often easier than trying to track down the problem.

**Experiment 5: Push Buttons**

Introduction

Up until now, we’ve focused mostly on outputs. Now we’re going to go to the other end of spectrum and play around with inputs. In experiment 2, we used an analog input to read the potentiometer. In this circuit, we’ll be reading in one of the most common and simple inputs – a push button – by using a digital input. The way a push button works with your RedBoard or Arduino Uno R3 is that when the button is pushed, the voltage goes LOW. You RedBoard or Arduino Uno R3 reads this and reacts accordingly.

In this circuit, you will also use a pull-up resistor, which keeps the voltage HIGH when you’re not pressing the button.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x RedBoard or Arduino Uno
  • 1x LED
  • 1x 330Ω Resistor
  • 7x Jumper Wires
  • 2x Push Buttons
  • 2x 10k Resistors

Didn’t get the SIK?

If you are following through this experiment and didn’t get the SIK, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

In stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Tactile Button Assortment

Tactile Button Assortment

In stock COM-10302

These tactile buttons are great for all sorts of projects. This assortment comes with 2 of each of 6 different colors for a t…

4.95
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

In stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

1/6 Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 330Ohm resistors make excellent…

0.95
LED - Assorted (20 pack)

LED - Assorted (20 pack)

In stock COM-12062

We all know that you can never get too many LEDs. Don't worry, we've got you covered. This is a pack of basic red, yellow, bl…

2.95
Resistor 10K Ohm 1/6th Watt PTH - 20 pack

Resistor 10K Ohm 1/6th Watt PTH - 20 pack

In stock COM-11508

1/6th Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 10K resistors make excellent …

0.95

You will also need either a RedBoard or Arduino Uno R3.

RedBoard - Programmed with Arduino

RedBoard - Programmed with Arduino

Only 5 left! DEV-12757

At SparkFun we use many Arduinos and we're always looking for the simplest, most stable one. Each board is a bit different an…

19.95
Arduino Uno- R3 SMD

Arduino Uno- R3 SMD

In stock DEV-11224

This is the new Arduino Uno R3. In addition to all the features of the previous board, the Uno now uses an ATmega16U2 instead…

29.95

Suggested Reading

Before continuing on with this tutorial, we recommend you be somewhat familiar with the concepts in these tutorials:

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram for RedBoard

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Fritzing Diagram for Arduino

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 5 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > examples > SIK Guide Code > Circuit_05

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Inventor's Kit
Example sketch 05

PUSH BUTTONS

  Use pushbuttons for digital input

  Previously we've used the analog pins for input, now we'll use
  the digital pins for input as well. Because digital pins only
  know about HIGH and LOW signals, they're perfect for interfacing
  to pushbuttons and switches that also only have "on" and "off"
  states.

  We'll connect one side of the pushbutton to GND, and the other
  side to a digital pin. When we press down on the pushbutton,
  the pin will be connected to GND, and therefore will be read
  as "LOW" by the Arduino.

  But wait - what happens when you're not pushing the button?
  In this state, the pin is disconnected from everything, which
  we call "floating". What will the pin read as then, HIGH or LOW?
  It's hard to say, because there's no solid connection to either
  5 Volts or GND. The pin could read as either one.

  To deal with this issue, we'll connect a small (10K, or 10,000 Ohm)
  resistance between the pin and 5 Volts. This "pullup" resistor
  will ensure that when you're NOT pushing the button, the pin will
  still have a weak connection to 5 Volts, and therefore read as
  HIGH.

  (Advanced: when you get used to pullup resistors and know when
  they're required, you can activate internal pullup resistors
  on the ATmega processor in the Arduino. See
  http://arduino.cc/en/Tutorial/DigitalPins for information.)

Hardware connections:

  Pushbuttons:

    Pushbuttons have two contacts that are connected if you're
    pushing the button, and disconnected if you're not.

    The pushbuttons we're using have four pins, but two pairs
    of these are connected together. The easiest way to hook up
    the pushbutton is to connect two wires to any opposite corners.

    Connect any pin on pushbutton 1 to ground (GND).
    Connect the opposite diagonal pin of the pushbutton to
    digital pin 2.

    Connect any pin on pushbutton 2 to ground (GND).
    Connect the opposite diagonal pin of the pushbutton to
    digital pin 3.

    Also connect 10K resistors (brown/black/red) between
    digital pins 2 and 3 and GND. These are called "pullup"
    resistors. They ensure that the input pin will be either
    5V (unpushed) or GND (pushed), and not somewhere in between.
    (Remember that unlike analog inputs, digital inputs are only
    HIGH or LOW.)

  LED:

    Most Arduinos, including the Uno, already have an LED
    and resistor connected to pin 13, so you don't need any
    additional circuitry.

    But if you'd like to connect a second LED to pin 13,

    Connect the positive side of your LED to Arduino digital pin 13
    Connect the negative side of your LED to a 330 Ohm resistor
    Connect the other side of the resistor to ground

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/


// First we'll set up constants for the pin numbers.
// This will make it easier to follow the code below.

const int button1Pin = 2;  // pushbutton 1 pin
const int button2Pin = 3;  // pushbutton 2 pin
const int ledPin =  13;    // LED pin


void setup()
{
  // Set up the pushbutton pins to be an input:
  pinMode(button1Pin, INPUT);
  pinMode(button2Pin, INPUT);

  // Set up the LED pin to be an output:
  pinMode(ledPin, OUTPUT);
}


void loop()
{
  int button1State, button2State;  // variables to hold the pushbutton states

  // Since a pushbutton has only two states (pushed or not pushed),
  // we've run them into digital inputs. To read an input, we'll
  // use the digitalRead() function. This function takes one
  // parameter, the pin number, and returns either HIGH (5V)
  // or LOW (GND).

  // Here we'll read the current pushbutton states into
  // two variables:

  button1State = digitalRead(button1Pin);
  button2State = digitalRead(button2Pin);

  // Remember that if the button is being pressed, it will be
  // connected to GND. If the button is not being pressed,
  // the pullup resistor will connect it to 5 Volts.

  // So the state will be LOW when it is being pressed,
  // and HIGH when it is not being pressed.

  // Now we'll use those states to control the LED.
  // Here's what we want to do:

  // "If either button is being pressed, light up the LED"
  // "But, if BOTH buttons are being pressed, DON'T light up the LED"

  // Let's translate that into computer code. The Arduino gives you
  // special logic functions to deal with true/false logic:

  // A == B means "EQUIVALENT". This is true if both sides are the same.
  // A && B means "AND". This is true if both sides are true.
  // A || B means "OR". This is true if either side is true.
  // !A means "NOT". This makes anything after it the opposite (true or false).

  // We can use these operators to translate the above sentences
  // into logic statements (Remember that LOW means the button is
  // being pressed)

  // "If either button is being pressed, light up the LED"
  // becomes:
  // if ((button1State == LOW) || (button2State == LOW)) // light the LED

  // "If BOTH buttons are being pressed, DON'T light up the LED"
  // becomes:
  // if ((button1State == LOW) && (button2State == LOW)) // don't light the LED

  // Now let's use the above functions to combine them into one statement:

  if (((button1State == LOW) || (button2State == LOW))  // if we're pushing button 1 OR button 2
      && !                                               // AND we're NOT
      ((button1State == LOW) && (button2State == LOW))) // pushing button 1 AND button 2
                                                        // then...
  {
    digitalWrite(ledPin, HIGH);  // turn the LED on
  }
  else
  {
    digitalWrite(ledPin, LOW);  // turn the LED off
  }

  // As you can see, logic operators can be combined to make
  // complex decisions!

  // Don't forget that we use = when we're assigning a value,
  // and use == when we're testing a value for equivalence.
}

Code To Note

pinMode(button2Pin, INPUT);

The digital pins can be used as inputs as well as outputs. Before you do either, you need to tell the Galileo which direction you’re going.

button1State = digitalRead(button1Pin);

To read a digital input, you use the digitalRead() function. It will return HIGH if there’s 5V present at the pin, or LOW if there’s 0V present at the pin.

if (button1State == LOW)

Because we’ve connected the button to GND, it will read LOW when it’s being pressed. Here we’re using the “equivalence” operator (“==”) to see if the button is being pressed.

What You Should See

You should see the LED turn on if you press either button, and off if you press both buttons. (See the code to find out why!) If it isn’t working, make sure you have assembled the circuit correctly and verified and uploaded the code to your board or see the troubleshooting section.

Real World Application

The buttons we used here are similar to the buttons in most video game controllers.

Troubleshooting

Light Not Turning On

The pushbutton is square, and because of this it is easy to put it in the wrong way. Give it a 90 degree twist and see if it starts working.

Underwhelmed

No worries, these circuits are all super stripped down to make playing with the components easy, but once you throw them together the sky is the limit.

**Experiment 6: Reading a Photoresistor**

Introduction

In experiment 2, you got to use a potentiometer, which varies resistance based on the twisting of a knob. In this circuit, you’ll be using a photoresistor, which changes resistance based on how much light the sensor receives. Since the RedBoard and Arduino Uno R3 can’t directly interpret resistance (rather, it reads voltage), we need to use a voltage divider to use our photoresistor. This voltage divider will output a high voltage when it is getting a lot of light and a low voltage when little or no light is present.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x RedBoard or Arduino Uno
  • 1x LED
  • 1x 330Ω Resistor
  • 6x Jumper Wires
  • 1x Photoresistor
  • 1x 10k Resistor

Didn’t get the SIK?

If you are following through this experiment and didn’t get the SIK, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

In stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Mini Photocell

Mini Photocell

In stock SEN-09088

This is a very small light sensor. A photocell changes (also called a [photodetector](http://en.wikipedia.org/wiki/Photodetec…

1.5
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

In stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

1/6 Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 330Ohm resistors make excellent…

0.95
LED - Assorted (20 pack)

LED - Assorted (20 pack)

In stock COM-12062

We all know that you can never get too many LEDs. Don't worry, we've got you covered. This is a pack of basic red, yellow, bl…

2.95
Resistor 10K Ohm 1/6th Watt PTH - 20 pack

Resistor 10K Ohm 1/6th Watt PTH - 20 pack

In stock COM-11508

1/6th Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 10K resistors make excellent …

0.95

You will also need either a RedBoard or Arduino Uno R3.

RedBoard - Programmed with Arduino

RedBoard - Programmed with Arduino

Only 5 left! DEV-12757

At SparkFun we use many Arduinos and we're always looking for the simplest, most stable one. Each board is a bit different an…

19.95
Arduino Uno- R3 SMD

Arduino Uno- R3 SMD

In stock DEV-11224

This is the new Arduino Uno R3. In addition to all the features of the previous board, the Uno now uses an ATmega16U2 instead…

29.95

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram for RedBoard

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Fritzing Diagram for Arduino

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 06 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > examples > SIK Guide Code > Circuit_06

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Inventor's Kit
Example sketch 06

PHOTORESISTOR

  Use a photoresistor (light sensor) to control the brightness
  of a LED.

Hardware connections:

  Photo resistor:

    Connect one side of the photoresistor to 5 Volts (5V).
    Connect the other side of the photoresistor to ANALOG pin 0.
    Connect a 10K resistor between ANALOG pin 0 and GND.

    This creates a voltage divider, with the photoresistor one
    of the two resistors. The output of the voltage divider
    (connected to A0) will vary with the light level.

  LED:

    Connect the positive side (long leg) of the LED to
    digital pin 9. (To vary the brightness, this pin must
    support PWM, which is indicated by "~" or "PWM" on the
    Arduino itself.)

    Connect the negative side of the LED (short leg) to a
    330 Ohm resistor.

    Connect the other side of the resistor to GND.

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/


// As usual, we'll create constants to name the pins we're using.
// This will make it easier to follow the code below.

const int sensorPin = 0;
const int ledPin = 9;

// We'll also set up some global variables for the light level:

int lightLevel, high = 0, low = 1023;


void setup()
{
  // We'll set up the LED pin to be an output.
  // (We don't need to do anything special to use the analog input.)

  pinMode(ledPin, OUTPUT);
}


void loop()
{
  // Just as we've done in the past, we'll use the analogRead()
  // function to measure the voltage coming from the photoresistor
  // resistor pair. This number can range between 0 (0 Volts) and
  // 1023 (5 Volts), but this circuit will have a smaller range
  // between dark and light.

  lightLevel = analogRead(sensorPin);

  // We now want to use this number to control the brightness of
  // the LED. But we have a problem: the analogRead() function
  // returns values between 0 and 1023, and the analogWrite()
  // function wants values from 0 to 255.

  // We can solve this by using two handy functions called map()
  // and constrain(). Map will change one range of values into
  // another range. If we tell map() our "from" range is 0-1023,
  // and our "to" range is 0-255, map() will squeeze the larger
  // range into the smaller. (It can do this for any two ranges.)

  // lightLevel = map(lightLevel, 0, 1023, 0, 255);

  // Because map() could still return numbers outside the "to"
  // range, (if they're outside the "from" range), we'll also use
  // a function called constrain() that will "clip" numbers into
  // a given range. If the number is above the range, it will reset
  // it to be the highest number in the range. If the number is
  // below the range, it will reset it to the lowest number.
  // If the number is within the range, it will stay the same.

  // lightLevel = constrain(lightLevel, 0, 255);

  // Here's one last thing to think about. The circuit we made
  // won't have a range all the way from 0 to 5 Volts. It will
  // be a smaller range, such as 300 (dark) to 800 (light).
  // If we just pass this number directly to map(), the LED will
  // change brightness, but it will never be completely off or
  // completely on.

  // You can fix this two ways, each of which we'll show
  // in the functions below. Uncomment ONE of them to
  // try it out:

  manualTune();  // manually change the range from light to dark

  //autoTune();  // have the Arduino do the work for us!

  // The above functions will alter lightLevel to be cover the
  // range from full-on to full-off. Now we can adjust the
  // brightness of the LED:

  analogWrite(ledPin, lightLevel);

  // The above statement will brighten the LED along with the
  // light level. To do the opposite, replace "lightLevel" in the
  // above analogWrite() statement with "255-lightLevel".
  // Now you've created a night-light!
}


void manualTune()
{
  // As we mentioned above, the light-sensing circuit we built
  // won't have a range all the way from 0 to 1023. It will likely
  // be more like 300 (dark) to 800 (light). If you run this sketch
  // as-is, the LED won't fully turn off, even in the dark.

  // You can accommodate the reduced range by manually
  // tweaking the "from" range numbers in the map() function.
  // Here we're using the full range of 0 to 1023.
  // Try manually changing this to a smaller range (300 to 800
  // is a good guess), and try it out again. If the LED doesn't
  // go completely out, make the low number larger. If the LED
  // is always too bright, make the high number smaller.

  // Remember you're JUST changing the 0, 1023 in the line below!

  lightLevel = map(lightLevel, 0, 1023, 0, 255);
  lightLevel = constrain(lightLevel, 0, 255);

  // Now we'll return to the main loop(), and send lightLevel
  // to the LED.
}


void autoTune()
{
  // As we mentioned above, the light-sensing circuit we built
  // won't have a range all the way from 0 to 1023. It will likely
  // be more like 300 (dark) to 800 (light).

  // In the manualTune() function above, you need to repeatedly
  // change the values and try the program again until it works.
  // But why should you have to do that work? You've got a
  // computer in your hands that can figure things out for itself!

  // In this function, the Arduino will keep track of the highest
  // and lowest values that we're reading from analogRead().

  // If you look at the top of the sketch, you'll see that we've
  // initialized "low" to be 1023. We'll save anything we read
  // that's lower than that:

  if (lightLevel < low)
  {
    low = lightLevel;
  }

  // We also initialized "high" to be 0. We'll save anything
  // we read that's higher than that:

  if (lightLevel > high)
  {
    high = lightLevel;
  }

  // Once we have the highest and lowest values, we can stick them
  // directly into the map() function. No manual tweaking needed!

  // One trick we'll do is to add a small offset to low and high,
  // to ensure that the LED is fully-off and fully-on at the limits
  // (otherwise it might flicker a little bit).

  lightLevel = map(lightLevel, low+30, high-30, 0, 255);
  lightLevel = constrain(lightLevel, 0, 255);

  // Now we'll return to the main loop(), and send lightLevel
  // to the LED.
}

Code To Note

lightLevel = map(lightLevel, 0, 1023, 0, 255);

Parameters

map(value, fromLow, fromHigh, toLow, toHigh)

value: the number to map

fromLow: the lower bound of the value’s current range

fromHigh: the upper bound of the value’s current range

toLow: the lower bound of the value’s target range

toHigh: the upper bound of the value’s target range

When we read an analog signal using analogRead(), it will be a number from 0 to 1023. But when we want to drive a PWM pin using analogWrite(), it wants a number from 0 to 255. We can “squeeze” the larger range into the smaller range using the map() function. See Arduino’s map reference page for more info.

lightLevel = constrain(lightLevel, 0, 255);

Parameters

constrain(x, a, b)

x: the number to constrain, all data types

a: the lower end of the range, all data types

b: the upper end of the range, all data types

Because map() could still return numbers outside the “to” range, we’ll also use a function called constrain() that will “clip” numbers into a range. If the number is outside the range, it will make it the largest or smallest number. If it is within the range, it will stay the same. See Arduino’s constrain reference page for more info.

What You Should See

You should see the LED grow brighter or dimmer in accordance with how much light your photoresistor is reading. If it isn’t working, make sure you have assembled the circuit correctly and verified and uploaded the code to your board or see the troubleshooting section.

Real World Application

Some street lamps as well as solar walkway lights use photoresistors to detect the absence of the sun and turn on the lights.

Troubleshooting

LED Remains Dark

This is a mistake we continue to make time and time again, if only they could make an LED that worked both ways. Pull it up and give it a twist.

It Isn’t Responding to Changes in Light

Given that the spacing of the wires on the photoresistor is not standard, it is easy to misplace it. Double check it’s in the right place.

Still Not Quite Working

You may be in a room which is either too bright or dark. Try turning the lights on or off to see if this helps. Or if you have a flashlight near by give that a try.

**Experiment 7: Reading a Temperature Sensor**

Introduction

A temperature sensor is exactly what it sounds like – a sensor used to measure ambient temperature. This particular sensor has three pins – a positive, a ground, and a signal. This is a linear temperature sensor. A change in temperature of one degree centigrade is equal to a change of 10 millivolts at the sensor output.

The TMP36 sensor has a nominal 750 mV at 25°C (about room temperature). In this circuit, you’ll learn how to integrate the temperature sensor with your RedBoard or Arduino Uno R3, and use the Arduino IDE’s serial monitor to display the temperature.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x RedBoard or Arduino Uno
  • 5x Jumper Wires
  • 1x Temperature Sensor

Didn’t get the SIK?

If you are following through this experiment and didn’t get the SIK, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

In stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

In stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Temperature Sensor - TMP36

Temperature Sensor - TMP36

In stock SEN-10988

This is the same temperature sensor that is included in our [SparkFun Inventor's Kit](http://www.sparkfun.com/products/10173)…

1.5

You will also need either a RedBoard or Arduino Uno R3.

RedBoard - Programmed with Arduino

RedBoard - Programmed with Arduino

Only 5 left! DEV-12757

At SparkFun we use many Arduinos and we're always looking for the simplest, most stable one. Each board is a bit different an…

19.95
Arduino Uno- R3 SMD

Arduino Uno- R3 SMD

In stock DEV-11224

This is the new Arduino Uno R3. In addition to all the features of the previous board, the Uno now uses an ATmega16U2 instead…

29.95

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Please note: The temperature sensor can only be connected to a circuit in one direction. See below for the pin outs of the temperature sensor - TMP36

Temperature Sensor<-

Fritzing Diagram for RedBoard

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Fritzing Diagram for Arduino

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 7 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > examples > SIK Guide Code > Circuit_07

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Inventor's Kit
Example sketch 07

TEMPERATURE SENSOR

  Use the "serial monitor" window to read a temperature sensor.

  The TMP36 is an easy-to-use temperature sensor that outputs
  a voltage that's proportional to the ambient temperature.
  You can use it for all kinds of automation tasks where you'd
  like to know or control the temperature of something.

  More information on the sensor is available in the datasheet:
  http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Sensors/Temp/TMP35_36_37.pdf

  Even more exciting, we'll start using the Arduino's serial port
  to send data back to your main computer! Up until now, we've
  been limited to using simple LEDs for output. We'll see that
  the Arduino can also easily output all kinds of text and data.

Hardware connections:

  Be careful when installing the temperature sensor, as it is
  almost identical to the transistors! The one you want has
  a triangle logo and "TMP" in very tiny letters. The
  ones you DON'T want will have "222" on them.

  When looking at the flat side of the temperature sensor
  with the pins down, from left to right the pins are:
  5V, SIGNAL, and GND.

  Connect the 5V pin to 5 Volts (5V).
  Connect the SIGNAL pin to ANALOG pin 0.
  Connect the GND pin to ground (GND).

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/

// We'll use analog input 0 to measure the temperature sensor's
// signal pin.

const int temperaturePin = 0;


void setup()
{
  // In this sketch, we'll use the Arduino's serial port
  // to send text back to the main computer. For both sides to
  // communicate properly, they need to be set to the same speed.
  // We use the Serial.begin() function to initialize the port
  // and set the communications speed.

  // The speed is measured in bits per second, also known as
  // "baud rate". 9600 is a very commonly used baud rate,
  // and will transfer about 10 characters per second.

  Serial.begin(9600);
}


void loop()
{
  // Up to now we've only used integer ("int") values in our
  // sketches. Integers are always whole numbers (0, 1, 23, etc.).
  // In this sketch, we'll use floating-point values ("float").
  // Floats can be fractional numbers such as 1.42, 2523.43121, etc.

  // We'll declare three floating-point variables
  // (We can declare multiple variables of the same type on one line:)

  float voltage, degreesC, degreesF;

  // First we'll measure the voltage at the analog pin. Normally
  // we'd use analogRead(), which returns a number from 0 to 1023.
  // Here we've written a function (further down) called
  // getVoltage() that returns the true voltage (0 to 5 Volts)
  // present on an analog input pin.

  voltage = getVoltage(temperaturePin);

  // Now we'll convert the voltage to degrees Celsius.
  // This formula comes from the temperature sensor datasheet:

  degreesC = (voltage - 0.5) * 100.0;

  // While we're at it, let's convert degrees Celsius to Fahrenheit.
  // This is the classic C to F conversion formula:

  degreesF = degreesC * (9.0/5.0) + 32.0;

  // Now we'll use the serial port to print these values
  // to the serial monitor!

  // To open the serial monitor window, upload your code,
  // then click the "magnifying glass" button at the right edge
  // of the Arduino IDE toolbar. The serial monitor window
  // will open.

  // (NOTE: remember we said that the communication speed
  // must be the same on both sides. Ensure that the baud rate
  // control at the bottom of the window is set to 9600. If it
  // isn't, change it to 9600.)

  // Also note that every time you upload a new sketch to the
  // Arduino, the serial monitor window will close. It does this
  // because the serial port is also used to upload code!
  // When the upload is complete, you can re-open the serial
  // monitor window.

  // To send data from the Arduino to the serial monitor window,
  // we use the Serial.print() function. You can print variables
  // or text (within quotes).

  Serial.print("voltage: ");
  Serial.print(voltage);
  Serial.print("  deg C: ");
  Serial.print(degreesC);
  Serial.print("  deg F: ");
  Serial.println(degreesF);

  // These statements will print lines of data like this:
  // "voltage: 0.73 deg C: 22.75 deg F: 72.96"

  // Note that all of the above statements are "print", except
  // for the last one, which is "println". "Print" will output
  // text to the SAME LINE, similar to building a sentence
  // out of words. "Println" will insert a "carriage return"
  // character at the end of whatever it prints, moving down
  // to the NEXT line.

  delay(1000); // repeat once per second (change as you wish!)
}


float getVoltage(int pin)
{
  // This function has one input parameter, the analog pin number
  // to read. You might notice that this function does not have
  // "void" in front of it; this is because it returns a floating-
  // point value, which is the true voltage on that pin (0 to 5V).

  // You can write your own functions that take in parameters
  // and return values. Here's how:

    // To take in parameters, put their type and name in the
    // parenthesis after the function name (see above). You can
    // have multiple parameters, separated with commas.

    // To return a value, put the type BEFORE the function name
    // (see "float", above), and use a return() statement in your code
    // to actually return the value (see below).

    // If you don't need to get any parameters, you can just put
    // "()" after the function name.

    // If you don't need to return a value, just write "void" before
    // the function name.

  // Here's the return statement for this function. We're doing
  // all the math we need to do within this statement:

  return (analogRead(pin) * 0.004882814);

  // This equation converts the 0 to 1023 value that analogRead()
  // returns, into a 0.0 to 5.0 value that is the true voltage
  // being read at that pin.
}

// Other things to try with this code:

//   Turn on an LED if the temperature is above or below a value.

//   Read that threshold value from a potentiometer - now you've
//   created a thermostat!

Code To Note

Serial.begin(9600);

Before using the serial monitor, you must call Serial.begin() to initialize it. 9600 is the “baud rate”, or communications speed. When two devices are communicating with each other, both must be set to the same speed.

Serial.print(degreesC);

The Serial.print() command is very smart. It can print out almost anything you can throw at it, including variables of all types, quoted text (AKA “strings”), etc. See http://arduino.cc/en/serial/print for more info.

Serial.println(degreesF);

Serial.print() will print everything on the same line.

Serial.println() will move to the next line. By using both of these commands together, you can create easy-to-read printouts of text and data.

What You Should See

You should be able to read the temperature your temperature sensor is detecting on the serial monitor in the Arduino IDE. If it isn’t working, make sure you have assembled the circuit correctly and verified and uploaded the code to your board or see the troubleshooting section.

Example of what you should see in the Arduino IDE’s serial monitor:

voltage: 0.73 deg C: 23.24 deg F: 73.84

voltage: 0.73 deg C: 23.24 deg F: 73.84

voltage: 0.73 deg C: 22.75 deg F: 72.96

voltage: 0.73 deg C: 23.24 deg F: 73.84

voltage: 0.73 deg C: 23.24 deg F: 73.84

voltage: 0.73 deg C: 23.24 deg F: 73.84

voltage: 0.73 deg C: 22.75 deg F: 72.96

voltage: 0.73 deg C: 23.24 deg F: 73.84

voltage: 0.73 deg C: 22.75 deg F: 72.96

voltage: 0.73 deg C: 22.75 deg F: 72.96

voltage: 0.73 deg C: 23.24 deg F: 73.84

voltage: 0.73 deg C: 22.75 deg F: 72.96

voltage: 0.73 deg C: 23.24 deg F: 73.84

Real World Application

Building climate control systems use a temperature sensor to monitor and maintain their settings.

Troubleshooting

Nothing Seems to Happen

This program has no outward indication it is working. To see the results you must open the Arduino IDE’s serial monitor (instructions on previous page).

Gibberish is Displayed

This happens because the serial monitor is receiving data at a different speed than expected. To fix this, click the pull-down box that reads “*** baud” and change it to “9600 baud”.

Temperature Value is Unchanging

Try pinching the sensor with your fingers to heat it up or pressing a bag of ice against it to cool it down.

**Experiment 8: Driving a Servo Motor**

Introduction

Servos are ideal for embedded electronics applications because they do one thing very well that motors cannot – they can move to a position accurately. By varying the pulse width of the output voltage to a servo, you can move a servo to a specific position. For example, a pulse of 1.5 milliseconds will move the servo 90 degrees. In this circuit, you’ll learn how to use PWM (pulse width modulation) to control and rotate a servo.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x RedBoard or Arduino Uno
  • 1x Servo
  • 8x Jumper Wires

Didn’t get the SIK?

If you are following through this experiment and didn’t get the SIK, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

In stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Servo - Generic (Sub-Micro Size)

Servo - Generic (Sub-Micro Size)

In stock ROB-09065

Here is a simple, low-cost, high quality servo for all your mechatronic needs. This servo is very similar in size and specifi…

8.95
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

In stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95

You will also need either a RedBoard or Arduino Uno R3.

RedBoard - Programmed with Arduino

RedBoard - Programmed with Arduino

Only 5 left! DEV-12757

At SparkFun we use many Arduinos and we're always looking for the simplest, most stable one. Each board is a bit different an…

19.95
Arduino Uno- R3 SMD

Arduino Uno- R3 SMD

In stock DEV-11224

This is the new Arduino Uno R3. In addition to all the features of the previous board, the Uno now uses an ATmega16U2 instead…

29.95

Suggested Reading

Before continuing on with this experiment, we recommend you be familiar with the concepts in the following tutorial:

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Connect 3x jumper wires to the female 3 pin header on the servo. This will make it easier to breadboard the servo.

Servo Jumpers

Fritzing Diagram for RedBoard

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Fritzing Diagram for Arduino

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 08 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > examples > SIK Guide Code > Circuit_08

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Inventor's Kit
Example sketch 08

SINGLE SERVO

  Sweep a servo back and forth through its full range of motion.

  A "servo", short for servomotor, is a motor that includes
  feedback circuitry that allows it to be commanded to move to
  specific positions. This one is very small, but larger servos
  are used extensively in robotics to control mechanical arms,
  hands, etc. You could use it to make a (tiny) robot arm,
  aircraft control surface, or anywhere something needs to be
  moved to specific positions.

Hardware connections:

  The servo has a cable attached to it with three wires.
  Because the cable ends in a socket, you can use jumper wires
  to connect between the Arduino and the servo. Just plug the
  jumper wires directly into the socket.

  Connect the RED wire (power) to 5 Volts (5V)
  Connect the WHITE wire (signal) to digital pin 9
  Connect the BLACK wire (ground) to ground (GND)

  Note that servos can use a lot of power, which can cause your
  Arduino to reset or behave erratically. If you're using large
  servos or many of them, it's best to provide them with their
  own separate 5V supply. See this Arduino Forum thread for info:
  http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1239464763

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/


// If we had to write a sketch to control a servo from scratch,
// it would be a lot of work. Fortunately, others have done the
// hard work for you. We're going to include a "library"
// that has the functions needed to drive servos.

// A library is an set of additional functions you can add to
// your sketch. Numerous libraries are available for many uses,
// see http://arduino.cc/en/Reference/Libraries for information
// on the standard libraries, and Google for others. When you're
// using a new part, chances are someone has written a library
// for it.

#include <Servo.h>  // servo library

// Once you "include" a library, you'll have access to those
// functions. You can find a list of the functions in the servo
// library at: http://arduino.cc/en/Reference/Servo
// Most libraries also have example sketches you can load from
// the "file/examples" menu.

// Now we'll create a servo "object", called myservo. You should
// create one of these for each servo you want to control.
// You can control a maximum of twelve servos on the Uno
// using this library. (Other servo libraries may let you
// control more). Note that this library disables PWM on
// pins 9 and 10!

Servo servo1;  // servo control object


void setup()
{
  // We'll now "attach" the servo1 object to digital pin 9.
  // If you want to control more than one servo, attach more
  // servo objects to the desired pins (must be digital).

  // Attach tells the Arduino to begin sending control signals
  // to the servo. Servos require a continuous stream of control
  // signals, even if you're not currently moving them.
  // While the servo is being controlled, it will hold its
  // current position with some force. If you ever want to
  // release the servo (allowing it to be turned by hand),
  // you can call servo1.detach().

  servo1.attach(9);
}


void loop()
{
  int position;

  // To control a servo, you give it the angle you'd like it
  // to turn to. Servos cannot turn a full 360 degrees, but you
  // can tell it to move anywhere between 0 and 180 degrees.

  // Change position at full speed:

  servo1.write(90);    // Tell servo to go to 90 degrees

  delay(1000);         // Pause to get it time to move

  servo1.write(180);   // Tell servo to go to 180 degrees

  delay(1000);         // Pause to get it time to move

  servo1.write(0);     // Tell servo to go to 0 degrees

  delay(1000);         // Pause to get it time to move

  // Change position at a slower speed:

  // To slow down the servo's motion, we'll use a for() loop
  // to give it a bunch of intermediate positions, with 20ms
  // delays between them. You can change the step size to make
  // the servo slow down or speed up. Note that the servo can't
  // move faster than its full speed, and you won't be able
  // to update it any faster than every 20ms.

  // Tell servo to go to 180 degrees, stepping by two degrees

  for(position = 0; position < 180; position += 2)
  {
    servo1.write(position);  // Move to next position
    delay(20);               // Short pause to allow it to move
  }

  // Tell servo to go to 0 degrees, stepping by one degree

  for(position = 180; position >= 0; position -= 1)
  {
    servo1.write(position);  // Move to next position
    delay(20);               // Short pause to allow it to move
  }
}

Code To Note

#include <Servo.h>

#include is a special “preprocessor” command that inserts a library (or any other file) into your sketch. You can type this command yourself, or choose an installed library from the “sketch / import library” menu.

Servo servo1;

servo1.attach(9);

The servo library adds new commands that let you control a servo. To prepare the Galileo to control a servo, you must first create a Servo “object” for each servo (here we’ve named it “servo1”), and then “attach” it to a digital pin (here we’re using pin 9).

servo1.write(180);

The servos in this kit don’t spin all the way around, but they can be commanded to move to a specific position. We use the servo library’s write() command to move a servo to a specified number of degrees(0 to 180). Remember that the servo requires time to move, so give it a short delay() if necessary.

What You Should See

You should see your servo motor move to various locations at several speeds. If the motor doesn’t move, check your connections and make sure you have verified and uploaded the code, or see the troubleshooting section.

Real World Application

Robotic arms you might see in an assembly line or sci-fi movie probably have servos in them.

Troubleshooting

Servo Not Twisting

Even with colored wires it is still shockingly easy to plug a servo in backward. This might be the case.

Still Not Working

A mistake we made a time or two was simply forgetting to connect the power (red and black wires) to +5 volts and ground.

Fits and Starts

If the servo begins moving then twitches, and there’s a flashing light on your RedBoard or Arduino Uno R3, the power supply you are using is not quite up to the challenge. Using a wall adapter instead of USB should solve this problem.

Experiment 9: Using a Flex Sensor

Introduction

In this circuit, we will use a flex sensor to measure, well, flex! A flex sensor uses carbon on a strip of plastic to act like a variable resistor, but instead of changing the resistance by turning a knob, you change it by flexing (bending) the component. We use a “voltage divider” again to detect this change in resistance.

The sensor bends in one direction and the more it bends, the higher the resistance gets; it has a range from about 10K ohm to 35K ohm. In this circuit we will use the amount of bend of the flex sensor to control the position of a servo.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x RedBoard or Arduino Uno
  • 1x Flex Sensor
  • 1x Servo
  • 1x 10k resistor
  • 11x Jumper Wires

Didn’t get the SIK?

If you are following through this experiment and didn’t get the SIK, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

In stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Flex Sensor 2.2"

Flex Sensor 2.2"

In stock SEN-10264

A simple flex sensor 2.2" in length. As the sensor is flexed, the resistance across the sensor increases. Patented technology…

7.95
Servo - Generic (Sub-Micro Size)

Servo - Generic (Sub-Micro Size)

In stock ROB-09065

Here is a simple, low-cost, high quality servo for all your mechatronic needs. This servo is very similar in size and specifi…

8.95
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

In stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Resistor 10K Ohm 1/6th Watt PTH - 20 pack

Resistor 10K Ohm 1/6th Watt PTH - 20 pack

In stock COM-11508

1/6th Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 10K resistors make excellent …

0.95

You will also need either a RedBoard or Arduino Uno R3.

RedBoard - Programmed with Arduino

RedBoard - Programmed with Arduino

Only 5 left! DEV-12757

At SparkFun we use many Arduinos and we're always looking for the simplest, most stable one. Each board is a bit different an…

19.95
Arduino Uno- R3 SMD

Arduino Uno- R3 SMD

In stock DEV-11224

This is the new Arduino Uno R3. In addition to all the features of the previous board, the Uno now uses an ATmega16U2 instead…

29.95

Suggested Reading

Before continuing on with this experiment, we recommend you be familiar with the concepts in the following tutorial:

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Connect 3x jumper wires to the female 3 pin header on the servo. This will make it easier to breadboard the servo.

Fritzing Diagram for RedBoard

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Fritzing Diagram for Arduino

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 9 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > examples > SIK Guide Code > Circuit_09

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Inventor's Kit Galileo
Example sketch 09

FLEX SENSOR

  Use the "flex sensor" to change the position of a servo

  In the previous sketch, we learned how to command a servo to
  mode to different positions. In this sketch, we'll introduce
  a new sensor, and use it to control the servo.

  A flex sensor is a plastic strip with a conductive coating.
  When the strip is straight, the coating will be a certain
  resistance. When the strip is bent, the particles in the coating
  get further apart, increasing the resistance. You can use this
  sensor to sense finger movement in gloves, door hinges, stuffed
  animals, etc. See http://www.sparkfun.com/tutorials/270 for
  more information.

Hardware connections:

  Flex sensor:

    The flex sensor is the plastic strip with black stripes.
    It senses bending away from the striped side.

    The flex sensor has two pins, and since it's a resistor,
    the pins are interchangable.

    Connect one of the pins to ANALOG IN pin 0 on the Arduino.
    Connect the same pin, through a 10K Ohm resistor (brown
    black orange) to GND.
    Connect the other pin to 5V.

  Servo:

    The servo has a cable attached to it with three wires.
    Because the cable ends in a socket, you can use jumper wires
    to connect between the Arduino and the servo. Just plug the
    jumper wires directly into the socket.

    Connect the RED wire (power) to 5 Volts (5V)
    Connect the WHITE wire (signal) to digital pin 9
    Connect the BLACK wire (ground) to ground (GND)

    Note that servos can use a lot of power, which can cause your
    Arduino to reset or behave erratically. If you're using large
    servos or many of them, it's best to provide them with their
    own separate 5V supply. See this Arduino Forum thread for info:
    http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1239464763

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/


// Include the servo library to add servo-control functions:

#include <Servo.h>

// Create a servo "object", called servo1. Each servo object
// controls one servo (you can have a maximum of 12):

Servo servo1;

// Define the analog input pin to measure flex sensor position:

const int flexpin = 0;


void setup()
{
  // Use the serial monitor window to help debug our sketch:

  Serial.begin(9600);

  // Enable control of a servo on pin 9:

  servo1.attach(9);
}


void loop()
{
  int flexposition;    // Input value from the analog pin.
  int servoposition;   // Output value to the servo.

  // Read the position of the flex sensor (0 to 1023):

  flexposition = analogRead(flexpin);

  // Because the voltage divider circuit only returns a portion
  // of the 0-1023 range of analogRead(), we'll map() that range
  // to the servo's range of 0 to 180 degrees. The flex sensors
  // we use are usually in the 600-900 range:

  servoposition = map(flexposition, 600, 900, 0, 180);
  servoposition = constrain(servoposition, 0, 180);

  // Now we'll command the servo to move to that position:

  servo1.write(servoposition);

  // Because every flex sensor has a slightly different resistance,
  // the 600-900 range may not exactly cover the flex sensor's
  // output. To help tune our program, we'll use the serial port to
  // print out our values to the serial monitor window:

  Serial.print("sensor: ");
  Serial.print(flexposition);
  Serial.print("  servo: ");
  Serial.println(servoposition);

  // Note that all of the above lines are "print" except for the
  // last line which is "println". This puts everything on the
  // same line, then sends a final carriage return to move to
  // the next line.

  // After you upload the sketch, turn on the serial monitor
  // (the magnifying-glass icon to the right of the icon bar).
  // You'll be able to see the sensor values. Bend the flex sensor
  // and note its minimum and maximum values. If you replace the
  // 600 and 900 in the map() function above, you'll exactly match
  // the flex sensor's range with the servo's range.

  delay(20);  // wait 20ms between servo updates
}

Code To Note

servoposition = map(flexposition, 600, 900, 0, 180);

map(value, fromLow, fromHigh, toLow, toHigh)

Because the flex sensor / resistor combination won’t give us a full 0 to 5 volt range, we’re using the map() function as a handy way to reduce that range. Here we’ve told it to only expect values from 600 to 900, rather than 0 to 1023.

servoposition = constrain(servoposition, 0, 180);

constrain(x, a, b)

Because map() could still return numbers outside the “to” range, we’ll also use a function called constrain() that will “clip” numbers into a range. If the number is outside the range, it will make it the largest or smallest number. If it is within the range, it will stay the same.

What You Should See

You should see the servo motor move in accordance with how much you are flexing the flex sensor. If it isn’t working, make sure you have assembled the circuit correctly and verified and uploaded the code to your board or see the troubleshooting section.

Real World Application

Controller accessories for video game consoles like Nintendo’s “Power Glove” use flex-sensing technology. It was the first video game controller attempting to mimic hand movement on a screen in real time.

Troublshooting

Servo Not Twisting

Even with colored wires it is still shockingly easy to plug a servo in backwards. This might be the case.

Servo Not Moving as Expected

The sensor is only designed to work in one direction. Try flexing it the other way (where the striped side faces out on a convex curve).

Servo Doesn’t Move very Far

You need to modify the range of values in the call to the map() function.

Experiment 10: Reading a Soft Potentiometer

Introduction

In this circuit, we are going to use yet another kind of variable resistor – this time, a soft potentiometer (or soft pot). This is a thin and flexible strip that can detect where pressure is being applied. By pressing down on various parts of the strip, you can vary the resistance from 100 to 10k ohms. You can use this ability to track movement on the soft pot, or simply as a button. In this circuit, we’ll get the soft pot up and running to control an RGB LED.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x RedBoard or Arduino Uno
  • 1x Soft Potentiometer
  • 1x 10k resistor
  • 3x 330Ω resistors
  • 1x RGB LED
  • 9x Jumper Wires

Didn’t get the SIK?

If you are following through this experiment and didn’t get the SIK, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

In stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
LED - RGB Clear Common Cathode

LED - RGB Clear Common Cathode

In stock COM-00105

Ever hear of a thing called RGB? Red, Green, Blue? How about an RGB LED? These 5mm units have four pins - Cathode is the long…

1.95
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

In stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

1/6 Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 330Ohm resistors make excellent…

0.95
Resistor 10K Ohm 1/6th Watt PTH - 20 pack

Resistor 10K Ohm 1/6th Watt PTH - 20 pack

In stock COM-11508

1/6th Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 10K resistors make excellent …

0.95
SoftPot Membrane Potentiometer - 50mm

SoftPot Membrane Potentiometer - 50mm

In stock SEN-08680

These are very thin variable potentiometers. By pressing down on various parts of the strip, the resistance linearly changes …

4.95

You will also need either a RedBoard or Arduino Uno R3.

RedBoard - Programmed with Arduino

RedBoard - Programmed with Arduino

Only 5 left! DEV-12757

At SparkFun we use many Arduinos and we're always looking for the simplest, most stable one. Each board is a bit different an…

19.95
Arduino Uno- R3 SMD

Arduino Uno- R3 SMD

In stock DEV-11224

This is the new Arduino Uno R3. In addition to all the features of the previous board, the Uno now uses an ATmega16U2 instead…

29.95

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram for RedBoard

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Fritzing Diagram for Arduino

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 10 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > examples > SIK Guide Code > Circuit_10

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Inventor's Kit
Example sketch 10

SOFT POTENTIOMETER

  Use the soft potentiometer to change the color
  of the RGB LED

  The soft potentiometer is a neat input device that detects
  pressure along its length. When you press it down with a finger
  (it works best on a flat surface), it will change resistance
  depending on where you're pressing it. You might use it to make
  a piano or light dimmer; here we're going to use it to control
  the color of an RGB LED.

Hardware connections:

  Soft potentiometer:

    The soft potentiometer is the large plastic strip with three
    pins. We'll be connecting it as a voltage divider, just like
    we did with the knob-type potentiometer back in circuit #2.

    Connect the middle pin to ANALOG IN pin 0 on the Arduino.
    Connect one side to 5V.
    Connect the other side to GND.
    Also connect a 10K resistor from the middle pin to GND.

    TIP: the soft pot will only work while you're actively
    pressing on it; at other times it will "float" to random
    values. To prevent this, we've added a 10K pull-down resistor
    to the middle pin (output voltage). This will keep the output
    at zero volts when the pot is not being pressed.

  RGB LED:

    An RGB LED is actually three LEDs (red, green, and blue)
    in one package. When we run them at different brightnesses,
    they mix to form new colors.

    Starting at the flattened edge of the flange on the LED,
    the pins are ordered RED, COMMON, GREEN, BLUE.

    Connect RED to a 330 Ohm resistor.
    Connect the other end of the resistor to Arduino digital pin 9.

    Connect COMMON to GND.

    Connect GREEN through a 330 Ohm resistor.
    Connect the other end of the resistor to Arduino digital pin 10.

    Connect BLUE through a 330 Ohm resistor.
    Connect the other end of the resistor to Arduino digital pin 11.

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/


// Constants for LED connections (note that these must be
// PWM pins, which are marked with "PWM" or have a "~" symbol
// next to them on the board).

const int RED_LED_PIN = 9;    // Red LED Pin
const int GREEN_LED_PIN = 10; // Green LED Pin
const int BLUE_LED_PIN = 11;  // Blue LED Pin

const int SENSOR_PIN = 0;      // Analog input pin

// Global PWM brightness values for the RGB LED.
// These are global so both loop() and setRGB() can see them.

int redValue, greenValue, blueValue;


void setup()
{
  // No need for any code here
  // analogWrite() sets up the pins as outputs
}


void loop()
{
  int sensorValue;

  // Read the voltage from the softpot (0-1023)

  sensorValue = analogRead(0);

  // We've written a new function called setRGB() (further down
  // in the sketch) that decodes sensorValue into a position
  // on the RGB "rainbow", and sets the RGB LED to that color.

  setRGB(sensorValue);
}


// setRGB()
// Set a RGB LED to a position on the "rainbow" of all colors.
// RGBposition should be in the range of 0 to 1023 (such as
// from an analog input).

void setRGB(int RGBposition)
{
  int mapRGB1, mapRGB2, constrained1, constrained2;

  // Here we take RGBposition and turn it into three RGB values.

  // The three values are computed so that the colors mix and
  // produce a rainbow of colors across the 0-1023 input range.

  // For each channel (red green blue), we're creating a "peak"
  // a third of the way along the 0-1023 range. By overlapping
  // these peaks with each other, the colors are mixed together.
  // This is most easily shown with a diagram:
  // http://sfecdn.s3.amazonaws.com/education/SIK/SchematicImages/Misc/RGB_function.jpg

  // Create the red peak, which is centered at 0.
  // (Because it's centered at 0, half is after 0, and half
  // is before 1023):

  mapRGB1 = map(RGBposition, 0, 341, 255, 0);
  constrained1 = constrain(mapRGB1, 0, 255);

  mapRGB2 = map(RGBposition, 682, 1023, 0, 255);
  constrained2 = constrain(mapRGB2, 0, 255);

  redValue = constrained1 + constrained2;

  // Create the green peak, which is centered at 341
  // (one-third of the way to 1023):

  // Note that we've nested the functions by putting the map()
  // function inside the constrain() function. This can make your
  // code more compact, and requires fewer variabls:

  greenValue = constrain(map(RGBposition, 0, 341, 0, 255), 0, 255)
             - constrain(map(RGBposition, 341, 682, 0,255), 0, 255);

  // Create the blue peak, which is centered at 682
  // (two-thirds of the way to 1023):

  blueValue = constrain(map(RGBposition, 341, 682, 0, 255), 0, 255)
            - constrain(map(RGBposition, 682, 1023, 0, 255), 0, 255);

  // Now we have all three brightnesses,
  // we just need to display the computed color:

  analogWrite(RED_LED_PIN, redValue);
  analogWrite(GREEN_LED_PIN, greenValue);
  analogWrite(BLUE_LED_PIN, blueValue);

  // Feel free to use this function in your own code!
}

Code To Note

language:cpp
redValue = constrain(map(RGBposition, 0, 341, 255, 0), 0, 255)
 + constrain(map(RGBposition, 682, 1023, 0, 255), 0, 255);


greenValue = constrain(map(RGBposition, 0, 341, 0, 255), 0, 255)
 - constrain(map(RGBposition, 341, 682, 0,255), 0, 255);


blueValue = constrain(map(RGBposition, 341, 682, 0, 255), 0, 255)
- constrain(map(RGBposition, 682, 1023, 0, 255), 0, 255);

These big, scary functions take a single Value (RGBposition) and calculate the three RGB values necessary to create a rainbow of color. The functions create three “peaks” for the red, green, and blue values, which overlap to mix and create new colors. See the code for more information! Even if you’re not 100% clear how it works, you can copy and paste this (or any) function into your own code and use it yourself.

What You Should See

You should see the RGB LED change colors in accordance with how you interact with the soft potentiometer. If it isn’t working, make sure you have assembled the circuit correctly and verified and uploaded the code to your board, or see the troubleshooting section.

Real World Application

The knobs found on many objects, like a radio for instance, are using similar concepts to the one you just completed for this circuit.

Troubleshooting

LED Remains Dark or Shows Incorrect Color

With the four pins of the LED so close together, it’s sometimes easy to misplace one. Try double checking each pin is where it should be.

Bizarre Results

The most likely cause of this is if you’re pressing the potentiometer in more than one position. This is normal and can actually be used to create some neat results.

Experiment 11: Using a Piezo Buzzer

Introduction

In this circuit, we’ll again bridge the gap between the digital world and the analog world. We’ll be using a piezo buzzer that makes a small “click” when you apply voltage to it (try it!). By itself that isn’t terribly exciting, but if you turn the voltage on and off hundreds of times a second, the piezo buzzer will produce a tone. And if you string a bunch of tones together, you’ve got music! This circuit and sketch will play a classic tune. We’ll never let you down!

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x RedBoard or Arduino Uno
  • 1x Piezo Buzzer
  • 3x Jumper Wires

Didn’t get the SIK?

If you are following through this experiment and didn’t get the SIK, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

In stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

In stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Piezo Speaker - PC Mount 12mm 2.048kHz

Piezo Speaker - PC Mount 12mm 2.048kHz

In stock COM-07950

This is a small 12mm round speaker that operates around the audible 2kHz range. You can use these speakers to create simple m…

1.95

You will also need either a RedBoard or Arduino Uno R3.

RedBoard - Programmed with Arduino

RedBoard - Programmed with Arduino

Only 5 left! DEV-12757

At SparkFun we use many Arduinos and we're always looking for the simplest, most stable one. Each board is a bit different an…

19.95
Arduino Uno- R3 SMD

Arduino Uno- R3 SMD

In stock DEV-11224

This is the new Arduino Uno R3. In addition to all the features of the previous board, the Uno now uses an ATmega16U2 instead…

29.95

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram for RedBoard

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Fritzing Diagram for Arduino

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 11 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > examples > SIK Guide Code > Circuit_11

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Inventor's Kit
Example sketch 11

BUZZER

  Use the buzzer to play a song!

  The buzzer in your Inventor's Kit is an electromechanical
  component you can use to make noise. Inside the buzzer is a
  coil of wire and a small magnet. When current flows through
  the coil, it becomes magnetized and pulls towards the magnet,
  creating a tiny "click". When you do this thousands of times
  per second, you create tones.

  The Arduino has a built-in command called tone() which clicks
  the buzzer at a certain frequency. This sketch knows the
  frequencies of the common notes, allowing you to create songs.
  We're never going to let you down!

Hardware connections:

  The buzzer has two pins. One is positive and one is negative.
  The postitive pin is marked by a "+" symbol on both the top
  and bottom of the buzzer.

  Connect the positive pin to Arduino digital pin 9.
  (Note that this must be a PWM pin.)
  Connect the negative pin to GND.

  Tip: if the buzzer doesn't fit into the breadboard easily,
  try rotating it slightly to fit into diagonal holes.

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
(This sketch was originally developed by D. Cuartielles for K3)
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/

/*
This sketch uses the buzzer to play songs.
The Arduino's tone() command will play notes of a given frequency.
We'll provide a function that takes in note characters (a-g),
and returns the corresponding frequency from this table:

  note  frequency
  c     262 Hz
  d     294 Hz
  e     330 Hz
  f     349 Hz
  g     392 Hz
  a     440 Hz
  b     494 Hz
  C     523 Hz

For more information, see http://arduino.cc/en/Tutorial/Tone
*/

const int buzzerPin = 9;

// We'll set up an array with the notes we want to play
// change these values to make different songs!

// Length must equal the total number of notes and spaces

const int songLength = 18;

// Notes is an array of text characters corresponding to the notes
// in your song. A space represents a rest (no tone)

char notes[] = "cdfda ag cdfdg gf "; // a space represents a rest

// Beats is an array of values for each note and rest.
// A "1" represents a quarter-note, 2 a half-note, etc.
// Don't forget that the rests (spaces) need a length as well.

int beats[] = {1,1,1,1,1,1,4,4,2,1,1,1,1,1,1,4,4,2};

// The tempo is how fast to play the song.
// To make the song play faster, decrease this value.

int tempo = 150;


void setup()
{
  pinMode(buzzerPin, OUTPUT);
}


void loop()
{
  int i, duration;

  for (i = 0; i < songLength; i++) // step through the song arrays
  {
    duration = beats[i] * tempo;  // length of note/rest in ms

    if (notes[i] == ' ')          // is this a rest?
    {
      delay(duration);            // then pause for a moment
    }
    else                          // otherwise, play the note
    {
      tone(buzzerPin, frequency(notes[i]), duration);
      delay(duration);            // wait for tone to finish
    }
    delay(tempo/10);              // brief pause between notes
  }

  // We only want to play the song once, so we'll pause forever:
  while(true){}
  // If you'd like your song to play over and over,
  // remove the above statement
}


int frequency(char note)
{
  // This function takes a note character (a-g), and returns the
  // corresponding frequency in Hz for the tone() function.

  int i;
  const int numNotes = 8;  // number of notes we're storing

  // The following arrays hold the note characters and their
  // corresponding frequencies. The last "C" note is uppercase
  // to separate it from the first lowercase "c". If you want to
  // add more notes, you'll need to use unique characters.

  // For the "char" (character) type, we put single characters
  // in single quotes.

  char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
  int frequencies[] = {262, 294, 330, 349, 392, 440, 494, 523};

  // Now we'll search through the letters in the array, and if
  // we find it, we'll return the frequency for that note.

  for (i = 0; i < numNotes; i++)  // Step through the notes
  {
    if (names[i] == note)         // Is this the one?
    {
      return(frequencies[i]);     // Yes! Return the frequency
    }
  }
  return(0);  // We looked through everything and didn't find it,
              // but we still need to return a value, so return 0.
}

Code To Note

char notes[] = "cdfda ag cdfdg gf ";

char names[] = {'c','d','e','f','g','a','b','C'};

Up until now we’ve been working solely with numerical data, but the Arduino can also work with text. Characters (single, printable, letters, numbers and other symbols) have their own type, called “char”. When you have an array of characters, it can be defined between double-quotes (also called a “string”), OR as a list of single-quoted characters.

tone(pin, frequency, duration);

One of Arduino’s many useful built-in commands is the tone() function. This function drives an output pin at a certain frequency, making it perfect for driving buzzers and speakers. If you give it a duration (in milliseconds), it will play the tone then stop. If you don’t give it a duration, it will keep playing the tone forever (but you can stop it with another function, noTone() ).

What You Should See

You should see - well, nothing! But you should be able to hear a song. If it isn’t working, make sure you have assembled the circuit correctly and verified and uploaded the code to your board or see the troubleshooting section.

Real World Application

Many modern megaphones have settings that use a loud amplified buzzer. They are usually very loud and quite good at getting people’s attention.

Troubleshooting

No Sound

Given the size and shape of the piezo buzzer it is easy to miss the right holes on the breadboard. Try double checking its placement.

Can’t Think While the Melody is Playing

Just pull up the piezo buzzer whilst you think, upload your program then plug it back in.

Feeling Let Down and Deserted

The code is written so you can easily add your own songs.

Experiment 12: Driving a Motor

Introduction

Back in experiment 8, you got to work with a servo motor. Now, we are going to tackle spinning a motor. This requires the use of a transistor, which can switch a larger amount of current than the RedBoard or Arduino Uno R3 can.

When using a transistor, you just need to make sure its maximum specs are high enough for your use case. The transistor we are using for this circuit is rated at 40V max and 200 milliamps max – perfect for our toy motor! When the motor is spinning and suddenly turned off, the magnetic field inside it collapses, generating a voltage spike. This can damage the transistor. To prevent this, we use a “flyback diode”, which diverts the voltage spike around the transistor.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x RedBoard or Arduino Uno
  • 1x Motor
  • 1x 330Ω Resistor
  • 1x NPN transistor
  • 1x Diode 1N4148
  • 6x Jumper Wires

Didn’t get the SIK?

If you are following through this experiment and didn’t get the SIK, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

In stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Transistor - NPN (P2N2222A)

Transistor - NPN (P2N2222A)

In stock COM-12852

This is the P2N2222A, an NPN silicon BJT (Bipolar Junction Transistor). This little transistor can help in your project by be…

0.5
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

In stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

1/6 Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 330Ohm resistors make excellent…

0.95
Diode Small Signal - 1N4148

Diode Small Signal - 1N4148

In stock COM-08588

This is a very common signal diode - 1N4148. Use this for signals up to 200mA of current. If you need a bunch of these, you…

0.15
Hobby Motor - Gear

Hobby Motor - Gear

In stock ROB-11696

This is our new Hobby Motor now with a 6mm, 10 tooth, gear to make your basic projects a little simpler to manage. It works w…

1.95

You will also need either a RedBoard or Arduino Uno R3.

RedBoard - Programmed with Arduino

RedBoard - Programmed with Arduino

Only 5 left! DEV-12757

At SparkFun we use many Arduinos and we're always looking for the simplest, most stable one. Each board is a bit different an…

19.95
Arduino Uno- R3 SMD

Arduino Uno- R3 SMD

In stock DEV-11224

This is the new Arduino Uno R3. In addition to all the features of the previous board, the Uno now uses an ATmega16U2 instead…

29.95

Suggested Reading

Before continuing on with this experiment, we recommend you be familiar with the concepts in the following tutorial:

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Please note: When you’re building the circuit be careful not to mix up the transistor and the temperature sensor, they’re almost identical. Look for “P2N2222A” on the body of the transistor.

Fritzing Diagram for RedBoard

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Fritzing Diagram for Arduino

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 12 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > examples > SIK Guide Code > Circuit_12

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Inventor's Kit
Example sketch 12

SPINNING A MOTOR

  Use a transistor to spin a motor at different speeds.
  We'll also show you how to input data from the serial port
  (see the serialSpeed() function below).

  Motors are the basis for thousands of things in our daily lives,
  and the Arduino can control them. Here we'll use pulse-width
  modulation (PWM) to vary the speed of a motor.

  The Arduino pins are strong enough to light small LEDs (up to
  40 milliAmps), but they're not strong enough to run motors and
  other power-hungry parts. (This motor needs 50-100mA).
  Because the motor needs more current than an Arduino pin can
  provide, we'll use a transistor to do the heavy lifting.
  A transistor is a solid-state switch. When we give it a small
  amount of current, it can switch a much larger current.
  The transistors in your kit (2N2222) can switch up to 200mA.

  You can turn a transistor on and off using the digitalWrite()
  function, but you can also use the analogWrite() function to
  vary the speed of the motor. The analogWrite() function pulses
  a pin, varying the width of the pulse from 0% to 100%. We call
  this technique "PWM", for "Pulse-Width Modulation".

  One thing to keep in mind is that when you lower the speed of
  a motor using PWM, you're also reducing the torque (strength)
  of the motor. For PWM values below 50 or so, the motor won't have
  enough torque to start spinning. It will start spinning when you
  raise the speed a bit.

Hardware connections:

  Transistor:

    The transistor has three pins. Looking at the flat side with the
    pins down, the order is COLLECTOR, BASE, EMITTER.

    Connect the black wire on the motor to the
    COLLECTOR pin on the transistor.

    Connect the BASE pin through a 330 Ohm resistor to
    digital pin 9.

    Connect the EMITTER pin to GND.

  Motor:

    You've already connected the black wire on the motor to the
    COLLECTOR pin on the transistor.

    Connect the other (red) wire on the motor to 5V.

  Flyback diode:

    When the motor is spinning and suddenly turned off, the
    magnetic field inside it collapses, generating a voltage spike.
    This can damage the transistor. To prevent this, we use a
    "flyback diode", which diverts the voltage spike "around" the
    transistor.

    Connect the side of the diode with the band (cathode) to 5V
    Connect the other side of the diode (anode) to the black wire
    on the motor.

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/

// We'll be controlling the motor from pin 9.
// This must be one of the PWM-capable pins.

const int motorPin = 9;


void setup()
{
  // Set up the motor pin to be an output:

  pinMode(motorPin, OUTPUT);

  // Set up the serial port:

  Serial.begin(9600);
}


void loop()
{
  // Here we've used comments to disable some of the examples.
  // To try different things, uncomment one of the following lines
  // and comment the other ones. See the functions below to learn
  // what they do and how they work.

  // motorOnThenOff();
  // motorOnThenOffWithSpeed();
  // motorAcceleration();
     serialSpeed();
}


// This function turns the motor on and off like the blinking LED.
// Try different values to affect the timing.

void motorOnThenOff()
{
  int onTime = 3000;  // milliseconds to turn the motor on
  int offTime = 3000; // milliseconds to turn the motor off

  digitalWrite(motorPin, HIGH); // turn the motor on (full speed)
  delay(onTime);                // delay for onTime milliseconds
  digitalWrite(motorPin, LOW);  // turn the motor off
  delay(offTime);               // delay for offTime milliseconds
}


// This function alternates between two speeds.
// Try different values to affect the timing and speed.

void motorOnThenOffWithSpeed()
{
  int Speed1 = 200;  // between 0 (stopped) and 255 (full speed)
  int Time1 = 3000;  // milliseconds for speed 1

  int Speed2 = 50;   // between 0 (stopped) and 255 (full speed)
  int Time2 = 3000;  // milliseconds to turn the motor off

  analogWrite(motorPin, Speed1);  // turns the motor On
  delay(Time1);                   // delay for onTime milliseconds
  analogWrite(motorPin, Speed2);  // turns the motor Off
  delay(Time2);                   // delay for offTime milliseconds
}


// This function slowly accelerates the motor to full speed,
// then back down to zero.

void motorAcceleration()
{
  int speed;
  int delayTime = 20; // milliseconds between each speed step

  // accelerate the motor

  for(speed = 0; speed <= 255; speed++)
  {
    analogWrite(motorPin,speed);    // set the new speed
    delay(delayTime);               // delay between speed steps
  }

  // decelerate the motor

  for(speed = 255; speed >= 0; speed--)
  {
    analogWrite(motorPin,speed);    // set the new speed
    delay(delayTime);               // delay between speed steps
  }
}


// This function will let you type a speed into the serial
// monitor window. Open the serial monitor using the magnifying-
// glass icon at the top right of the Arduino window. Then
// type your desired speed into the small text entry bar at the
// top of the window and click "Send" or press return. The motor
// will then operate at that speed. The valid range is 0 to 255.

void serialSpeed()
{
  int speed;

  Serial.println("Type a speed (0-255) into the box above,");
  Serial.println("then click [send] or press [return]");
  Serial.println();  // Print a blank line

  // In order to type out the above message only once,
  // we'll run the rest of this function in an infinite loop:

  while(true)  // "true" is always true, so this will loop forever.
  {
    // First we check to see if incoming data is available:

    while (Serial.available() > 0)
    {
      // If it is, we'll use parseInt() to pull out any numbers:

      speed = Serial.parseInt();

      // Because analogWrite() only works with numbers from
      // 0 to 255, we'll be sure the input is in that range:

      speed = constrain(speed, 0, 255);

      // We'll print out a message to let you know that the
      // number was received:

      Serial.print("Setting speed to ");
      Serial.println(speed);

      // And finally, we'll set the speed of the motor!

      analogWrite(motorPin, speed);
    }
  }
}

Code To Note

while (Serial.available() > 0)

The Galileo’s serial port can be used to receive as well as send data. Because data could arrive at any time, the Galileostores, or “buffers” data coming into the port until you’re ready to use it. The Serial.available() command returns the number of characters that the port has received, but haven’t been used by your sketch yet. Zero means no data has arrived.

speed = Serial.parseInt();

If the port has data waiting for you, there are a number of ways for you to use it. Since we’re typing numbers into the port, we can use the handy Serial.parseInt() command to extract, or “parse” integer numbers from the characters it’s received. If you type “1” “0” “0” to the port, this function will return the number 100.

What You Should See

The DC Motor should spin if you have assembled the circuit’s components correctly, and also verified/uploaded the correct code. If your circuit is not working check the troubleshooting section.

Real World Application

Radio Controlled (RC) cars use Direct Current (DC) motors to turn the wheels for propulsion.

Troubleshooting

Motor Not Spinning

If you sourced your own transistor, double check with the data sheet that the pinout is compatible with a P2N2222AG (many are reversed).

Still No Luck

If you sourced your own motor, double check that it will work with 5 volts and that it does not draw too much power.

Still Not Working

Sometimes the Galileo will disconnect from the computer. Try un-plugging and then re-plugging it into your USB port.

Experiment 13: Using Relays

Introduction

In this circuit, we are going to use some of the lessons we learned in experiment 12 to control a relay. A relay is basically an electrically controlled mechanical switch. Inside that harmless looking plastic box is an electromagnet that, when it gets a jolt of energy, causes a switch to trip. In this circuit, you’ll learn how to control a relay like a pro – giving your Galileo even more powerful abilities!

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x RedBoard or Arduino Uno
  • 2x LEDs
  • 2x 330Ω Resistors
  • 1x Relay (SPDT)
  • 1x Diode 1N4148
  • 1x NPN Transistor
  • 14x Jumper Wires

Didn’t get the SIK?

If you are following through this experiment and didn’t get the SIK, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

In stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Transistor - NPN (P2N2222A)

Transistor - NPN (P2N2222A)

In stock COM-12852

This is the P2N2222A, an NPN silicon BJT (Bipolar Junction Transistor). This little transistor can help in your project by be…

0.5
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

In stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

1/6 Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 330Ohm resistors make excellent…

0.95
LED - Assorted (20 pack)

LED - Assorted (20 pack)

In stock COM-12062

We all know that you can never get too many LEDs. Don't worry, we've got you covered. This is a pack of basic red, yellow, bl…

2.95
Diode Small Signal - 1N4148

Diode Small Signal - 1N4148

In stock COM-08588

This is a very common signal diode - 1N4148. Use this for signals up to 200mA of current. If you need a bunch of these, you…

0.15
Relay SPDT Sealed

Relay SPDT Sealed

In stock COM-00100

These are high quality Single Pole - Double Throw (SPDT) sealed relays. Use them to switch high voltage, and/or high current …

1.95

You will also need either a RedBoard or Arduino Uno R3.

RedBoard - Programmed with Arduino

RedBoard - Programmed with Arduino

Only 5 left! DEV-12757

At SparkFun we use many Arduinos and we're always looking for the simplest, most stable one. Each board is a bit different an…

19.95
Arduino Uno- R3 SMD

Arduino Uno- R3 SMD

In stock DEV-11224

This is the new Arduino Uno R3. In addition to all the features of the previous board, the Uno now uses an ATmega16U2 instead…

29.95

Suggested Reading

Before continuing on with this experiment, we recommend you be familiar with the concepts in the following tutorial:

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram for RedBoard

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Fritzing Diagram for Arduino

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 13 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > examples > SIK Guide Code > Circuit_13

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Inventor's Kit
Example sketch 13

RELAYS

  Use a transistor to drive a relay

  A relay is a electrically-controlled mechanical switch.
  It can control much more voltage and current than an Arduino pin
  (or the transistor included in your kit) can. If you want to use
  the Arduino to control a 120V bulb, coffee maker, or other high-
  power device, a relay is an excellent way to do that. Because
  the relay needs more power to switch than an Arduino pin can
  provide, we'll use a transistor to drive the relay in exactly
  the same way we used a transistor to drive a motor in circuit 12.

  A relay consists of a coil of wire, and switch contacts. When
  you apply power to the coil, it becomes magnetized, and pulls
  the switch contacts closed. Since the switch contacts are
  completely isolated from the Arduino, you can safely use a
  relay to control normally dangerous voltages (but please only do
  this if you already know how to safely work with high voltage!).

  The relay has three contact pins, COM (common), NC (Normally
  Closed), and NO (Normally Open). When the relay is turned off,
  the COM pin is connected to the NC (Normally Closed) pin. When
  the relay is turned on, the COM pin is connected to the NO
  (Normally Open) pin.

  This code is very simple - it turns the relay on for one second,
  and off for one second, the same as the blink sketch!

Hardware connections:

  Transistor:

    The transistor has three pins. Looking at the flat side with
    the pins down, the order is COLLECTOR, BASE, EMITTER.

    Connect the BASE pin through a 1K resistor to digital pin 2.

    Connect the EMITTER pin to GND.

  Relay coil:

    The relay has pins for a coil (which you use to control the
    relay), and contacts (which you connect to the device you'd
    like to switch). The top or bottom of the relay should have
    a symbol indicating the coil pins.

    Connect one side of the coil to the COLLECTOR pin
    on the transistor.

    Connect other side of the coil to 5V.

  Diode:

    The relay has a coil that you energize to close the switch.
    When you disconnect power from a coil, the coil will generate
    a voltage spike that can damage the transistor. This diode
    protects the transistor from the voltage spike.

    Connect the side of the diode with the band (cathode) to 5V

    Connect the other side of the diode (anode) to the COLLECTOR
    pin of the transistor.

  Relay contacts and LEDs:

    We'll use the relay contacts to turn LEDs on and off, but you
    can use them to switch almost anything on and off.

    Connect the COMMON side of the switch to a 330 Ohm resistor.
    Connect the other side of the above resistor to 5V.

    Connect the NC (Normally Closed) side of the switch to the
    positive (longer) leg of LED 1.

    Connect the NO (Normally Open) side of the switch to the
    positive (longer) leg of LED 2.

    Connect the negative sides (shorter leg) of both LEDs to GND.

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/


const int relayPin = 2;     // use this pin to drive the transistor
const int timeDelay = 1000; // delay in ms for on and off phases

// You can make timeDelay shorter, but note that relays, being
// mechanical devices, will wear out quickly if you try to drive
// them too fast.


void setup()
{
  pinMode(relayPin, OUTPUT);  // set pin as an output
}


void loop()
{
  digitalWrite(relayPin, HIGH);  // turn the relay on

  delay(timeDelay);              // wait for one second

  digitalWrite(relayPin, LOW);   // turn the relay off

  delay(timeDelay);              // wait for one second
}

Code To Note

digitalWrite(relayPin, HIGH);

When we turn on the transistor, which in turn energizes the relay’s coil, the relay’s switch contacts are closed. This connects the relay’s COM pin to the NO (Normally Open) pin. Whatever you’ve connected using these pins will turn on. (Here we’re using LEDs, but this could be almost anything.)

digitalWrite(relayPin, LOW);

The relay has an additional contact called NC (Normally Closed). The NC pin is connected to the COM pin when the relay is OFF. You can use either pin depending on whether something should be normally on or normally off. You can also use both pins to alternate power to two devices, much like railroad crossing warning lights.

What You Should See

You should be able to hear the relay contacts click, and see the two LEDs alternate illuminating at 1-second intervals. If you don’t, double-check that you have assembled the circuit correctly, and uploaded the correct sketch to the board. Also, see the troubleshooting section.

Real World Application

Garage door openers use relays to operate. You might be able to hear the clicking if you listen closely.

Troubleshooting

LEDs Not Lighting

Double-check that you’ve plugged them in correctly. The longer lead (and non-flat edge of the plastic flange) is the positive lead.

No Clicking Sound

The transistor or coil portion of the circuit isn’t quite working. Check the transistor is plugged in the right way.

Not Quite Working

The included relays are designed to be soldered rather than used in a breadboard. As such you may need to press it in to ensure it works (and it may pop out occasionally).

When you’re building the circuit be careful not to mix up the temperature sensor and the transistor, they’re almost identical.

Experiment 14: Using a Shift Register

Introduction

Now we are going to step into the world of ICs (integrated circuits). In this circuit, you’ll learn all about using a shift register (also called a serial-to-parallel converter). The shift register will give your RedBoard or Arduino Uno R3 an additional eight outputs, using only three pins on your board. For this circuit, you’ll practice by using the shift register to control eight LEDs.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x RedBoard or Arduino Uno
  • 8x LEDs
  • 8x 330Ω Resistors
  • 1x Shift Register 8-Bit - 74HC595
  • 19x Jumper Wires

Didn’t get the SIK?

If you are following through this experiment and didn’t get the SIK, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

In stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

In stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

1/6 Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 330Ohm resistors make excellent…

0.95
LED - Assorted (20 pack)

LED - Assorted (20 pack)

In stock COM-12062

We all know that you can never get too many LEDs. Don't worry, we've got you covered. This is a pack of basic red, yellow, bl…

2.95
Shift Register 8-Bit - 74HC595

Shift Register 8-Bit - 74HC595

In stock COM-00733

Simple shift register IC. Clock in data and latch it to free up IO pins on your micro. Check out this [tutorial](http://dln…

1.5

You will also need either a RedBoard or Arduino Uno R3.

RedBoard - Programmed with Arduino

RedBoard - Programmed with Arduino

Only 5 left! DEV-12757

At SparkFun we use many Arduinos and we're always looking for the simplest, most stable one. Each board is a bit different an…

19.95
Arduino Uno- R3 SMD

Arduino Uno- R3 SMD

In stock DEV-11224

This is the new Arduino Uno R3. In addition to all the features of the previous board, the Uno now uses an ATmega16U2 instead…

29.95

Suggested Reading

Before continuing on with this experiment, we recommend you be familiar with the concepts in the following tutorial:

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

For the shift register, align notch on top, in-between “e1” and “f1” on the breadboard. The notch indicates where pin 1 is.

Fritzing Diagram for RedBoard

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Fritzing Diagram for Arduino

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 14 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > examples > SIK Guide Code > Circuit_14

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Inventor's Kit
Example sketch 13

SHIFT REGISTER

  Use a shift register to turn three pins into eight (or more!)
  outputs

  An integrated circuit ("IC"), or "chip", is a self-contained
  circuit built into a small plastic package. (If you look closely
  at your Arduino board you'll see a number of ICs.) There are
  thousands of different types of ICs available that you can use
  to perform many useful functions.

  The 74HC595 shift register in your kit is an IC that has eight
  digital outputs. To use these outputs, we'll use a new interface
  called SPI (Serial Peripheral Interface). It's like the TX and
  RX you're used to, but has an additional "clock" line that
  controls the speed of the data transfer. Many parts use SPI
  for communications, so the Arduino offers simple commands called
  shiftIn() and shiftOut() to access these parts.

  This IC lets you use three digital pins on your Arduino to
  control eight digital outputs on the chip. And if you need
  even more outputs, you can daisy-chain multiple shift registers
  together, allowing an almost unlimited number of outputs from
  the same three Arduino pins! See the shift register datasheet
  for details:

  http://www.sparkfun.com/datasheets/IC/SN74HC595.pdf

Hardware connections:

  Shift register:

    Plug in the chip so it bridges the center "canyon"
    on the breadboard.

    The shift register has 16 pins. They are numbered
    counterclockwise starting at the pin 1 mark (notch
    in the end of the chip). See the datasheet above
    for a diagram.

    74HC595 pin     LED pin     Arduino pin

    1  (QB)     LED 2 +
    2  (QC)     LED 3 +
    3  (QD)     LED 4 +
    4  (QE)     LED 5 +
    5  (QF)     LED 6 +
    6  (QG)     LED 7 +
    7  (QH)     LED 8 +
    8  (GND)                GND

    9  (QH*)
    10 (SRCLR*)             5V
    11 (SRCLK)              Digital 3
    12 (RCLK)               Digital 4
    13 (OE*)                GND
    14 (SER)                Digital 2
    15 (QA)     LED 1 +
    16 (VCC)                5V

  LEDs:

    After making the above connections to the positive (longer)
    legs of the LEDs, connect the negative side (short lead) of
    each LED to a 330 Ohm resistor, and connect the other side
    of each resistor to GND.

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG
*/


// Pin definitions:
// The 74HC595 uses a type of serial connection called SPI
// (Serial Peripheral Interface) that requires three pins:

int datapin = 2;
int clockpin = 3;
int latchpin = 4;

// We'll also declare a global variable for the data we're
// sending to the shift register:

byte data = 0;


void setup()
{
  // Set the three SPI pins to be outputs:

  pinMode(datapin, OUTPUT);
  pinMode(clockpin, OUTPUT);
  pinMode(latchpin, OUTPUT);
}


void loop()
{
  // We're going to use the same functions we played with back
  // in circuit 04, "Multiple LEDs", we've just replaced
  // digitalWrite() with a new function called shiftWrite()
  // (see below). We also have a new function that demonstrates
  // binary counting.

  // To try the different functions below, uncomment the one
  // you want to run, and comment out the remaining ones to
  // disable them from running.

  oneAfterAnother();      // All on, all off

  //oneOnAtATime();       // Scroll down the line

  //pingPong();           // Like above, but back and forth

  //randomLED();          // Blink random LEDs

  //marquee();

  //binaryCount();        // Bit patterns from 0 to 255
}


void shiftWrite(int desiredPin, boolean desiredState)

// This function lets you make the shift register outputs
// HIGH or LOW in exactly the same way that you use digitalWrite().

// Like digitalWrite(), this function takes two parameters:

//    "desiredPin" is the shift register output pin
//    you want to affect (0-7)

//    "desiredState" is whether you want that output
//    to be HIGH or LOW

// Inside the Arduino, numbers are stored as arrays of "bits",
// each of which is a single 1 or 0 value. Because a "byte" type
// is also eight bits, we'll use a byte (which we named "data"
// at the top of this sketch) to send data to the shift register.
// If a bit in the byte is "1", the output will be HIGH. If the bit
// is "0", the output will be LOW.

// To turn the individual bits in "data" on and off, we'll use
// a new Arduino commands called bitWrite(), which can make
// individual bits in a number 1 or 0.
{
  // First we'll alter the global variable "data", changing the
  // desired bit to 1 or 0:

  bitWrite(data,desiredPin,desiredState);

  // Now we'll actually send that data to the shift register.
  // The shiftOut() function does all the hard work of
  // manipulating the data and clock pins to move the data
  // into the shift register:

  shiftOut(datapin, clockpin, MSBFIRST, data);

  // Once the data is in the shift register, we still need to
  // make it appear at the outputs. We'll toggle the state of
  // the latchPin, which will signal the shift register to "latch"
  // the data to the outputs. (Latch activates on the high-to
  // -low transition).

  digitalWrite(latchpin, HIGH);
  digitalWrite(latchpin, LOW);
}


/*
oneAfterAnother()

This function will light one LED, delay for delayTime, then light
the next LED, and repeat until all the LEDs are on. It will then
turn them off in the reverse order.
*/

void oneAfterAnother()
{
  int index;
  int delayTime = 100; // Time (milliseconds) to pause between LEDs
                       // Make this smaller for faster switching

  // Turn all the LEDs on:

  // This for() loop will step index from 0 to 7
  // (putting "++" after a variable means add one to it)
  // and will then use digitalWrite() to turn that LED on.

  for(index = 0; index <= 7; index++)
  {
    shiftWrite(index, HIGH);
    delay(delayTime);
  }

  // Turn all the LEDs off:

  // This for() loop will step index from 7 to 0
  // (putting "--" after a variable means subtract one from it)
  // and will then use digitalWrite() to turn that LED off.

  for(index = 7; index >= 0; index--)
  {
    shiftWrite(index, LOW);
    delay(delayTime);
  }
}


/*
oneOnAtATime()

This function will step through the LEDs, lighting one at at time.
*/

void oneOnAtATime()
{
  int index;
  int delayTime = 100; // Time (milliseconds) to pause between LEDs
                       // Make this smaller for faster switching

  // step through the LEDs, from 0 to 7

  for(index = 0; index <= 7; index++)
  {
    shiftWrite(index, HIGH);    // turn LED on
    delay(delayTime);       // pause to slow down the sequence
    shiftWrite(index, LOW); // turn LED off
  }
}


/*
pingPong()

This function will step through the LEDs, lighting one at at time,
in both directions.
*/

void pingPong()
{
  int index;
  int delayTime = 100; // time (milliseconds) to pause between LEDs
                       // make this smaller for faster switching

  // step through the LEDs, from 0 to 7

  for(index = 0; index <= 7; index++)
  {
    shiftWrite(index, HIGH);    // turn LED on
    delay(delayTime);       // pause to slow down the sequence
    shiftWrite(index, LOW); // turn LED off
  }

  // step through the LEDs, from 7 to 0

  for(index = 7; index >= 0; index--)
  {
    shiftWrite(index, HIGH);    // turn LED on
    delay(delayTime);       // pause to slow down the sequence
    shiftWrite(index, LOW); // turn LED off
  }
}


/*
randomLED()

This function will turn on random LEDs. Can you modify it so it
also lights them for random times?
*/

void randomLED()
{
  int index;
  int delayTime = 100; // time (milliseconds) to pause between LEDs
                       // make this smaller for faster switching

  // The random() function will return a semi-random number each
  // time it is called. See http://arduino.cc/en/Reference/Random
  // for tips on how to make random() more random.

  index = random(8);    // pick a random number between 0 and 7

  shiftWrite(index, HIGH);  // turn LED on
  delay(delayTime);     // pause to slow down the sequence
  shiftWrite(index, LOW);   // turn LED off
}


/*
marquee()

This function will mimic "chase lights" like those around signs.
*/

void marquee()
{
  int index;
  int delayTime = 200; // Time (milliseconds) to pause between LEDs
                       // Make this smaller for faster switching

  // Step through the first four LEDs
  // (We'll light up one in the lower 4 and one in the upper 4)

  for(index = 0; index <= 3; index++)
  {
    shiftWrite(index, HIGH);    // Turn a LED on
    shiftWrite(index+4, HIGH);  // Skip four, and turn that LED on
    delay(delayTime);       // Pause to slow down the sequence
    shiftWrite(index, LOW); // Turn both LEDs off
    shiftWrite(index+4, LOW);
  }
}


/*
binaryCount()

Numbers are stored internally in the Arduino as arrays of "bits",
each of which is a 1 or 0. Just like the base-10 numbers we use
every day, The position of the bit affects the magnitude of its
contribution to the total number:

Bit position   Contribution
0              1
1              2
2              4
3              8
4              16
5              32
6              64
7              128

To build any number from 0 to 255 from the above 8 bits, just
select the contributions you need to make. The bits will then be
1 if you use that contribution, and 0 if you don't.

This function will increment the "data" variable from 0 to 255
and repeat. When we send this value to the shift register and LEDs,
you can see the on-off pattern of the eight bits that make up the
byte. See http://www.arduino.cc/playground/Code/BitMath for more
information on binary numbers.
*/

void binaryCount()
{
  int delayTime = 1000; // time (milliseconds) to pause between LEDs
                        // make this smaller for faster switching

  // Send the data byte to the shift register:

  shiftOut(datapin, clockpin, MSBFIRST, data);

  // Toggle the latch pin to make the data appear at the outputs:

  digitalWrite(latchpin, HIGH);
  digitalWrite(latchpin, LOW);

  // Add one to data, and repeat!
  // (Because a byte type can only store numbers from 0 to 255,
  // if we add more than that, it will "roll around" back to 0
  // and start over).

  data++;

  // Delay so you can see what's going on:

  delay(delayTime);
}

Code To Note

shiftOut(datapin, clockpin, MSBFIRST, data);

You’ll communicate with the shift register (and a lot of other parts) using an interface called SPI, or Serial Peripheral Interface. This interface uses a data line and a separate clock line that work together to move data in or out of the Galileo at high speed. The MSBFIRST parameter specifies the order in which to send the individual bits, in this case we’re sending the Most Significant Bit first.

bitWrite(data, desiredPin, desiredState);

Bits are the smallest possible piece of memory in a computer; each one can store either a “1” or a “0”. Larger numbers are stored as arrays of bits. Sometimes we want to manipulate these bits directly, for example now when we’re sending eight bits to the shift register and we want to make them 1 or 0 to turn the LEDs on or off. The Galileo has several commands, such as bitWrite(), that make this easy to do.

What You Should See

You should see the LEDs light up similarly to experiment 4 (but this time, you’re using a shift register). If they aren’t, make sure you have assembled the circuit correctly and verified and uploaded the code to your board. See the troubleshooting section.

Real World Application

Similar to experiment 4, a scrolling marquee display delivers a message with multiple LEDs. Essentially the same task the shift register achieves here in experiment 14.

Troubleshooting

The Arduino’s power LED goes out

This happened to us a couple of times, it happens when the chip is inserted backward. If you fix it quickly nothing will break.

Not Quite Working

Sorry to sound like a broken record but it is probably something as simple as a crossed wire.

Frustration

Shoot us an e-mail, this circuit is both simple and complex at the same time. We want to hear about problems you have so we can address them in future editions: techsupport@sparkfun.com

Experiment 15: Using an LCD

Introduction

In this circuit, you’ll learn about how to use an LCD. An LCD, or liquid crystal display, is a simple screen that can display commands, bits of information, or readings from your sensor - all depending on how you program your board. In this circuit, you’ll learn the basics of incorporating an LCD into your project.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x RedBoard or Arduino Uno
  • 1x Potentiometer
  • 1x LCD
  • 16x Jumper Wires

Didn’t get the SIK?

If you are following through this experiment and didn’t get the SIK, we suggest using these parts:

Trimpot 10K with Knob

Trimpot 10K with Knob

In stock COM-09806

There are lots of trimpots out there. Some are very large, some so small they require a screwdriver. Here at SparkFun, we jus…

0.95
Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

In stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

In stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Basic 16x2 Character LCD - White on Black 5V

Basic 16x2 Character LCD - White on Black 5V

In stock LCD-00709

This is a basic 16 character by 2 line display with a snazzy black background with white characters. Utilizes the extremely c…

15.95

You will also need either a RedBoard or Arduino Uno R3.

RedBoard - Programmed with Arduino

RedBoard - Programmed with Arduino

Only 5 left! DEV-12757

At SparkFun we use many Arduinos and we're always looking for the simplest, most stable one. Each board is a bit different an…

19.95
Arduino Uno- R3 SMD

Arduino Uno- R3 SMD

In stock DEV-11224

This is the new Arduino Uno R3. In addition to all the features of the previous board, the Uno now uses an ATmega16U2 instead…

29.95

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram for RedBoard

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Fritzing Diagram for Arduino

alt text

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 15 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > examples > SIK Guide Code > Circuit_15

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Inventor's Kit
Example sketch 15

LIQUID CRYSTAL DISPLAY (LCD)

  A Liquid Crystal Display (LCD) is a sophisticated module
  that can be used to display text or numeric data. The display
  included in your SIK features two lines of 16 characters, and
  a backlight so it can be used at night.

  If you've been using the Serial Monitor to output data,
  you'll find that a LCD provides many of the same benefits
  without needing to drag a large computer around.

  This sketch will show you how to connect an LCD to your Arduino
  and display any data you wish.

Hardware connections:

  The LCD has a 16-pin male header attached to it along the top
  edge. Pin 1 is the pin closest to the corner of the LCD.
  Pin 16 is the pin closest to the center of the LCD.

  Plug the LCD into your breadboard.

  As usual, you will want to connect the + and - power rails
  on the side of the breadboard to 5V and GND on your Arduino.

  Plug your 10K potentiometer into three unused rows on your
  breadboard. Connect one side of the potentiometer to 5V,
  and the other side to GND (it doesn't matter which). When you
  run this sketch, you'll use the potentiometer to adjust the
  contrast of the LCD so you can see the display.

  Now connect the LCD pins. Remember that pin 1 on the LCD
  is the one closest to the corner. Start there and work your
  way up.

  1 to GND
  2 to 5V
  3 to the center pin on the potentiometer
  4 to Galileo digital pin 12
  5 to GND
  6 to Galileo  digital pin 11
  7 (no connection)
  8 (no connection)
  9 (no connection)
  10 (no connection)
  11 to Galileo  digital pin 5
  12 to Galileo  digital pin 4
  13 to Galileo  digital pin 3
  14 to Galileo  digital pin 2
  15 to 5V
  16 to GND

  Once everything is connected, load this sketch into the
  Galileo, and adjust the potentiometer until the display
  is clear.

Library

  The LCD has a chip built into it that controls all the
  individual dots that make up the display, and obeys commands
  sent to it by the the Arduino. The chip knows the dot patterns
  that make up all the text characters, saving you a lot of work.

  To communicate with this chip, we'll use the LiquidCrystal
  library, which is one of the standard libraries that comes
  with the Arduino. This library does most of the hard work
  of interfacing to the LCD; all you need to pick a location
  on the display and send your data!

Tips

  The LCD comes with a protective film over the display that
  you can peel off (but be careful of the display surface as
  it scratches easily).

  The LCD has a backlight that will light up when you turn on
  your Arduino. If the backlight doesn't turn on, check your
  connections.

  As we said above, the potentiometer adjusts the contrast of
  the display. If you can't see anything when you run the sketch,
  turn the potentiometer's knob until the text is clear.

This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 1.0 2/2013 MDG
*/

// Load the LiquidCrystal library, which will give us
// commands to interface to the LCD:

#include <LiquidCrystal.h>

// Initialize the library with the pins we're using.
// (Note that you can use different pins if needed.)
// See http://arduino.cc/en/Reference/LiquidCrystal
// for more information:

LiquidCrystal lcd(12,11,5,4,3,2);

void setup()
{
  // The LiquidCrystal library can be used with many different
  // LCD sizes. We're using one that's 2 lines of 16 characters,
  // so we'll inform the library of that:

  lcd.begin(16, 2);

  // Data sent to the display will stay there until it's
  // overwritten or power is removed. This can be a problem
  // when you upload a new sketch to the Arduino but old data
  // remains on the display. Let's clear the LCD using the
  // clear() command from the LiquidCrystal library:

  lcd.clear();

  // Now we'll display a message on the LCD!

  // Just as with the Arduino IDE, there's a cursor that
  // determines where the data you type will appear. By default,
  // this cursor is invisible, though you can make it visible
  // with other library commands if you wish.

  // When the display powers up, the invisible cursor starts
  // on the top row and first column.

  lcd.print("hello, world!");

  // Adjusting the contrast (IMPORTANT!)

  // When you run the sketch for the first time, there's a
  // very good chance you won't see anything on the LCD display.
  // This is because the contrast likely won't be set correctly.
  // Don't worry, it's easy to set, and once you set it you won't
  // need to change it again.

  // Run the sketch, then turn the potentiometer until you can
  // clearly see the "hello, world!" text. If you still can't
  // see anything, check all of your connections, and ensure that
  // the sketch was successfully uploaded to the Arduino.
}

void loop()
{
  // You can move the invisible cursor to any location on the
  // LCD before sending data. Counting starts from 0, so the top
  // line is line 0 and the bottom line is line 1. Columns range
  // from 0 on the left side, to 15 on the right.

  // In additon to the "hello, world!" printed above, let's
  // display a running count of the seconds since the Arduino
  // was last reset. Note that the data you send to the display
  // will stay there unless you erase it by overwriting it or
  // sending a lcd.clear() command.

  // Here we'll set the invisible cursor to the first column
  // (column 0) of the second line (line 1):

  lcd.setCursor(0,1);

  // Now we'll print the number of seconds (millis() / 1000)
  // since the Arduino last reset:

  lcd.print(millis()/1000);

  // TIP: Since the numeric data we're sending is always growing
  // in length, new values will always overwrite the previous ones.
  // However, if you want to display varying or decreasing numbers
  // like a countdown, you'll find that the display will leave
  // "orphan" characters when the new value is shorter than the
  // old one.

  // To prevent this, you'll need to erase the old number before
  // writing the new one. You can do this by overwriting the
  // last number with spaces. If you erase the old number and
  // immediately write the new one, the momentary erase won't
  // be noticeable. Here's a typical sequence of code:

  // lcd.setCursor(0,1);   // Set the cursor to the position
  // lcd.print(""); // Erase the largest possible number
  // lcd.setCursor(0,1);   // Reset the cursor to the original position
  // lcd.print(millis()/1000); // Print our value

  // NEXT STEPS:

  // Now you know the basics of hooking up an LCD to the Arduino,
  // and sending text and numeric data to the display!

  // The LCD library has many commands for turning the
  // cursor on and off, scrolling the screen, etc. See:
  // http://arduino.cc/en/Reference/LiquidCrystal
  // for more information.

  // Arduino also comes with a number of built-in examples
  // showing off the features of the LiquidCrystal library.
  // These are locted in the file/examples/LiquidCrystal menu.

  // Have fun, and let us know what you create!
  // Your friends at SparkFun.
}

Code To Note

#include <LiquidCrystal.h>

This bit of code tells your Arduino IDE to include the library for a simple LCD display. Without it, none of the commands will work, so make sure you include it!

lcd.print(“hello, world!”);

This is the first time you’ll fire something up on your screen. You may need to adjust the contrast to make it visible. Twist the potentiometer until you can clearly see the text!

What You Should See

Initially, you should see the words “hello, world!” pop up on your LCD. Remember you can adjust the contrast using the potentiometer if you can’t make out the words clearly. If you have any issues, make sure your code is correct and double-check your connections.

Real World Application

LCDs are everywhere! From advanced LCDs like your television, to simple notification screens, this is a very common and useful display!

The Screen is Blank or Completely Lit?

Fiddle with the contrast by twisting the potentiometer. If it’s incorrectly adjusted, you won’t be able to read the text.

Not Working At All?

Double check the code, specifically that you include the LCD library.

Screen Is Flickering

Double check your connections to your breadboard and Arduino.

Experiment 16: Simon Says

Introduction

Now that we’ve learned all the basics behind the components in the SIK experiments, let’s put them all together to make some fun. This circuit will show you how to create your own Simon Says game. Using some LEDs, some buttons, a buzzer, and some resistors, you can create this and other exciting games with the RedBoard or Arduino Uno R3.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x RedBoard or Arduino Uno
  • 4x LEDs
  • 1x Piezo Buzzer
  • 4x 330Ω Resistors
  • 4x Push Buttons
  • 17x Jumper Wires

Didn’t get the SIK?

If you are following through this experiment and didn’t get the SIK, we suggest using these parts:

Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

In stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

In stock COM-11507

1/6 Watt, +/- 5% tolerance PTH resistors. Commonly used in breadboards and perf boards, these 330Ohm resistors make excellent…

0.95
Momentary Pushbutton Switch - 12mm Square

Momentary Pushbutton Switch - 12mm Square

In stock COM-09190

This is a standard 12mm square momentary button. What we really like is the large button head and good tactile feel (it 'clic…

0.5
LED - Assorted (20 pack)

LED - Assorted (20 pack)

In stock COM-12062

We all know that you can never get too many LEDs. Don't worry, we've got you covered. This is a pack of basic red, yellow, bl…

2.95
Piezo Speaker - PC Mount 12mm 2.048kHz

Piezo Speaker - PC Mount 12mm 2.048kHz

In stock COM-07950

This is a small 12mm round speaker that operates around the audible 2kHz range. You can use these speakers to create simple m…

1.95

You will also need either a RedBoard or Arduino Uno R3.

RedBoard - Programmed with Arduino

RedBoard - Programmed with Arduino

Only 5 left! DEV-12757

At SparkFun we use many Arduinos and we're always looking for the simplest, most stable one. Each board is a bit different an…

19.95
Arduino Uno- R3 SMD

Arduino Uno- R3 SMD

In stock DEV-11224

This is the new Arduino Uno R3. In addition to all the features of the previous board, the Uno now uses an ATmega16U2 instead…

29.95

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected. Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram for RedBoard

alt text

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger image.

Fritzing Diagram for Arduino

alt text

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 16 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > examples > SIK Guide Code > Circuit_16

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
 SparkFun Inventor's Kit
 Example sketch 16
 Spark Fun Electronics
 Oct. 7, 2014

 Simon Says is a memory game. Start the game by pressing one of the four buttons. When a button lights up,
 press the button, repeating the sequence. The sequence will get longer and longer. The game is won after
 13 rounds.

 Generates random sequence, plays music, and displays button lights.

 Simon tones from Wikipedia
 - A (red, upper left) - 440Hz - 2.272ms - 1.136ms pulse
 - a (green, upper right, an octave higher than A) - 880Hz - 1.136ms,
 0.568ms pulse
 - D (blue, lower left, a perfect fourth higher than the upper left)
 587.33Hz - 1.702ms - 0.851ms pulse
 - G (yellow, lower right, a perfect fourth higher than the lower left) -
 784Hz - 1.276ms - 0.638ms pulse

 Simon Says game originally written in C for the PIC16F88.
 Ported for the ATmega168, then ATmega328, then Arduino 1.0.
 Fixes and cleanup by Joshua Neal <joshua[at]trochotron.com>

 This sketch was written by SparkFun Electronics,
 with lots of help from the Arduino community.
 This code is completely free for any use.
 Visit http://www.arduino.cc to learn about the Arduino.
 */

/*************************************************
* Public Constants
*************************************************/
#define NOTE_B0 31
#define NOTE_C1 33
#define NOTE_CS1 35
#define NOTE_D1 37
#define NOTE_DS1 39
#define NOTE_E1 41
#define NOTE_F1 44
#define NOTE_FS1 46
#define NOTE_G1 49
#define NOTE_GS1 52
#define NOTE_A1 55
#define NOTE_AS1 58
#define NOTE_B1 62
#define NOTE_C2 65
#define NOTE_CS2 69
#define NOTE_D2 73
#define NOTE_DS2 78
#define NOTE_E2 82
#define NOTE_F2 87
#define NOTE_FS2 93
#define NOTE_G2 98
#define NOTE_GS2 104
#define NOTE_A2 110
#define NOTE_AS2 117
#define NOTE_B2 123
#define NOTE_C3 131
#define NOTE_CS3 139
#define NOTE_D3 147
#define NOTE_DS3 156
#define NOTE_E3 165
#define NOTE_F3 175
#define NOTE_FS3 185
#define NOTE_G3 196
#define NOTE_GS3 208
#define NOTE_A3 220
#define NOTE_AS3 233
#define NOTE_B3 247
#define NOTE_C4 262
#define NOTE_CS4 277
#define NOTE_D4 294
#define NOTE_DS4 311
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_FS4 370
#define NOTE_G4 392
#define NOTE_GS4 415
#define NOTE_A4 440
#define NOTE_AS4 466
#define NOTE_B4 494
#define NOTE_C5 523
#define NOTE_CS5 554
#define NOTE_D5 587
#define NOTE_DS5 622
#define NOTE_E5 659
#define NOTE_F5 698
#define NOTE_FS5 740
#define NOTE_G5 784
#define NOTE_GS5 831
#define NOTE_A5 880
#define NOTE_AS5 932
#define NOTE_B5 988
#define NOTE_C6 1047
#define NOTE_CS6 1109
#define NOTE_D6 1175
#define NOTE_DS6 1245
#define NOTE_E6 1319
#define NOTE_F6 1397
#define NOTE_FS6 1480
#define NOTE_G6 1568
#define NOTE_GS6 1661
#define NOTE_A6 1760
#define NOTE_AS6 1865
#define NOTE_B6 1976
#define NOTE_C7 2093
#define NOTE_CS7 2217
#define NOTE_D7 2349
#define NOTE_DS7 2489
#define NOTE_E7 2637
#define NOTE_F7 2794
#define NOTE_FS7 2960
#define NOTE_G7 3136
#define NOTE_GS7 3322
#define NOTE_A7 3520
#define NOTE_AS7 3729
#define NOTE_B7 3951
#define NOTE_C8 4186
#define NOTE_CS8 4435
#define NOTE_D8 4699
#define NOTE_DS8 4978

#define CHOICE_OFF      0 //Used to control LEDs
#define CHOICE_NONE     0 //Used to check buttons
#define CHOICE_RED  (1 << 0)
#define CHOICE_GREEN    (1 << 1)
#define CHOICE_BLUE (1 << 2)
#define CHOICE_YELLOW   (1 << 3)

#define LED_RED     10
#define LED_GREEN   3
#define LED_BLUE    13
#define LED_YELLOW  5

// Button pin definitions
#define BUTTON_RED    9
#define BUTTON_GREEN  2
#define BUTTON_BLUE   12
#define BUTTON_YELLOW 6

// Buzzer pin definitions
#define BUZZER1  4
#define BUZZER2  7

// Define game parameters
#define ROUNDS_TO_WIN      13 //Number of rounds to succesfully remember before you win. 13 is do-able.
#define ENTRY_TIME_LIMIT   3000 //Amount of time to press a button before game times out. 3000ms = 3 sec

#define MODE_MEMORY  0
#define MODE_BATTLE  1
#define MODE_BEEGEES 2

// Game state variables
byte gameMode = MODE_MEMORY; //By default, let's play the memory game
byte gameBoard[32]; //Contains the combination of buttons as we advance
byte gameRound = 0; //Counts the number of succesful rounds the player has made it through

void setup()
{
  //Setup hardware inputs/outputs. These pins are defined in the hardware_versions header file

  //Enable pull ups on inputs
  pinMode(BUTTON_RED, INPUT_PULLUP);
  pinMode(BUTTON_GREEN, INPUT_PULLUP);
  pinMode(BUTTON_BLUE, INPUT_PULLUP);
  pinMode(BUTTON_YELLOW, INPUT_PULLUP);

  pinMode(LED_RED, OUTPUT);
  pinMode(LED_GREEN, OUTPUT);
  pinMode(LED_BLUE, OUTPUT);
  pinMode(LED_YELLOW, OUTPUT);

  pinMode(BUZZER1, OUTPUT);
  pinMode(BUZZER2, OUTPUT);

  //Mode checking
  gameMode = MODE_MEMORY; // By default, we're going to play the memory game

  // Check to see if the lower right button is pressed
  if (checkButton() == CHOICE_YELLOW) play_beegees();

  // Check to see if upper right button is pressed
  if (checkButton() == CHOICE_GREEN)
  {
    gameMode = MODE_BATTLE; //Put game into battle mode

    //Turn on the upper right (green) LED
    setLEDs(CHOICE_GREEN);
    toner(CHOICE_GREEN, 150);

    setLEDs(CHOICE_RED | CHOICE_BLUE | CHOICE_YELLOW); // Turn on the other LEDs until you release button

    while(checkButton() != CHOICE_NONE) ; // Wait for user to stop pressing button

    //Now do nothing. Battle mode will be serviced in the main routine
  }

  play_winner(); // After setup is complete, say hello to the world
}

void loop()
{
  attractMode(); // Blink lights while waiting for user to press a button

  // Indicate the start of game play
  setLEDs(CHOICE_RED | CHOICE_GREEN | CHOICE_BLUE | CHOICE_YELLOW); // Turn all LEDs on
  delay(1000);
  setLEDs(CHOICE_OFF); // Turn off LEDs
  delay(250);

  if (gameMode == MODE_MEMORY)
  {
    // Play memory game and handle result
    if (play_memory() == true)
      play_winner(); // Player won, play winner tones
    else
      play_loser(); // Player lost, play loser tones
  }

  if (gameMode == MODE_BATTLE)
  {
    play_battle(); // Play game until someone loses

    play_loser(); // Player lost, play loser tones
  }
}

//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//The following functions are related to game play only

// Play the regular memory game
// Returns 0 if player loses, or 1 if player wins
boolean play_memory(void)
{
  randomSeed(millis()); // Seed the random generator with random amount of millis()

  gameRound = 0; // Reset the game to the beginning

  while (gameRound < ROUNDS_TO_WIN)
  {
    add_to_moves(); // Add a button to the current moves, then play them back

    playMoves(); // Play back the current game board

    // Then require the player to repeat the sequence.
    for (byte currentMove = 0 ; currentMove < gameRound ; currentMove++)
    {
      byte choice = wait_for_button(); // See what button the user presses

      if (choice == 0) return false; // If wait timed out, player loses

      if (choice != gameBoard[currentMove]) return false; // If the choice is incorect, player loses
    }

    delay(1000); // Player was correct, delay before playing moves
  }

  return true; // Player made it through all the rounds to win!
}

// Play the special 2 player battle mode
// A player begins by pressing a button then handing it to the other player
// That player repeats the button and adds one, then passes back.
// This function returns when someone loses
boolean play_battle(void)
{
  gameRound = 0; // Reset the game frame back to one frame

  while (1) // Loop until someone fails
  {
    byte newButton = wait_for_button(); // Wait for user to input next move
    gameBoard[gameRound++] = newButton; // Add this new button to the game array

    // Then require the player to repeat the sequence.
    for (byte currentMove = 0 ; currentMove < gameRound ; currentMove++)
    {
      byte choice = wait_for_button();

      if (choice == 0) return false; // If wait timed out, player loses.

      if (choice != gameBoard[currentMove]) return false; // If the choice is incorect, player loses.
    }

    delay(100); // Give the user an extra 100ms to hand the game to the other player
  }

  return true; // We should never get here
}

// Plays the current contents of the game moves
void playMoves(void)
{
  for (byte currentMove = 0 ; currentMove < gameRound ; currentMove++)
  {
    toner(gameBoard[currentMove], 150);

    // Wait some amount of time between button playback
    // Shorten this to make game harder
    delay(150); // 150 works well. 75 gets fast.
  }
}

// Adds a new random button to the game sequence, by sampling the timer
void add_to_moves(void)
{
  byte newButton = random(0, 4); //min (included), max (exluded)

  // We have to convert this number, 0 to 3, to CHOICEs
  if(newButton == 0) newButton = CHOICE_RED;
  else if(newButton == 1) newButton = CHOICE_GREEN;
  else if(newButton == 2) newButton = CHOICE_BLUE;
  else if(newButton == 3) newButton = CHOICE_YELLOW;

  gameBoard[gameRound++] = newButton; // Add this new button to the game array
}

//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//The following functions control the hardware

// Lights a given LEDs
// Pass in a byte that is made up from CHOICE_RED, CHOICE_YELLOW, etc
void setLEDs(byte leds)
{
  if ((leds & CHOICE_RED) != 0)
    digitalWrite(LED_RED, HIGH);
  else
    digitalWrite(LED_RED, LOW);

  if ((leds & CHOICE_GREEN) != 0)
    digitalWrite(LED_GREEN, HIGH);
  else
    digitalWrite(LED_GREEN, LOW);

  if ((leds & CHOICE_BLUE) != 0)
    digitalWrite(LED_BLUE, HIGH);
  else
    digitalWrite(LED_BLUE, LOW);

  if ((leds & CHOICE_YELLOW) != 0)
    digitalWrite(LED_YELLOW, HIGH);
  else
    digitalWrite(LED_YELLOW, LOW);
}

// Wait for a button to be pressed.
// Returns one of LED colors (LED_RED, etc.) if successful, 0 if timed out
byte wait_for_button(void)
{
  long startTime = millis(); // Remember the time we started the this loop

  while ( (millis() - startTime) < ENTRY_TIME_LIMIT) // Loop until too much time has passed
  {
    byte button = checkButton();

    if (button != CHOICE_NONE)
    {
      toner(button, 150); // Play the button the user just pressed

      while(checkButton() != CHOICE_NONE) ;  // Now let's wait for user to release button

      delay(10); // This helps with debouncing and accidental double taps

      return button;
    }

  }

  return CHOICE_NONE; // If we get here, we've timed out!
}

// Returns a '1' bit in the position corresponding to CHOICE_RED, CHOICE_GREEN, etc.
byte checkButton(void)
{
  if (digitalRead(BUTTON_RED) == 0) return(CHOICE_RED);
  else if (digitalRead(BUTTON_GREEN) == 0) return(CHOICE_GREEN);
  else if (digitalRead(BUTTON_BLUE) == 0) return(CHOICE_BLUE);
  else if (digitalRead(BUTTON_YELLOW) == 0) return(CHOICE_YELLOW);

  return(CHOICE_NONE); // If no button is pressed, return none
}

// Light an LED and play tone
// Red, upper left:     440Hz - 2.272ms - 1.136ms pulse
// Green, upper right:  880Hz - 1.136ms - 0.568ms pulse
// Blue, lower left:    587.33Hz - 1.702ms - 0.851ms pulse
// Yellow, lower right: 784Hz - 1.276ms - 0.638ms pulse
void toner(byte which, int buzz_length_ms)
{
  setLEDs(which); //Turn on a given LED

  //Play the sound associated with the given LED
  switch(which)
  {
  case CHOICE_RED:
    buzz_sound(buzz_length_ms, 1136);
    break;
  case CHOICE_GREEN:
    buzz_sound(buzz_length_ms, 568);
    break;
  case CHOICE_BLUE:
    buzz_sound(buzz_length_ms, 851);
    break;
  case CHOICE_YELLOW:
    buzz_sound(buzz_length_ms, 638);
    break;
  }

  setLEDs(CHOICE_OFF); // Turn off all LEDs
}

// Toggle buzzer every buzz_delay_us, for a duration of buzz_length_ms.
void buzz_sound(int buzz_length_ms, int buzz_delay_us)
{
  // Convert total play time from milliseconds to microseconds
  long buzz_length_us = buzz_length_ms * (long)1000;

  // Loop until the remaining play time is less than a single buzz_delay_us
  while (buzz_length_us > (buzz_delay_us * 2))
  {
    buzz_length_us -= buzz_delay_us * 2; //Decrease the remaining play time

    // Toggle the buzzer at various speeds
    digitalWrite(BUZZER1, LOW);
    digitalWrite(BUZZER2, HIGH);
    delayMicroseconds(buzz_delay_us);

    digitalWrite(BUZZER1, HIGH);
    digitalWrite(BUZZER2, LOW);
    delayMicroseconds(buzz_delay_us);
  }
}

// Play the winner sound and lights
void play_winner(void)
{
  setLEDs(CHOICE_GREEN | CHOICE_BLUE);
  winner_sound();
  setLEDs(CHOICE_RED | CHOICE_YELLOW);
  winner_sound();
  setLEDs(CHOICE_GREEN | CHOICE_BLUE);
  winner_sound();
  setLEDs(CHOICE_RED | CHOICE_YELLOW);
  winner_sound();
}

// Play the winner sound
// This is just a unique (annoying) sound we came up with, there is no magic to it
void winner_sound(void)
{
  // Toggle the buzzer at various speeds
  for (byte x = 250 ; x > 70 ; x--)
  {
    for (byte y = 0 ; y < 3 ; y++)
    {
      digitalWrite(BUZZER2, HIGH);
      digitalWrite(BUZZER1, LOW);
      delayMicroseconds(x);

      digitalWrite(BUZZER2, LOW);
      digitalWrite(BUZZER1, HIGH);
      delayMicroseconds(x);
    }
  }
}

// Play the loser sound/lights
void play_loser(void)
{
  setLEDs(CHOICE_RED | CHOICE_GREEN);
  buzz_sound(255, 1500);

  setLEDs(CHOICE_BLUE | CHOICE_YELLOW);
  buzz_sound(255, 1500);

  setLEDs(CHOICE_RED | CHOICE_GREEN);
  buzz_sound(255, 1500);

  setLEDs(CHOICE_BLUE | CHOICE_YELLOW);
  buzz_sound(255, 1500);
}

// Show an "attract mode" display while waiting for user to press button.
void attractMode(void)
{
  while(1)
  {
    setLEDs(CHOICE_RED);
    delay(100);
    if (checkButton() != CHOICE_NONE) return;

    setLEDs(CHOICE_BLUE);
    delay(100);
    if (checkButton() != CHOICE_NONE) return;

    setLEDs(CHOICE_GREEN);
    delay(100);
    if (checkButton() != CHOICE_NONE) return;

    setLEDs(CHOICE_YELLOW);
    delay(100);
    if (checkButton() != CHOICE_NONE) return;
  }
}

//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// The following functions are related to Beegees Easter Egg only

// Notes in the melody. Each note is about an 1/8th note, "0"s are rests.
int melody[] = {
  NOTE_G4, NOTE_A4, 0, NOTE_C5, 0, 0, NOTE_G4, 0, 0, 0,
  NOTE_E4, 0, NOTE_D4, NOTE_E4, NOTE_G4, 0,
  NOTE_D4, NOTE_E4, 0, NOTE_G4, 0, 0,
  NOTE_D4, 0, NOTE_E4, 0, NOTE_G4, 0, NOTE_A4, 0, NOTE_C5, 0};

int noteDuration = 115; // This essentially sets the tempo, 115 is just about right for a disco groove :)
int LEDnumber = 0; // Keeps track of which LED we are on during the beegees loop

// Do nothing but play bad beegees music
// This function is activated when user holds bottom right button during power up
void play_beegees()
{
  //Turn on the bottom right (yellow) LED
  setLEDs(CHOICE_YELLOW);
  toner(CHOICE_YELLOW, 150);

  setLEDs(CHOICE_RED | CHOICE_GREEN | CHOICE_BLUE); // Turn on the other LEDs until you release button

  while(checkButton() != CHOICE_NONE) ; // Wait for user to stop pressing button

  setLEDs(CHOICE_NONE); // Turn off LEDs

  delay(1000); // Wait a second before playing song

  digitalWrite(BUZZER1, LOW); // setup the "BUZZER1" side of the buzzer to stay low, while we play the tone on the other pin.

  while(checkButton() == CHOICE_NONE) //Play song until you press a button
  {
    // iterate over the notes of the melody:
    for (int thisNote = 0; thisNote < 32; thisNote++) {
      changeLED();
      tone(BUZZER2, melody[thisNote],noteDuration);
      // to distinguish the notes, set a minimum time between them.
      // the note's duration + 30% seems to work well:
      int pauseBetweenNotes = noteDuration * 1.30;
      delay(pauseBetweenNotes);
      // stop the tone playing:
      noTone(BUZZER2);
    }
  }
}

// Each time this function is called the board moves to the next LED
void changeLED(void)
{
  setLEDs(1 << LEDnumber); // Change the LED

  LEDnumber++; // Goto the next LED
  if(LEDnumber > 3) LEDnumber = 0; // Wrap the counter if needed
}

Code To Note

#define

The #define statement is used to create constants in your code. Constants are variables that will likely only have one value during the lifespan of your code. Thus, you can assign constants a value, and then use them throughout your code wherever. Then, if you need to change that value, you can change that one line instead of going through all the code to find every instance of that variable.

byte

Bytes are another variable type. In the world of computing, a byte is a chunk of space that contains 8 bits, and a bit is a single binary value. Binary is another way of counting and uses only 1’s and 0’s. So a byte can hold all 1’s: 11111111, all 0’s: 00000000, or a combination of the two: 10010110.

What You Should See

Once the code is uploaded, the buzzer will beep a few times, and all four LEDs should begin blinking. The game begins once you press any of the four buttons. Once the game has been started, a random LED will blink. Press the button associated with that color LED to replicate the pattern. With a successful guess, the pattern will repeat, this time adding another random LED. The player is to follow the pattern for as long as possible, with each successful guess resulting in an additional layer of complexity added to the original pattern.

Real World Application

Toys and Games, such as the original Simon from Milton Bradley, have relied on electronics to provide fun and entertainment to children across the world.

Troubleshooting

Only Half the Circuit Works

If only half of you circuit is working, make sure you added the additional wire from one ground rail to the other. Remember that breadboards have two power rails on each side and that these can be connected, or bussed, together to provide the power to both sides of the same circuit.

No Sound

Once the piezo buzzer is in the breadboard, it’s hard to see the legs and to which row they are connected. If you aren’t hearing any sound, make sure your wires are on the same row as the piezo buzzer legs.

Game is Not Working

If everything starts up ok, but you’re having trouble when it comes time to play the game, you may have a button or two misplaced. Pay close attention to which pin is connected to each button as it matters which button is pressed when a particular color lights up.

Resources and Going Further

There are tons of sensors and shields you can hookup to an Arduino that will help take your projects to the next level. Here’s some further reading that may help you along in learning more about the world of electronics. For more info on Arduino, check out these tutorials:

For more hardware related tutorials, give these a read:


learn.sparkfun.com |CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado


Humidity-sensing LED Flower

$
0
0

Humidity-sensing LED Flower a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t319

Introduction

This tutorial will show you how to make your own LED flower that senses humidity, just like the one in this week’s episode of ElectriCute! In case you missed it, here’s the video explaining exactly how this circuit works:

This is a pretty versatile project. It lives in my terrarium, and could reasonably go pretty much anywhere, including a garment or accessory. The only reason I didn’t go that route is our location: Colorado is a very boring place to sense humidity!

Humidity-sensing flower in terrarium

Continue reading to learn how to make your own.

Suggested Reading

Before getting started with this tutorial, there are a few concepts with which you should be familiar. Consider reading some of the tutorials below, before continuing on with this one.

Materials

Here’s what you’re going to need for this circuit. The RGB LED flower is exclusive to the 21st Century Fashion Kit, but you can substitute a standard RGB LED if you’d rather!

The Circuit

This circuit design (and the associated code) draws heavily from the Bildr tutorial linked on the SHT15 product page, which I highly recommend looking over! The information there is very helpful!

In particular, the tutorial mentions the need to re-hydrate to polymer in the sensor by placing it in a ziplock bag with (but not touching) a wet towel. This worked perfectly for me.

Here’s your circuit, in all its glory:

circuit diagram

Click image for a closer look.

The Fritzing diagram makes it look nearly impossible to tell the pins of the RGB LED apart, but it really isn’t! The longest leg is ground. The single pin to one side of ground is red, and the other two pins, moving out from ground, are green, then blue.

If you’re using the flower, rather than a standard RGB LED, be very careful if you use heatshrink over the connections – it’s very easy to melt the flower petals with a hot-air gun!

The Code

Not sure how to upload code to your Arduino? No problem! Take a look our tutorial explaining everything in detail. Remember to select the correct board and port for your application.

Copy and paste the code below into the IDE, and click Upload:

language:c
 /*********************************************************
ElectriCute: Humidity Sensing LED Flower
Dia Campbell
SparkFun Electronics
Oct. 29, 2014
Based off of the code found on bildr.org,
http://bildr.org/2012/11/sht15-arduino/
which in turn was based of the wiring code at
http://wiring.org.co/learning/basics/humiditytemperaturesht15.html
With a few additions from Arduino example code
Basically, if this code was a dog, you'd have gotten it from the pound.

Development environment specifics:
Arduino IDE 1.0+
Arduino Pro 5V 16MHz

This code is beerware; if you see us at the local pub,
and you've found our code helpful, please buy us a round!
*********************************************************/


 int SHT_clockPin = 3;  // pin used for clock
 int SHT_dataPin  = 2;  // pin used for data
 int redPin = 4; // Define RGB pins
 int bluePin = 6;
 int greenPin = 5;

void setup(){
  Serial.begin(9600); // open serial at 9600 bps
pinMode(redPin, OUTPUT); //set RGB pins as outputs
pinMode(bluePin, OUTPUT);
pinMode(greenPin, OUTPUT);

 }
 void loop(){
  //these can take a bit to get the values (100ms or so)
  float temperature = getTemperature();
  float humidity = getHumidity();

   Serial.print(temperature);
   Serial.print(" | ");
   Serial.println(humidity);

    if (humidity > 25) {  //humidity threshold; change to suit your purpose
    digitalWrite(bluePin, HIGH);  //When humidity is high enough
   digitalWrite(greenPin, HIGH); //all three pins are high
  digitalWrite(redPin, HIGH);
  }
  else {
    digitalWrite(bluePin, LOW);  //when humidity is too low
    digitalWrite(greenPin, LOW); //turn off green and blue
    digitalWrite(redPin,HIGH);  //turn on red
   delay(1000);               // wait for a second
  digitalWrite(redPin, LOW);    // turn the red LED off
  delay(1000);               // wait for a second
    }
  }


float getTemperature(){
  //Return Temperature in Celsius
  SHT_sendCommand(B00000011, SHT_dataPin, SHT_clockPin);
  SHT_waitForResult(SHT_dataPin);

  int val = SHT_getData(SHT_dataPin, SHT_clockPin);
  SHT_skipCrc(SHT_dataPin, SHT_clockPin);
  return (float)val * 0.01 - 40; //convert to celsius
   }

float getHumidity(){
  //Return  Relative Humidity
  SHT_sendCommand(B00000101, SHT_dataPin, SHT_clockPin);
  SHT_waitForResult(SHT_dataPin);
  int val = SHT_getData(SHT_dataPin, SHT_clockPin);
  SHT_skipCrc(SHT_dataPin, SHT_clockPin);
  return -4.0 + 0.0405 * val + -0.0000028 * val * val;
 }


void SHT_sendCommand(int command, int dataPin, int clockPin){
  // send a command to the SHTx sensor
  // transmission start
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  digitalWrite(dataPin, HIGH);
  digitalWrite(clockPin, HIGH);
  digitalWrite(dataPin, LOW);
  digitalWrite(clockPin, LOW);
  digitalWrite(clockPin, HIGH);
  digitalWrite(dataPin, HIGH);
  digitalWrite(clockPin, LOW);


  // shift out the command (the 3 MSB are address and must be 000, the last 5 bits are the command)
  shiftOut(dataPin, clockPin, MSBFIRST, command);

   // verify we get the right ACK
   digitalWrite(clockPin, HIGH);
   pinMode(dataPin, INPUT);

  if (digitalRead(dataPin)) Serial.println("ACK error 0");
  digitalWrite(clockPin, LOW);
  if (!digitalRead(dataPin)) Serial.println("ACK error 1");
 }


void SHT_waitForResult(int dataPin){
  // wait for the SHTx answer
  pinMode(dataPin, INPUT);

  int ack; //acknowledgement

  //need to wait up to 2 seconds for the value
  for (int i = 0; i < 1000; ++i){
    delay(2);
   ack = digitalRead(dataPin);
   if (ack == LOW) break;
 }

  if (ack == HIGH) Serial.println("ACK error 2");
   }

 int SHT_getData(int dataPin, int clockPin){
  // get data from the SHTx sensor

  // get the MSB (most significant bits)
  pinMode(dataPin, INPUT);
  pinMode(clockPin, OUTPUT);
  byte MSB = shiftIn(dataPin, clockPin, MSBFIRST);

  // send the required ACK
  pinMode(dataPin, OUTPUT);
  digitalWrite(dataPin, HIGH);
  digitalWrite(dataPin, LOW);
  digitalWrite(clockPin, HIGH);
  digitalWrite(clockPin, LOW);

  // get the LSB (less significant bits)
  pinMode(dataPin, INPUT);
  byte LSB = shiftIn(dataPin, clockPin, MSBFIRST);
  return ((MSB << 8) | LSB); //combine bits
    }

void SHT_skipCrc(int dataPin, int clockPin){
  // skip CRC data from the SHTx sensor
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  digitalWrite(dataPin, HIGH);
 digitalWrite(clockPin, HIGH);
 digitalWrite(clockPin, LOW);
}

Once the code is uploaded, open the Serial Monitor. This should open a window which is scrolling numbers. The right column is temperature, the left column is humidity. Take a look at the number your humidity is hovering around, and use that to determine what you’d like your ideal humidity to be.

The line addressing humidity threshold is commented, and pretty close to the top, so look for that and make adjustments as needed. I set mine to just a hair above ambient humidity, because I wanted it to be easy to demo. You may want yours to be a bit less sensitive. In that same section, you can make changes to the way the lights react to those changes!

When the sensor is reading below that threshold, the LED blinks red, like so:

alt text

And, when it’s above the threshold, a nice, white glow is emitted:

alt text

Once you’ve got your reactivity and behavior where you’d like them, you’re all set! Unhook the board from the computer, plug the battery into the Arduino, and put your new humidity sensing device in your favorite terrarium, buttonhole, fascinator, or whatever you choose!

Resources and Going Further

Thanks for reading this project tutorial. Check out these other great ElectriCute videos for more project inspiration:




learn.sparkfun.com |CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

Micro OLED Breakout Hookup Guide

$
0
0

Micro OLED Breakout Hookup Guide a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t308

Introduction

Want to add a little graphic pizzazz to your Arduino project? Do you need to display diagnostic information without resorting to serial output? Or maybe you want to learn a little game theory while creating a fun, Arduino-based video game. These are just a handful of example applications for the Micro OLED Breakout.

Micro OLED Action Shot

The Micro OLED Breakout Board breaks out a small monochrome, blue-on-black OLED. It’s 64 pixels wide and 48 pixels tall, measuring 0.66" across. It’s micro, but it still packs a punch – the OLED display is crisp, and you can fit a deceivingly large amount of graphics on there. Most important of all, though, is the Micro OLED is easy to control over either an SPI or I2C interface.

Covered In This Tutorial

In this tutorial we’ll give you a brief introduction to the OLED and the breakout, then we’ll jump into example hardware hookups and code. The tutorial is split into the following sections:

  • Breakout Board Overview– To begin, we’ll go over each of the pins on the breakout board and their function. This section also overviews the jumpers on the backside of the Breakout.
  • Hardware Assembly– Soldering tips and other Micro OLED Breakout assembly tricks.
  • Hardware Hookup– In this section we’ll show you how to hook an Arduino up to the display via either SPI or I2C.
  • Arduino Library Download, Install, and Test– Download and install the Arduino library, then upload an example to test everything out.
  • Using the Arduino Library– A quick examination of the Micro OLED Arduino library’s family of function calls.

Materials Used

In addition to the display, you’ll also need a few components and tools to follow along with this tutorial. Here is what we used to get the display up-and-running:

Break Away Headers - Straight

Break Away Headers - Straight

In stock PRT-00116

A row of headers - break to fit. 40 pins that can be cut to any size. Used with custom PCBs or general custom headers. **Fea…

1.5
Jumper Wires Standard 7" M/M Pack of 30

Jumper Wires Standard 7" M/M Pack of 30

In stock PRT-11026

If you need to knock up a quick prototype there's nothing like having a pile of jumper wires to speed things up, and let's fa…

4.95
Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

In stock PRT-12002

**Description**: This is your tried and true white solderless breadboard. It has 2 power buses, 10 columns, and 30 rows - a t…

4.95
Arduino Pro 328 - 3.3V/8MHz

Arduino Pro 328 - 3.3V/8MHz

In stock DEV-10914

It's blue! It's skinny! It's the Arduino Pro! SparkFun's minimal design approach to Arduino. This is a 3.3V Arduino running t…

14.95

There are many ways to complete the hookup, though. In general, you’ll need:

  • Arduino or other microcontroller– You’ll need something to control the display. Optimally you’ll want something that has a 3.3V operating voltage. We’ll be using a 3.3V Arduino Pro, the 3.3V Arduino Pro Mini would be another good option.
  • Level shifting– If you’re using a 5V Arduino, like the Uno or RedBoard, you’ll need to add some level shifting. Something like the bi-directional logic level converter should do the trick.
  • Connectors– Some means for interfacing the breakout with your microcontroller. Male headers are perfect if you’re using a breadboard. Or maybe all you need is some wire.
  • Soldering tools– After you’ve picked a connector, you’ll need to solder it to the breakout board. A simple iron and some solder should be all you need.

Recommended Reading

Before getting started with the Micro OLED Breakout, there are a few concepts you should be familiar with. Consider reading some of the tutorials below, before continuing on with this one.

Breakout Board Overview

Pin Descriptions

In total, the Micro OLED Breakout provides access to 16 of the OLED’s pins. Fortunately, though, you’ll only need about half of them to make the display work.

OLED pin overview

The top row of pins (in the image above) breaks out everything you’d need to interface with the OLED over an SPI or I2C interface. Those pins are:

Pin LabelSPI FunctionI2C FunctionNotes
GNDGroundGround0V
3V3 (VDD)PowerPowerShould be a regulated 3.3V supply.
D1 (SDI)MOSISDASerial data in
D0 (SCK)SCKSCLSPI and I2C clock
D2 (SDO)MISOCan be unused in SPI mode. No function for I2C.
D/CData/CommandI2C address selectionDigital pin to signal if incoming byte is a command or screen data.
RSTResetResetActive-low screen reset.
CSCSSPI chip select (active-low)

The pins on the bottom are mostly only used if you need to control the display over a parallel interface. D3-D7 are the last 5 bits of the parallel data bus. E/RD acts as either an enable/disable pin, or a read/write control, depending on the parallel bus configuration. The RW/WR pin is either used as a read/write control or a write latch.

The VB pin allows you to individually power the VBAT line of the display. The supply for VBAT should be between 3.3V and 4.2V (LiPo battery-ish supply). If you’d like power this line individually, pay extra-special attention to the VD/VB jumper section below.

Those bottom eight pins were simply broken out for complete-ness. If you’re controlling the display via either SPI or I2C, you can safely ignore them.

Setting the Jumpers

With the board flipped over, you’ll notice there are five jumpers. The majority of these jumpers are used to switch between SPI and I2C mode. As the board ships, these jumpers are set to configure the display in SPI mode.

Here’s an overview of each jumper, moving from left-to-right, top-to-bottom in the picture above:

  • D1/D2 -- This jumper can be used to short D1 to D2. If you want to use SPI, leave this jumper open. If you're using I2C, short the jumper. By default this jumper is open.
  • D/C -- This jumper can be used to short D/C to either 3.3V (1) or 0V (0). In I2C mode, the D/C pin sets the 7-bit address of the display. In SPI mode this jumper should be left open, as the D/C pin needs to be toggled to determine if an incoming byte is data or command.
  • BS2 and BS1 -- These pins on the OLED determine which interface you're using to control the OLED. With the two signals, there are four possible combinations:
    BS2BS1Interface
    00SPI
    01I2C
    108-bit Parallel (6800)
    118-bit Parallel (8080)
    By default, both of these jumpers are set to 0, which puts the display in SPI mode. If you want to change it to I2C mode, clear the BS1 jumper and set it to 1.
  • VD/VB -- This jumper shorts the digital power supply (VDD) to the battery power supply (VBAT). Because both of these supplies can be powered at 3.3V, an easy one-supply solution is to short them together and provide them a single supply. If you need to power the digital supply at something lower, like 1.8V, you may need to cut this jumper and provide two supplies.

That brief overview should cover the 99% use case. Consult the schematic and the notes therein if you have any questions about jumpers or pins.

Hardware Assembly

Before you solder anything to the Micro OLED Breakout, take some time to think about how you’re going to use it. Are you just prototyping with it? Sticking it on a breadboard? Maybe all you need to do is solder some headers on there. Are you enclosing it? Embedding it into a project? In that case, maybe you’ll want to solder wires to the pins instead.

Also think about how you want the screen to be visible. The board is designed so you can either fold the display over, or have it flop off the edge of the board. The screen’s orientation will determine which side of the board you’ll need to solder to.

Solder on either side of the PCB

Solder on either side of the PCB. If you’re using wire (left) either configuration will do. If you’re using headers, we recommend soldering as shown above to the right.

Even if you’re not going to use the extra eight pins, try to solder headers to them if you can. This will help balance the display if you’re plugging it into a breadboard. Just take care not to burn the screen’s connector as you solder these pins – you can gently pull it back while applying the solder.

Soldering the pins under the connector

Carefully solder the pins under the connector, which will help stabilize the display in your breadboard.

After soldering, you may want to secure the display with some tape – especially if you’re going with the “fold-over” method. Double-sided foam tape is perfect for this application.

Foam tape!

Fold the display over and it should fit perfectly within the PCB’s outline.

Display folded over on top of PCB

Setting Jumpers for I2C Mode

If you’re controlling the display over I2C, you’ll need to make a few modifications to the jumpers:

  1. Short D1/D2– This will combine the data output line and data input line into one.
  2. Set BS1 to 1– The BS1 jumpers comes defaulted to 0, which does half the job of setting it to SPI. To set the display to I2C, you’ll need to flip that jumper to 1. Also make sure the BS2 jumper remains set to 0.
  3. Set D/C– In I2C mode, the D/C pin configures the display’s 7-bit address. You can set it to either 0 or 1, just keep that value in mind when you get to the code part of this tutorial.

Once you’re done setting jumpers, the back of the board should look a little something like this:

alt text

Breakout jumpers set for I2C mode.

Hardware Hookup

Now that your breakout is all soldered-to and assembled, it’s time to wire it up. In this section we’ll go over to example hookups, depending on whether you’d like to use SPI or I2C to control the display.

If you’re not sure which interface to use, we recommend going with SPI, which will give you the fastest transfer rate and screen refresh speed.

Arduino Pro 3.3V via SPI

We’ll be using the Arduino’s hardware SPI pins in order to achieve the fastest data transfer speed. That means we’ll need to use pins 13, 11, and 10 as the SCLK, MOSI, and CS pins. The other pins – RST and D/C – can be connected to any available digital pin on the Arduino.

Here’s the example hookup:

SPI hookup

Make sure your display is powered at 3.3V and not 5V!

Arduino Pro 3.3V via Using I2C

The benefit of I2C is the lower pin count – this hookup only requires three wires, besides power and ground – but you do sacrifice some speed for fewer wires.

In this case, SDA and SCL must be tied to the Arduino Pro’s pins A4 and A5 respectively. RST can be tied to any other digital pin, we’re using 9.

I2C hookup

While I2C affords you a few extra available pins, it is quite a bit slower than SPI. If you don’t need a fast framerate, though, I2C is a great option.

Arduino Library Download, Install, and Test

Soldering? Check. Wiring? Check. On to the firmware. Let’s make the display blink!

Download, Install the Arduino Library

To make controlling the OLED as easy as possible, we’ve adapted an Arduino library for it. Using the library, you can draw anything from pixels to shapes and even text. To download the library, click the button below, or grab the latest version from our GitHub repository.

Download the Arduino Library!

Then install the library in your Arduino sketchbook. If you need any guidance installing the library, check out our Installing an Arduino Library tutorial.

Load the Demo Example

Next, load up the demo example that’s included with the library. After installing the library, open Arduino. Then navigate to File>Examples>SFE_MicroOLED>MicroOLED_Demo.

Opening the example

Make sure your Board and Serial Port are set correctly and upload!

alt text

The demo example will show off a lot of what the OLED can do. For more fun, check out the other examples included with the library.

Using the Arduino Library

Now that you’ve loaded up the example, and proven out your display and hookup, it’s time to get started writing your own application! Before you get started, here’s a quick rundown of the SFE_MicroOLED library.

Including, Initializing, and Beginning

At the top of your code, of course, you’ll need to include the SFE_MicroOLED library. On top of that, you’ll also need to include the SPI and Wire libraries so the SFE_MicroOLED library has access to those interfaces.

language:c
#include <SPI.h>
#include <Wire.h>
#include <SFE_MicroOLED.h>

After you’ve included the library, you can create a MicroOLED object in the global variable area of your code. This is where you’ll tell the library whether you’re using SPI or I2C, and which pins are driving the display.

language:c
#define PIN_RESET 9  // Connect RST to pin 9 (req. for SPI and I2C)
#define PIN_DC    8  // Connect DC to pin 8 (required for SPI)
#define PIN_CS    10 // Connect CS to pin 10 (required for SPI)
//#define DC_JUMPER 0 // (I2C only) Set to either 0 or 1, matching the value of the DC Jumper

// Declare a MicroOLED object. The parameters include:
// 1 - Reset pin: Any digital pin
// 2 - D/C pin: Any digital pin (SPI mode only)
// 3 - CS pin: Any digital pin (SPI mode only, 10 recommended)
MicroOLED oled(PIN_RESET, PIN_DC, PIN_CS); // Example SPI Declaration
//MicroOLED oled(PIN_RESET, DC_JUMPER); // Example I2C Declaration

If you’re using SPI to talk to the display, define three parameters to tell the library which pins you have RST, D/C and CS connected to, respectively. If you’re using I2C, you’ll need two parameters: the reset pin and the value of the D/C jumper (0 or 1).

In the example above we’ve called our MicroOLED object oled, but you can call it anything you’d like. You can even create more than one, if you have more displays connected to your Arduino.

The last step to the OLED setup should occur in the setup() function. Stick a oled.begin() function in there, which will initialize the display and update all sorts of behind-the-scenes settings for you.

language:c
setup()
{
    // Before you can start using the OLED, call begin() to init
    // all of the pins and configure the OLED.
    oled.begin();
}

Drawing Pixels and Displaying

Let’s begin by drawing the simplest shape out there – a pixel. Drawing anything requires at least two steps. First you have to tell the screen what you want to draw, then you have to tell it to draw it.

To draw a pixel, start by calling the pixel(int x, int y) function.

language:c
// Draw a pixel in the middle of the screen
oled.pixel(LCDWIDTH/2, LCDHEIGHT/2); // Add a pixel to the display buffer.

Then, after you’ve told the screen what to draw, use the display() function to execute.

language:c
oled.display(); // Draw whatever is in the display buffer.

The display() function re-draws the entire screen – all 3072 pixels. It takes a relatively long time to execute the command, so try not to do it too much.

Lines, Rectangles, Circles, Oh My!

Now that we know how to draw pixels, it’ll be easy to draw all sorts of shapes.

To draw a line, you need two sets of x/y coordinates, the line will be drawn between them. Here’s an example:

language:c
int x0 = 7; int y0 = 7;   // (x0,y0) = (7, 7)
int x1 = 42; int y1 = 24; // (x1,y1) = (42, 24)
oled.line(x0, y0, x1, y1);  // Draw a line from (x0,y0) to (x1,y1);
oled.display(); // Draw to the screen

Things are a little different if you want to draw a rectangle. In this case, you give it a x/y coordinate to start at, then a width and a height.

language:c
int x0 = 7; int y0 = 5;
int width = 24;
int height = 13;
oled.rect(x0, y0, width, height);  // Draw a rectange from (7,5) to (31,18)
oled.display(); // Draw to the screen

The rectangle will be drawn from (x0, y0) to (x0+width, y0+height).

Want to fill that rectangle? Use the rectFill function instead!

language:c
oled.rectFill(7, 5, 35, 5); // Fill a rectangle from (7, 5) to (42, 10)
oled.display(); // Draw to the screen

Circles require a set of coordinates for the middle, and then a radius.

language:c
int radius = 13;
// Draw a 13-pixel radius (26-pixel diameter)
// circle centered in the middle of the display:
oled.circle(LCDWIDTH/2, LCDHEIGHT/2, radius);

As with the rectangle function, you can also fill the circle with circleFill:

language:c
oled.circleFill(42, 20, 7); // Fill a circle, 7 radius, centered at (42, 20)
oled.display(); // Draw to the screen

Drawing Text

In addition to basic shapes, you can also draw text with the SFE_MicroOLED library. There are a few settings to adjust before you get to texting, though. First, set the font type with setFontType(type). The parameter in this function can be either 0, 1, 2, or 3, each size gets progressively larger.

language:c
oled.setFontType(0);  // Set the text to small (10 columns, 6 rows worth of characters).
oled.setFontType(1);  // Set the text to medium (6 columns, 3 rows worth of characters).
oled.setFontType(2);  // Set the text to medium/7-segment (5 columns, 3 rows worth of characters).
oled.setFontType(3);  // Set the text to large (5 columns, 1 row worth of characters).

Here’s a quick overview of each of the four font types:

Font TypeMaximum ColumnsMaximum RowsDescription
0106Smallest, 5x7-pixel characters.
163Medium, 8x16-pixel characters.
2537-segment display style characters, 10x16-pixels each.
351Large, 12x48 (the entire screen height) characters.

Next, after setting the font type, define your text cursor with setCursor(x, y). This will define the top-left corner of the first character you print.

language:c
oled.setCursor(0, 0);  // Set the text cursor to the upper-left of the screen.

Finally, you can use the print(String/int/float) command to print whatever you want.

language:c
oled.print("Hello, world"); // Print a const string
oled.print(analogRead(0));  // Print an integer
oled.print(42.07);  // Print a float
oled.display(); // Draw to the screen

That covers the basics of the library, but it can do more. Check out the library’s readme for a complete overview of the MicroOLED class. There you’ll find more functions, like invert(boolean)flipVertical(boolean), flipHorizontal(boolean), and scrollRight(start, stop).

Resources & Going Further

Here are a few helpful links that might help to answer any questions you may still have regarding the Micro OLED Breakout:

Going Further

Now that you’re well-versed in all things Micro OLED Breakout and its Arduino library, what are you going to make with it? Need some inspiration, check out these related tutorials:

OLED Display Hookup Guide

October 22, 2013

A simple hookup guide to get you started with the OLED LCD.

Serial Graphic LCD Hookup

December 3, 2013

Learn how to use the Serial Graphic LCD.

RGB Panel Hookup Guide

December 12, 2013

Make bright, colorful displays using the 32x32 and 32x16 RGB LED panels. This hookup guide shows how to hook up these panels and control them with an Arduino.

Reaction Timer

January 16, 2014

Demonstrate mental chronometry with this simple reaction timer!

learn.sparkfun.com |CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

Cackling Apple Head Witch

$
0
0

Cackling Apple Head Witch a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t315

Introduction

In this tutorial, we’ll show you how to create a fun, easy Halloween prop out of an apple and a few SparkFun parts. You’ll sew a LilyPad Light Sensor and LilyPad MP3 Trigger onto a witch’s dress and be able to customize your own sounds for the witch to make. By the end of the project you’ll have a completed witch doll that will cackle as soon as the lights go down!

Apple Head Witch

Suggested Reading

If you’ve never worked with e-textiles before, you may want to have a look at these other tutorials.

Materials and Tools

Let’s go over all of the things you’ll need to put your project together:

You will also need:

  • Stiff interfacing (18 inch circle cut in half)
  • Fabric for your witch dress (19 inch circle cut in half)
  • Felt for the speaker pocket (8x12 sheet will be plenty)
  • Sharpened full length pencil
  • Black pipe cleaner
  • Black cardstock for your witch hat (one 8.5x11 sheet will do)
  • Gray or black yarn for your witch hair (4 feet or so)
  • White, black & red sewing pins (about 4-5)
  • Small apple
  • Hot glue gun
  • Scissors

Here are some extra materials you might need in case you do not have these things at home.

Step 1: Shrinking the Apple Head

Apple

Peel a small apple, and leave it to dry out near a sunny window for about a week.

Peeling Apple

Fully Peeled Apple

You want the apple to become dried out for the witch face. It will naturally shrink in size.

Once the apple has been dried out and to the desired facial texture, cut off the top portion of the apple where the stem is (about a ¼ inch) to create a flat surface.

Cut Off Apple Head

Step 2: Programming the MP3 Trigger

While you’re waiting for your apple head to shrink, let’s get all the electronic bits together, and program the LilyPad MP3 Player with the sketch that will monitor the light sensor and play the scary sound when a shadow falls across it.

Testing the circuit

To make sure everything works before you start sewing it into your project, we recommend using alligator clips to temporarily make all the electrical connections. You can easily attach alligator clips to the bare metal around the holes on the LilyPad boards.

alt text

Follow the above diagram to make the following connections:

fromto
LilyPad MP3 Player "3.3V"LilyPad Light Sensor "+"
LilyPad MP3 Player "GND"LilyPad Light Sensor "-"
LilyPad MP3 Player "T1"LilyPad Light Sensor "S"
LilyPad MP3 Player "RIGHT SPEAKER +"Speaker + *
LilyPad MP3 Player "RIGHT SPEAKER -"Speaker - *
Lipo BatteryLilyPad MP3 Player battery connector
5V FTDI boardLilyPad MP3 Player FTDI connector

* It doesn’t matter which side of the speaker you connect to “+” and “-”. However, if you use two speakers, make sure they’re both connected the same way.

OPTIONAL: You can use one or two speakers. If you want to use two speakers, connect one speaker to the right speaker connections (+ and -), and the second speaker to the left speaker connections (+ and -).

OPTIONAL: If you want to connect LEDs that light up while audio is playing, you can connect them between the LilyPad MP3 Player’s T2 terminal and GND.

The 5V FTDI board is used to program the LilyPad MP3 Player and recharge the battery. Plug the FTDI board’s socket into the 6-pin connector on the LilyPad MP3 Player, and plug the other end of the USB cable into your computer. (It’s normal for the yellow “charge” LED to come on when you do this, it will go out when the battery is fully charged.)

TIP: If you look closely at the FTDI board, you’ll see labels that say “GRN” (green) and “BLK” (black). Match these up with the labels on the LilyPad MP3 Player when you’re plugging them together. (These “colors” match the wires on a different FTDI cable.)

Copy your sound file to the SD card

You can use almost any sound file you wish. Here’s the one we’re using for this project:

cackle.mp3

Right-click the above link, choose “Save link” to download the file to your computer, and copy it to your SD card. Insert the SD card into the socket on the LilyPad MP3 Player.

NOTE: The Arduino sketch (below) looks for a file called “cackle.mp3”. If you use a different file, either rename it to “cackle.mp3”, or change the filename at the top of the Arduino sketch.

Now, let’s program the LilyPad MP3 Player!

Install the Arduino software

If you have never used the Arduino software before, go through our getting started tutorial first. This will walk you through installing the Arduino software on your computer.

Install the extra libraries

You’ll now need to add the extra libraries needed to program the LilyPad MP3 Player. The easiest way to do this is:

  1. Go to the LilyPad MP3 Player Github page
  2. Click the “Download Zip” button on the right-hand side to download an archive of the files you need. Save it on your computer.
  3. Locate your personal Arduino folder. This should be in your documents folder.
  4. Open the archive you downloaded, open the “Arduino” folder inside it, and drag the contents of that folder into your personal Arduino folder.

If any of this is confusing, check out our Arduino library tutorial.

Load the sketch into the editor

Once you’ve done that, start the Arduino IDE, and copy and paste the following sketch into the editing window:

language:c
// Applehead_witch
// Demo program for Sparkfun's LilyPad MP3 Player
// Mike Grusin, SparkFun Electronics

// This sketch works with Amanda Clark's Apple Head Witch tutorial.
// If your shadow passes over an innocent-looking apple-head doll,
// the LilyPad MP3 Player will play a scary sound!

// HOW IT WORKS:

// The sketch monitors a light sensor connected to TRIG1.
// When the sketch first runs, it will sample a baseline light level
// and compute a threshold value (baseline * 0.9). After that, if the
// light level falls below this threshold, a sound file will play.
// Also, TRIG2 will be set to HIGH while the file is playing, and
// LOW otherwise (for optional scary LED eyes or other features).

// SOFTWARE INSTALLATION:

// If you haven't yet, you should install the LilyPad MP3 Player
// libraries available here: https://github.com/sparkfun/LilyPad_MP3_Player

// HARDWARE CONNECTIONS:

// Connect the "S" pin of the LilyPad Light Sensor to TRIG1.
// Also connect 3.3V to the Light Sensor's "+" pin, and
// GND to the Light Sensor's "-" pin.
// (Optional) Connect TRIG2 to LEDs through a resistor for 3.3V supply.
// (330 Ohms is a common value).
// Connect one or two speakers to the left and/or right speaker terminals.
// Put a sound file on a microSD card and place it in the player.
// Change the below filename to match the one you put on the SD card:

char filename[] = "cackle.mp3";

// Connect a 3.7V Lipo battery to the battery connector.
// Connect a 5V FTDI Basic Breakout.
// Remember to turn on the player before programming it!

// RUNNING THE SKETCH

// When you first run the sketch, the light sensor will be sampled for
// the baseline light level. So have the project in it's installed position,
// and avoid casting shadows on it, before turning it on.

// Once it is on, when you cast a shadow over the project, it should play
// the audio file through the speaker.

// If it doesn't activate properly (too often or not often enough),
// you can adjust the sensitivity value below.
// The sensitivity can be from 0.0 to 1.0. The closer it is to 1.0, the more
// sensitive the sketch will be. If you make it 1.0, it will probably activate
// continuously.
// If your project it too sensitive, make the sensitivity smaller.
// If your project is not sensitive enough, make the sensitivity larger.

const float sensitivity = 0.9;

// If the sketch does not work properly, connect your 5V FTDI and open a
// Serial Monitor at 9600 baud to receive debugging information.

// HAVE FUN!
// Your friends at SparkFun


// We'll need a few libraries to access all this hardware!

#include <SPI.h>            // To talk to the SD card and MP3 chip
#include <SdFat.h>          // SD card file system
#include <SFEMP3Shield.h>   // MP3 decoder chip

// Constants for the trigger pins:

const int TRIG1 = A0;
const int TRIG2 = A4;

// Save the light sensor baseline reading:

int threshold;

// And a few output pins we'll be using:

const int ROT_LEDR = 10; // Red LED in rotary encoder (optional)
const int EN_GPIO1 = A2; // Amp enable + MIDI/MP3 mode select
const int SD_CS = 9;     // Chip Select for SD card

// Create library objects:

SFEMP3Shield MP3player;
SdFat sd;

// Set debugging = true to send status messages to the serial port:

boolean debugging = true;


void setup()
{
  byte result;

  // Use TRIG1 as an anlog input for our light sensor:

  pinMode(TRIG1,INPUT);

  // Use TRIG2 as a digital output that will be HIGH
  // while we're playing an audio file and LOW otherwise:

  pinMode(TRIG2,OUTPUT);
  digitalWrite(TRIG2,LOW);

  // If serial port debugging is inconvenient, you can connect
  // a LED to the red channel of the rotary encoder to blink
  // startup error codes:

  pinMode(ROT_LEDR,OUTPUT);
  digitalWrite(ROT_LEDR,HIGH);  // HIGH = off

  // The board uses a single I/O pin to select the
  // mode the MP3 chip will start up in (MP3 or MIDI),
  // and to enable/disable the amplifier chip:

  pinMode(EN_GPIO1,OUTPUT);
  digitalWrite(EN_GPIO1,LOW);  // MP3 mode / amp off

  // If debugging is true, initialize the serial port:
  // (The 'F' stores constant strings in flash memory to save RAM)

  if (debugging)
  {
    Serial.begin(9600);
    Serial.println(F("Lilypad MP3 Player trigger sketch"));
  }

  // Initialize the SD card; SS = pin 9, half speed at first

  if (debugging) Serial.print(F("initialize SD card... "));

  result = sd.begin(SD_CS, SPI_HALF_SPEED); // 1 for success

  if (result != 1) // Problem initializing the SD card
  {
    if (debugging) Serial.print(F("error, halting"));
    errorBlink(1); // Halt forever, blink LED if present.
  }
  else
    if (debugging) Serial.println(F("success!"));

  // Start up the MP3 library

  if (debugging) Serial.print(F("initialize MP3 chip... "));

  result = MP3player.begin(); // 0 or 6 for success

  // Check the result, see the MP3 library readme for error codes.

  if ((result != 0) && (result != 6)) // Problem starting up
  {
    if (debugging)
    {
      Serial.print(F("error code "));
      Serial.print(result);
      Serial.print(F(", halting."));
    }
    errorBlink(result); // Halt forever, blink red LED if present.
  }
  else
    if (debugging) Serial.println(F("success!"));

  // Set the VS1053 volume. 0 is loudest, 255 is lowest (off):

  MP3player.setVolume(10,10);

  // Get baseline readings from the light sensor:

  threshold = (analogRead(TRIG1));
  if (debugging)
  {
    Serial.print(F("measured threshold value: "));
    Serial.println(threshold);
  }

  threshold = threshold * sensitivity;
  if (debugging)
  {
    Serial.print(F("modified threshold value: "));
    Serial.println(threshold);
  }

  // Turn on the amplifier chip:

  digitalWrite(EN_GPIO1,HIGH);
  delay(2);
}


void loop()
{
  byte result;
  byte sensorvalue;

  // Get the current light level (sensorvalue):

  sensorvalue = analogRead(TRIG1);

  if (debugging)
  {
    Serial.print(F("sensor value: "));
    Serial.print(sensorvalue);
    Serial.print(F("  threshold: "));
    Serial.println(threshold);
  }

  // Check to see whether we're below the threshold

  if (sensorvalue < threshold)
  {
    if(debugging)
    {
      Serial.println(F("got a trigger!"));
    }

    // If we're currently playing a file, let it finish (don't start over)

    if (MP3player.isPlaying())
    {
      if(debugging)
      {
        Serial.println(F("...but we're already playing"));
      }
    }
    else
    {
      // Play the file!

      result = MP3player.playMP3(filename);

      // Print out error information for debugging

      if(debugging)
      {
        if(result != 0)
        {
          Serial.print(F("error "));
          Serial.print(result);
          Serial.print(F(" when trying to play track "));
        }
        else
        {
          Serial.print(F("playing "));
        }
        Serial.println(filename);
      }
    }
  }

  // For fun, we'll set TRIG2 HIGH while we're playing a file,
  // and LOW when the player is silent.

  if (MP3player.isPlaying())
    digitalWrite(TRIG2,HIGH);
  else
    digitalWrite(TRIG2,LOW);
}


void errorBlink(int blinks)
{
  // The following function will blink the red LED in the rotary
  // encoder (optional) a given number of times and repeat forever.
  // This is so you can see any startup error codes without having
  // to use the serial monitor window.

  int x;

  while(true) // Loop forever
  {
    for (x=0; x < blinks; x++) // Blink the given number of times
    {
      digitalWrite(ROT_LEDR,LOW); // Turn LED ON
      delay(250);
      digitalWrite(ROT_LEDR,HIGH); // Turn LED OFF
      delay(250);
    }
    delay(1500); // Longer pause between blink-groups
  }
}

Upload the sketch to the LilyPad MP3 Player

Turn the power switch on the LilyPad MP3 Player to ON. The red LED should light up.

In the Arduino IDE, go to the “tools/board” menu. Select Arduino Pro or Pro Mini (3.3V, 8MHz) w/ ATmega328.

Now go to the “tools/serial port” menu. Select the serial port that your FTDI is using. If you just installed it, this will be the highest number.

Now click the right-arrow button above the editing window. This will compile the sketch and upload it through the FTDI board to the LilyPad MP3 Player.

Hopefully you’ll see some blinking on the FTDI, followed by an “upload successful” message. If there are errors, see the troubleshooting tips below.

Try it out!

Once you’ve uploaded the sketch, it will automatically start running. The first thing the sketch does is take a baseline reading from the light sensor. It will then keep monitoring the sensor, and if the sensor dips below that level (such as when a shadow passes across it), it will play the scary sound. For best results, whenever you turn your project on, try not to be casting a shadow over it.

Try passing your hand over the light sensor, and see if it plays the scary sound.

If it works, congratulations! If not, don’t worry, see the troubleshooting tips below.

Once you know everything works, you’re ready to build the rest of your project. Note that you won’t have to reprogram the LilyPad MP3 Player again (unless you want to), it will remember the last sketch you uploaded to it!

Troubleshooting

Syntax errors are almost always caused by not restarting the Arduino IDE after installing the libraries, or not installing the libraries correctly. Check your above steps to make sure you placed the new libraries into a “libraries” directory within your personal Arduino sketch folder.

Uploading errors may be caused by the LilyPad MP3 Player being switched off (it must be on to upload code), The FTDI drivers not being installed correctly, or selecting the wrong port in the “tools/serial port” menu.

No sound? If the code uploaded without errors but the sound still doesn’t play, try looking at the debugging information. In the Arduino IDE, click on the magnifying glass button at the upper right. This will open a serial monitor window. Set the baud rate (bottom of window) to 9600 baud.

The LilyPad MP3 Player should now fill the window with text showing what it’s doing and if there are any problems such as not being able to find the SD card or the proper filename on it.

Still stumped? If after all this you still can’t get it working, don’t panic! You can always contact our Tech Support Department. They’ll be happy to help you get up and running.

Step 3: Soldering the Speaker to the LilyPad MP3

Next, you’re going to be doing some minimal soldering. Make sure to wear your safety glasses! Take your thin speaker and solder the positive wire into the positive left speaker pin on the MP3 trigger. Using flux on the pin will help the solder flow nicely onto it. Take the negative wire and solder it into the negative left speaker pin. (You may need to strip back some wire for more exposed wire to solder to the pin. Using wire strippers will help.)

Soldering the Speaker

Speaker Attached to LilyPad MP3

Step 4: Sewing in Your Components

Now, you’ll take your interfacing and cut out an 18 inch diameter circle. After the circle is cut you’ll want to cut the circle in half.

Interfacing Half Circle

Grab your dress fabric and cut out a 19 inch diameter circle. You’ll want this circle to be just a tad bit bigger than the interfacing circle so that it covers up the interfacing and you’ll only see the dress fabric. After the circle is cut you’ll want to cut the circle in half.

Interfacing & Velvet Half Circles

Hot glue (or an adhesive that bonds well with fabric) the dress fabric onto the interfacing making sure that you don’t see any of interfacing behind it. Make sure the two pieces are lined up well and that the bond is clean and tight with no wrinkles. This is one of the main focal points of the witch, so you want it to look good!

Next, take your LilyPad MP3 with the soldered speaker and position it inside of the dress with the speaker facing outward towards the front. By doing this you’ll be able to hear the cackle more clearly when it is turned on. The MP3 Trigger may be hot glued to the inside of the dress. When hot gluing the MP3 board to the dress, make sure to avoid gluing any areas with exposed pins that are on the board. Make sure the side with the components on the MP3 board is facing out so you can easily access the pins.

Take your LilyPad light sensor, and figure out where you want it to be sewn into the dress. I find that the best place is the front of the dress for the best light exposure.

You’re going to carefully sew traces to each of the following through the dress:

fromto
S pin on the LilyPad light sensorT1 pin on the MP3 Trigger
negative pin (-) on the LilyPad light sensorGND (ground) pin on the MP3 Trigger
positive pin (+) on the LilyPad light sensor3.3v pin on the MP3 Trigger

Next, cut out two 3 inch squares of a sturdy fabric (felt will do). These are going to be your pockets for your speaker and battery to sit in inside of the dress .

Position the pockets so that they sit close to the front of the dress. Hot glue the sides and bottom of the squares and position them within the dress on the interfacing. Test to make sure your speaker and battery will sit nicely inside the pockets.

Sewing Diagram

Light Sensor Diagram

Step 5: Getting Crafty with the Witch

Take your half circle of interface and fabric that are glued together with all of the components, and wrap it into a cone shape. Glue it together with your hot glue gun or some sort of strong, fabric adhesive. Make sure to leave enough space for your pencil body to go through at the top of the cone. (about ¼ inch diameter)

Cone Dress

Make sure your pencil is sharpened. Use the leaded side of your pencil and stick it about halfway through the dried out apple. This will be your witch body. You may need to reinforce it by adding some hot glue so it stays in place.

Pencil Stab Apple

Take your apple head on the pencil, and slide it through the top of the cone dress until the head is about ¼ inch away from where it’ll meet the dress. Glue the cone dress to the pencil with your hot glue gun. Make sure the bond is secure.

Apple Head & Dress

Take one black pipe cleaner, and wrap it around the area of the pencil that is exposed (in between the apple head and the dress). You are making the witch arms, so be sure they are even on both sides.

Twisting Arms

Completed Arms

Grab your bundle of yarn, and cut a piece about 5 inches long and leave it to the side. Take more of the yarn from the bundle and wrap it loosely around your four fingers about 40 times or so.

Yarn Bundle & Single Piece

Cut the bottom of the loop of yarn. This will be the hair for your witch.

Cutting Yarn Bundle

Yarn Cut in Half

Grab the cut yarn and use the other 5 inch cut piece of cut yarn to tie the loop of yarn together.

Yarn Tied

Using your hot glue gun, dab a drop of glue on the knot of the hair you tied together. Place it on the top of the dried apple making it look like a head of hair. Make sure the bond is nice and strong by holding the glued hair down on the apple for about 30 seconds.

Yarn Hair on Apple Head

Now to make the witch’s hat. Cut one 3 inch circle and one 6 inch circle out of black cardstock or felt. Cut a 2 inch hole within the middle of the 3 inch circle. Take the unused 6 inch circle, and cut it in half.

Hat Cutouts

Bend one of the half circles into a cone, and glue the seam. You have just made the base of the hat. For more detailed instructions check out this video. Make little ½ inch slits all around the base of the cone, and fold them up. This is where the brim of the hat will be glued to the cone base. Take the 3 inch circle with the 2 inch hole in it, and stick it through the top of the cone pulling it down to where the folded up fringe of the cone base is. This is the brim of your hat.

Fringe Hat Side View

Fringe Hat Inside View

Glue both pieces together, and now your hat is complete.

Completed Witch Hat

Place the hat on the top of the apple head adjusting it to where it looks best. You may glue it down to the apple head if it tends to easily fall off.

Take your red sewing pins, and place them as eyes on your apple head. Then, take your white and black sewing pins, and use them to make the teeth. Using one black pin helps give the witch a rotten tooth look.

Sewing Needles

Witch Eyes & Teeth

Your witch is complete! Turn on the LilyPad MP3 and display your witch somewhere scary. Turn the lights low and hear her cackle. Enjoy!

Completed Apple Head Witch

Resources and Going Further

Thanks for reading! Check out these other great E-Textiles tutorials:

  • Twinkling Trick or Treat Bag - Make a light up goodie bag with conductive thread, LEDs, and the LilyTwinkle!
  • e-Textile Mask - Use LilyPad LEDs, a switched battery holder, and coin cell battery to make a fun light up mask for your next costume party.
  • My Drunk Kitchen Apron - A fun project that uses the LilyPad MP3 trigger. This apron will dispense helpful kitchen advice and humor from the host of My Drunk Kitchen, Hannah Harto!

learn.sparkfun.com |CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

Benchtop Power Board Kit Hookup Guide

$
0
0

Benchtop Power Board Kit Hookup Guide a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t262

Board Overview

The Benchtop Power Board Kit enables you to power up embedded electronics projects from a benchtop power supply. The kit breaks out the most commonly used voltages for physical computing projects to binding posts, including 3.3V, 5V, 12V and -12V.

Each power rail is spaced to fit banana jacks, and has a replaceable 5A fuse on it. It connects to a standard computer supply via an ATX connector.

Kit Parts laid out

This board will require assembly before use.

To complete this tutorial, you will need the following materials.

  • Benchtop Power Board Kit
  • Power Supply with an ATX connector
  • Standard soldering materials
  • Hookup wire

Suggested Reading

If you aren’t familiar with the following concepts, you may want to check those out before moving ahead in this tutorial.

Hardware Assembly

When soldering your kit together, it’s generally a good idea to check that you have all of the components first and then start soldering with the smallest components first.

We are going to start with the 1K Ohm resistor. Since resistors are not polarized, it doesn’t matter which way we plug it into the board. Bend the legs at 90 degrees to the body of the resistor, and place one leg in each hole next to the 1K silkscreen on the top of the board. You should then solder the resistor legs on the side of the board opposite all of the silk screen. Make sure you get a good connection between the resistor legs and the board.

Resistor Soldered

Resistor soldered in the lower left corner of the board.

Once you have the resistor securely attached, it’s time to add the red LED to the board. LEDs are polarized, so double check that you have the LED oriented correctly before soldering it down.

When looking at the LED, one leg should be shorter than the other. This is the cathode, or positive leg. The longer leg, the anode, should be placed in the hole closest to the flat edge of the LED silk screen on the board. This flat edge on the silk screen will also correspond to the flat edge of the LED casing as well. Again, this is important! If you solder in the LED backwards, it will not function!

LED Orientation

Make sure the LED is oriented properly before soldering it!

Flip the board over and solder the LED just like the resistor.

The next component to solder on is the switch. The switch is not polarized (just like the resistor), so you can place it in any orientation on the board. Place it in the box with the On/Off silk box, and solder the legs on the bottom of the board.

Switch Soldered

At this point, your board should look like this.

The next components you want to solder are the fuse clips. These clips are basically shaped pieces of conductive metal, but they still need to be oriented properly!! If you look at a single clip, one side of the U-shape will have two little curved-in pieces. These are designed to prevent the fuse from slipping out the end of the fuse clip. You will be pairing these up on the board (2 clips for each fuse), so they need to be oriented correctly to ensure that the fuse will actually fit in between them.

If you look closely at the silk screen on the board for the fuse clips, you will see one side of the square has a secondary line added. This is the side you should orient the curved bits towards.

Fuse clip orientation

Notice the secondary silk screen line on the same side as the curved edge on the clip.

Remember you need to be able to hold a fuse between each pair of clips, so be very careful when inserting them into the board. Double-checking before you solder them in will prevent frustrating rework time.

Fuse clip pair

These can be a bit finicky at staying in the holes while you solder them, so it may help to bend the tab out a bit on each leg of the clip before attempting to solder them. Also, keep in mind that these are just basically hunks of metal, so they will take a lot of heat from the soldering iron to get a properly flowed joint. The clip itself will also heat up, so make sure you don’t accidentally touch it and burn yourself!

Once the fuse clips are in, you can either insert the fuses, or wait until you are done soldering, so they aren’t in the way.

Inserted fuse

If the fuse slips out or won’t stay inserted, take a pair of pliers and bend one side of the clip in towards the other. You’ll want a good connection between the fuse clip and the fuse.

The last component you will be soldering onto the top of the board is the ATX connector. Make sure you carefully align all the pins and line up the edge of the connector with the edge of the board. The two plastic clips should also line up and snap into the vias on the board, to ensure the connector is oriented properly. Flip the board over and solder each of the pins. Make sure you don’t bridge any of these - this connector can handle a large amount of current and a short could ruin your day.

ATX connector

Make sure you insert the ATX connector all the way into the board before soldering it down. The two white tabs should pop through the guide-holes.

Once you have all of the components soldered to the top of the board, it’s time to connect the wires to the board. You will want to cut 8 2-inch pieces of wire (one for each barrel jack connector). I personally like to use red hook-up wire for the positive voltage lines and black hook-up wire for the ground voltage lines. Strip a bit of the coating off of each end of the wire. Once the wire is prepped, it’s time to solder it.

Pre-cut wire

Prepped wire inserted into bottom of the board

To make the rest of the assembly go smoothly, you should connect the wire to the bottom of the board, meaning that you will be soldering on the top of the board. This should be opposite of all of the other soldering you have done up to this point.

Wires all soldered

So close to completion!

Once everything is soldered properly to the board, double check that you don’t have any jumpers anywhere, and also make sure you clip any component legs that could potentially short out later.

It’s time to add in your barrel jack connectors. You will want to unscrew the large nut from each jack, orient the jack in the hole in the board, and then reattach the nut on the bottom to secure the jack to the board. Again, this should follow the convention of red for positive voltages and black with ground connections.

Inserting barreljack

To connect your barrel jacks to your wires, you will want to unscrew the first small nut on the bottom of the barrel jack. Take the corresponding wire for that jack, and wrap it around the bottom of the jack. Then secure the wire in place by tightening back on the first nut to the jack.

Wire connected to barrel jack

It is extremely important at this step to ensure you connect your wires tightly to the jacks and to clip of any dangling ends. We really don’t want these to short out once the system is powered!

Tightening nut on wire

Tighten those connections and trim those potential shorts.

The final step of the assembly is to attach the stand-offs. Keep in mind this step is optional, depending on how you will be using the board. If you intend to mount this into a case, you may not need the following steps. We do have a template file in the GitHub repo that you can use to mill or cut out a space for this board if you are so interested.

Insert a screw into the top of the board so the screw head lays flush on the same side as the components. Screw on the plastic standoff on the bottom of the board.

Standoff attachment

If you didn’t already, now is the time to insert the fuses into the clips.

Your assembly is now complete!

Complete Kit

System Connection

Now that you have your Benchtop Supply soldered together, it’s time to power it up! First, you will need to decide what system you are powering. For this example, we will be powering up a 4 RPM Standard Gear Motor. This motor can run from 3-12V, making it a great piece to simply test out several of the power rail connections on the Benchtop board.

Plug in the computer power supply’s ATX connector into the Benchtop Power Supply. Since there is a power switch on the Benchtop Power Supply board, you can turn on the computer power supply and leave it on.

Place the bare wire ends into the barrel jacks of the appropriate voltage rail for your project. In our case, we are hooking up the motor to the 3.3V rail initially. Flip the power switch on the Benchtop board and you should see your motor spinning!

Resources and Going Further

Now that you understand the functionality of the Benchtop Power Supply board, you can use it to power many different projects and prototype many different components. We’d love to hear what you come up with!

If you have any feedback, please visit the comments or contact our technical support team at TechSupport@sparkfun.com.

Check out these additional resources for more information and other project ideas.


learn.sparkfun.com |CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

21st Century Fashion Kit: Electrochromatic Circuits

$
0
0

21st Century Fashion Kit: Electrochromatic Circuits a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t323

What is an Electrochromatic Circuit?

Electrochromatic circuits use electricity to make something change color. It’s very experimental, so you won’t see anything electrochromatic for sale in the store. Here’s a tutorial to get you started making your own electrochromatic circuit. You will combine thermochromatic pigment (which changes color when heated) with steel conductive thread (that will heat the pigment in a short circuit). When you push a felt button, your electrochromatic circuit will turn on, and a design will appear in the thermochromatic pigment. Here’s a video example:

Suggested Reading

Before getting started with this tutorial, make sure you’re familiar with these other concepts first.

Required Materials

Craft materials first:

  • Scissors
  • Felt (to create the button)
  • Thread
  • Thin Fabric to paint your electrochromatic design (quilting weight works well)
  • Fabric Paint
  • Paint Brush
  • Paper Plate (to mix paint on)
  • Fabric Glue

All of the parts for this are included in the 21st Century Fashion kit. Should you need to buy all the parts separately, here is a wishlist for your convenience.

Making a Soft Circuit Button

In this section, you will use conductive thread and felt to make your own button. When you push the felt, two pieces of conductive thread inside of the button will touch turning the circuit on.

To begin, Cut a piece of felt for the top of the button and a piece for the inside. Cut a small hole in the inside piece of felt (the conductive thread will touch through this hole when the button is pushed).

Using the conductive thread, sew from In+ on the MOSFET power Controller to the side of your button location. With a second piece of conductive thread, sew from In- to the bottom of your button location. For a strong secure connection, stitch through the through-holes in the board a few times, and make sure your stitches are tight. The two threads should not touch. Tip: Don’t use your fancy sewing scissor to cut the conductive thread; it is steel and will dull them.

steps one through three

With one thread, create a long stitch in the fabric that will go under the button. Sew back over the stitch three times, then tie off the thread on the back. Cut off any loose ends.

step 4

Place the felt button inside piece over the long stitch. With the remaining conductive thread, sew across the felt button inside piece so that the two threads are perpendicular to each other. Stitch so that the thread spans across the top of the hole and is separated from the bottom thread by the felt. Once you’ve sewn to the opposite side of the button, tie off the thread on the back, and cut the loose end. Make sure the two threads do not touch.

Fine-tuning Your Button

This is experimental fashion, so getting a working button takes some fine tuning. Be sure to unplug your battery whenever you are working on your circuit.

alt text

Tape four inches (4") of conductive thread between Out+ and Out – on the Power Controller. Make sure the thread lays flat against the metal part of the through-holes and is taped tightly in place.

alt text

Start by making sure your button can be turned off. Plug your battery in and look to see if the thread is heating up and making the thermochromatic powder turn white. You may need to press the thread against bag of powder with your fingers to make sure the thread is close enough to the powder to heat it. If it turns white, unplug your battery immediately. This means the top thread of the button is too close to the bottom thread (it’s completing the circuit before you even press the button!). Cut a small doughnut of felt and slide it under the button felt.

alt text

Repeat until the thread is no longer heating up and making the thermochromatic pigment turn white (I wound up adding two doughnuts of felt under my button).

Now it’s time to make sure your button can be turned on. With the battery plugged in, place the top piece of felt on the button. Then push the button. Make sure that the thread is heating and turning the powder white. If the thread is not heating, trim the holes in the felt button and felt doughnuts a little bigger. Then try to push the button again. Be patient, you will probably need to trim and test several times. Repeat until your button turns on and off at the appropriate times.

Got a working button? Great! Stitch all of your felt pieces in place with traditional thread. Be careful not to sew through the conductive thread. Give the button one more test. If it isn’t working, you may need to do some restitching and troubleshooting.

Stitching Your Design

Sew conductive thread where you want your design to change color. You can use a minimum of two inches (2") and a maximum of six inches (6") of this particular steel conductive thread. Less than two inches will overheat the battery and more than six inches may not heat hot enough to make the pigment change color.

Tip: After sewing the connection to Out-, I cut my thread so that it was nine inches long. When there were only three inches left, I stitched the connection to Out+.

alt text

Start by sewing the connection at Out- by stitching through the through-holes a few times. For a secure connection keep your stitches tight.

alt text

If you want there to be a little space between your board and your design, pull your thread to the back of the fabric and start stitching a little ways away from your board. If you need some extra insulation to keep this part of the thread from heating the thermochromatic pigment, you can stick some felt between the thread and the fabric.

Sew your design with an upside-down invisible stitch by sewing through a few threads of the fabric every 1/8 inch. This will keep the thread mostly on the top of the fabric so that it can heat the pigment.

Finish by sewing the connection at Out+ by stitching through the through-holes a few times.

alt text

Mix the thermochromatic pigment with your paint, and paint your design on the piece of thin fabric. Put your thermochromatic design on top of your stitched conductive thread design. It is important that the conductive thread design is placed flat against the thermochromatic design, so that it will heat up evenly. You can adhere your designs with fabric glue, or very carefully stitch them to make sure they are touching evenly.

alt text

You’re done! This is just one of an endless variety of applications for thermochromatic pigment. It’s a beautiful way to paint everything from an evening gown to your fingernails with heat-reaction.

Resources and Going Further

Thanks for reading! Check out these other great E-Textiles tutorials:

  • Humidity-sensing LED Flower - Use the 21st Century Fashion Kit to create a smart flower that can tell you if it needs some water.
  • Twinkling Trick or Treat Bag - Make a light up goodie bag with conductive thread, LEDs, and the LilyTwinkle!
  • E-Textile Mask - Use LilyPad LEDs, a switched battery holder, and coin cell battery to make a fun light up mask for your next costume party.
  • My Drunk Kitchen Apron - A fun project that uses the LilyPad MP3 trigger. This apron will dispense helpful kitchen advice and humor from the host of My Drunk Kitchen, Hannah Harto!

learn.sparkfun.com |CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

APDS-9960 RGB and Gesture Sensor Hookup Guide

$
0
0

APDS-9960 RGB and Gesture Sensor Hookup Guide a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t321

Introduction

Touchless gestures are the new frontier in the world of human-machine interfaces. By swiping your hand over a sensor, you can control a computer, microcontroller, robot, etc. One manufacturer has even created a touchless toilet that flushes when you move your hand over the tank. The Avago APDS-9960 offers ambient light and color (as clear, red, green, and blue) measuring, proximity detection, and gesture sensing.

Avago APDS-9960 Breakout Board

The APDS-9960 RGB and Gesture Sensor board breaks out the pins on the Avago APDS-9960 so you can easily use it in a variety of projects. The APDS-9960 uses the I2C interface for communications.

Covered In This Tutorial

In this tutorial, we will give an overview of the APDS-9960 sensor board and provide an example hookup and code. The tutorial is split into the following sections:

  • Board Overview– To begin, we’ll go over each of the pins on the breakout board and their function. This section also overviews the jumpers on the front of the board.
  • Hardware Hookup– In this section, we’ll show you how to hook the APDS-9960 up to an Arduino to detect gestures via I2C.
  • Arduino Library Installation– Here, we download and install the APDS-9960 Arduino library.
  • Gesture Sensing Example– We try out the sensor with the the GestureTest example.
  • Resources and Going Further– You made a simple gesture sensor, but where do you go from there? This section gives you some additional resources for getting more use out of the APDS-9960.

Materials Used

You will need a few components and tools to follow along with this tutorial. Here is what you will need:

If you do not have specifically a 3.3V Arduino Pro, there are a number of ways to complete the walkthrough. In general, you will need:

  • Arduino or other microcontroller– You will need something that is capable of I2C and communicating back to the computer (e.g. serial communications). The microcontroller needs to have a 3.3V I/O voltage or you will have to use a level shifter. We are using the 3.3V Arduino Pro, but the 3.3V Arduino Pro Mini would work as well.
  • Level shifting– If you are using a 5V Arduino, like the Uno or RedBoard, you will need to use a level shifter, such as the bi-directional logic level converter.
  • Connectors– You will need to interface your microcontroller with the breakout board. Male headers are perfect if you’re using a breadboard. Another option is to use wire to connect the breakout board directly to the microcontroller.
  • Soldering tools– After you’ve picked a connector, you will need to solder it to the breakout board. A simple soldering iron and some solder should be all you need.

Recommended Reading

Before getting started with the APDS-9960, there are a few concepts that you should be familiar with. Consider reading some of these tutorials before continuing:

  • What is an Arduino?– We will use an Arduino to control the APDS-9960
  • I2C– I2C is the communication protocol used by the APDS-9960
  • Serial Communication– We use serial communications (with the FTDI breakout board) to program the Arduino and provide information to our computer from the Arduino
  • How to Use a Breadboard– The breadboard ties the Arduino to the APDS-9960 breakout board

Board Overview

Pin Descriptions

The APDS-9960 breakout board provides 6 pins to provide power to the sensor and I2C bus.

Front of APDS-9960 breakout board

Pin LabelDescription
VLOptional power to the IR LED if PS jumper is disconnected. Must be 3.0 - 4.5V
GNDConnect to ground.
VCCUsed to power the APDS-9960 sensor. Must be 2.4 - 3.6V
SDAI2C data
SCLI2C clock
INTExternal interrupt pin. Active LOW on interrupt event

Setting the Jumpers

On the front of the breakout board are 2 solder jumpers:

  • PS– This jumper connects the power supplies of the sensor and IR LED (also located on the APDS-9960) together. When the jumper is closed (i.e. connected), you only need to supply power to the VCC pin to power both the sensor and the IR LED. If the jumper is open, you need to provide power to both the VCC (2.4 - 3.6V) and VL (3.0 - 4.5V) pins separately. This jumper is closed by default.
  • I2C PU– This is a 3-way solder jumper that is used to connect and disconnect the I2C pullup resistors. By default, this jumper is closed, which means that both SDA and SCL lines have connected pullup resistors on the breakout board. Use some solder wick to open the jumper if you do not need the pullup resistors (e.g. you have pullup resistors that are located on the I2C bus somewhere else).

Hardware Hookup

Add Headers

Solder a row of break away male headers to the 6 headers holes on the board.

Solder headers onto board

Connect the Breakout Board

We will be using the Arduino Pro’s regulated 3.3V power and I2C bus with the APDS-9960. Note that we are leaving VL on the breakout board unconnected.

IMPORTANT: You must use 3.3V! If you try to use a 5V power supply or 5V I2C communications, you risk damaging the APDS-9960. If you are using a 5V Arduino (e.g. UNO), then you need to have some kind of level shifting.

Connect the breakout board to the following pins on the Arduino:

APDS-9960 to Arduino Fritzing Diagram

APDS-9960 Breakout BoardArduino Pro 3.3V
GND GND
VCCVCC
SDAA4
SCLA5
INT2

Arduino Library Installation

To use the APDS-9960, you will need some supporting software. If you are using an Arduino, then you are in luck! We created an Arduino library that makes the APDS-9960 easy to use. Click the button below to download the latest version of the APDS-9960 breakout board project, which includes the Arduino library.

Download the Arduino Library!

Unzip the downloaded file and navigate to <your download directory>\APDS-9960_RGB_and_Gesture_Sensor-master\APDS-9960_RGB_and_Gesture_Sensor-master\Libraries.

Install APDS-9960 Arduino Library

Follow this guide on installing Arduino libraries to install the files within the SparkFun_APDS9960 directory as an Arduino library.

Gesture Sensing Example

Load the GestureTest Example

Open up the Arduino program and select File → Examples → SparkFun_APDS9960 → GestureTest.

APDS-9960 GestureTest example

Plug in your FTDI Breakout (3.3V) to the Arduino Pro (3.3V). Attach a USB mini cable from your computer to the FTDI Breakout. If you have not previously done so, install the FTDI drivers.

Connect FTDI breakout board to the Arduino Pro

For reference, here is the GestureTest.ino sketch.

language:c
/****************************************************************
GestureTest.ino
APDS-9960 RGB and Gesture Sensor
Shawn Hymel @ SparkFun Electronics
May 30, 2014
https://github.com/sparkfun/APDS-9960_RGB_and_Gesture_Sensor

Tests the gesture sensing abilities of the APDS-9960. Configures
APDS-9960 over I2C and waits for gesture events. Calculates the
direction of the swipe (up, down, left, right) and displays it
on a serial console.

To perform a NEAR gesture, hold your hand
far above the sensor and move it close to the sensor (within 2
inches). Hold your hand there for at least 1 second and move it
away.

To perform a FAR gesture, hold your hand within 2 inches of the
sensor for at least 1 second and then move it above (out of
range) of the sensor.

Hardware Connections:

IMPORTANT: The APDS-9960 can only accept 3.3V!

 Arduino Pin  APDS-9960 Board  Function

 3.3V         VCC              Power
 GND          GND              Ground
 A4           SDA              I2C Data
 A5           SCL              I2C Clock
 2            INT              Interrupt

Resources:
Include Wire.h and SparkFun_APDS-9960.h

Development environment specifics:
Written in Arduino 1.0.5
Tested with SparkFun Arduino Pro Mini 3.3V

This code is beerware; if you see me (or any other SparkFun
employee) at the local, and you've found our code helpful, please
buy us a round!

Distributed as-is; no warranty is given.
****************************************************************/

#include <Wire.h>
#include <SparkFun_APDS9960.h>

// Pins
#define APDS9960_INT    2 // Needs to be an interrupt pin

// Constants

// Global Variables
SparkFun_APDS9960 apds = SparkFun_APDS9960();
int isr_flag = 0;

void setup() {

  // Initialize Serial port
  Serial.begin(9600);
  Serial.println();
  Serial.println(F("--------------------------------"));
  Serial.println(F("SparkFun APDS-9960 - GestureTest"));
  Serial.println(F("--------------------------------"));

  // Initialize interrupt service routine
  attachInterrupt(0, interruptRoutine, FALLING);

  // Initialize APDS-9960 (configure I2C and initial values)
  if ( apds.init() ) {
    Serial.println(F("APDS-9960 initialization complete"));
  } else {
    Serial.println(F("Something went wrong during APDS-9960 init!"));
  }

  // Start running the APDS-9960 gesture sensor engine
  if ( apds.enableGestureSensor(true) ) {
    Serial.println(F("Gesture sensor is now running"));
  } else {
    Serial.println(F("Something went wrong during gesture sensor init!"));
  }
}

void loop() {
  if( isr_flag == 1 ) {
    handleGesture();
    isr_flag = 0;
  }
}

void interruptRoutine() {
  isr_flag = 1;
}

void handleGesture() {
    if ( apds.isGestureAvailable() ) {
    switch ( apds.readGesture() ) {
      case DIR_UP:
        Serial.println("UP");
        break;
      case DIR_DOWN:
        Serial.println("DOWN");
        break;
      case DIR_LEFT:
        Serial.println("LEFT");
        break;
      case DIR_RIGHT:
        Serial.println("RIGHT");
        break;
      case DIR_NEAR:
        Serial.println("NEAR");
        break;
      case DIR_FAR:
        Serial.println("FAR");
        break;
      default:
        Serial.println("NONE");
    }
  }
}

Run

Make sure you have the correct serial port selected under Tools → Serial Port and “Arduino Pro or Pro Mini (3.3V, 8MHz) w/ ATmega328” selected under Tools → Board. If you have never used the Arduino IDE before, this turoial should get you started.

Click the Upload button and wait for the program to finish uploading to the Arduino. Select Tools → Serial Monitor to open up the serial terminal. More info on the Serial Terminal can be found here. You should see a couple of messages noting that “APDS-9960 initialization complete” and “Gesture sensor is now running.”

APDS-9960 GestureTest initialization

Hover your hand 4 to 8 inches (10 to 20 cm) above the sensor but off to one side (i.e. not directly above the sensor). While maintaining the same height, swipe your hand over the sensor (into and then immediately out of range of the sensor). If you move too fast, the sensor will not recognize the gesture.

Swipe

Gestures will appear on the serial monitor, which indicate the direction of the swipe.

APDS-9960 swipe directions

There are also 2 other gestures available: NEAR and FAR.

A NEAR gesture can be achieved by holding your hand far above the sensor (greater than 10 inches (25 cm)), bringing it close to the sensor (about 2 inches (5 cm) directly above the sensor), holding it there for at least 1 second, and then removing your hand.

A FAR gesture can be achieved by holding your hand directly above and close to the sensor (about 2 inches (5 cm)) for at least 1 second and then moving your hand up directly above and out of range of the sensor.

If a gesture was not correctly interpreted, NONE will appear in the serial monitor.

Other gestures supported by the APDS-9960

Supported Gestures

Here is a list of the currently supported gestures. Make sure each gesture begins outside of the range of the sensor, moves into the range of the sensor, and ends outside the range of the sensor.

GestureDescription
UPA swipe from the bottom of the board to the top and out of range of the sensor. Make sure that your wrist/arm is not in the sensor's range at the end of the swipe!
DOWNA swipe from the top of the board to the bottom and out of range of the sensor.
LEFTA swipe from the right side of the board to the left and out of range of the sensor.
RIGHTA swipe from the left side of the board to the right and out of range of the sensor.
NEARObject (e.g. hand) starts far above the sensor, moves close to the sensor, hovers for at least 1 second, and moves out of range of the sensor.
FARObject starts near the sensor, hovers for at least 1 second, and then moves up above and out of range of the sensor.
NONEThe sensor could not correctly guess the gesture being performed.

Resources and Going Further

Now that you have seen the gesture recognition capabilities of the APDS-9960, you can begin to use it in your project! Keep in mind that the APDS-9960 is also capable of sensing object proximity and ambient/color light. Try out the other examples in the SFE_APDS9960 library to see what the sensor can do:

  • AmbientLightInterrupt– This example shows how you can generate an Arduino interrupt whenever the ambient light falls below a given level. You can also change it to throw an interrupt when the light rises above a certain level.
  • ColorSensor– This demo shows how to read ambient, red, green, and blue light values from the APDS-9960.
  • GestureTest– We used this example in this hookup guide. It shows how to read basic gestures with the APDS-9960.
  • ProximityInterrupt– The APDS-9960 can be used to detect when objects move within range of its sensor. This example shows how to throw an interrupt whenever an object moves within a certain range of the sensor. You can also change the limits to generate an interrupt whenever an object moves outside of a certain range.
  • ProximitySensor– You do not need to use interrupts with the proximity sensor. In this demo, we show you how to poll the sensor for proximity data at regular intervals. Try running this example and moving your hand close to the sensor.

Resources

Here are some additional resources to help you with the APDS-9960:

Other Tutorials

What will you make with the APDS-9960? If you need some inspiration, check out these related tutorials:

Serial Graphic LCD Hookup

December 3, 2013

Learn how to use the Serial Graphic LCD.

RGB Panel Hookup Guide

December 12, 2013

Make bright, colorful displays using the 32x32 and 32x16 RGB LED panels. This hookup guide shows how to hook up these panels and control them with an Arduino.
New!

Micro OLED Breakout Hookup Guide

October 30, 2014

Learn how to hook up the Micro OLED breakout to an Arduino. Then draw pixels, shapes, text and bitmaps all over it!

learn.sparkfun.com |CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

Sunny Buddy Solar Charger V13 Hookup Guide

$
0
0

Sunny Buddy Solar Charger V13 Hookup Guide a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t313

Introduction

If you have an older version of the Sunny Buddy (V1.0 and older), please refer to this hookup guide. For V1.3 and beyond, continue reading. Check the back of the board for the version number.


The Sunny Buddy is a small maximum power point tracking solar charger for single-cell LiPo batteries.

Product pic

This tutorial will help you understand what the Sunny Buddy is, why it’s useful, and how to use it.

What You’ll Need

The Sunny Buddy can’t do anything without a supporting cast. Pair the Sunny Buddy with these buddies to make it work:

  • Solar Panel– Most panels should work, just make sure they produce an output voltage between 6-20V. Our small, large, and huge panels will all work. Panels with a center-positive barrel jack (like those) will be able to plug directly into the Sunny Buddy.

Solar Panel

  • LiPo Battery (single cell) – The Sunny Buddy is intended to charge a single Polymer Lithium Ion cell. LiPo’s come in all shapes and sizes, we recommend you use one with a capacity greater than 450mAh (e.g. 850mAh, 1000mAh, or 2000mAh). Batteries like those, with a JST termination, will plug directly into the Sunny Buddy. The 450mAh size suggestion is due to the charge rate of the Sunny Buddy–most LiPo cells don’t like being charged faster than their equivalent capacity.

A LiPo battery

  • A Load– Your battery has to power something, right? Your load can be anything from an LED to an Arduino-powered robot.

Suggested Reading

Here are some other tutorials you may find useful before delving into this hookup guide:

  • Batteries– Check out the battery tutorial for some help understanding why the Sunny Buddy works only with LiPo batteries.
  • Electricity Basics– It may be useful to review how current and voltage combine to transmit power to a load.
  • How to Power Your Project– Solar power and batteries are just one of many ways to power your project. Make sure to consider all possibilities!

Why MPPT?

The Sunny Buddy is a maximum power point transfer (MPPT) solar charger. Why does that matter? What makes it worth having in a circuit? The answers lay ahead.

How Batteries Are Charged

Battery charging is a current dependent action, not a voltage dependent action. Battery chargers monitor the current flowing into the battery and limit it to some set value, chosen to prevent damage to the battery. An ideal battery charger will provide as much current to the battery as it is capable of drawing from its power supply, but no more than the battery can handle.

Power Supply Behavior

Consider the first part of that last sentence: “as much current as it is capable of drawing from its power supply.” I’ve collected some data from five different power supplies: a 2000 mAh LiPo battery, a bench supply, our small solar cell, our large solar cell, and the Sunny Buddy attached to the small cell in full Colorado sunlight (albeit in midwinter).

Load testing results of various supplies
That’s some mighty fine data!

The chart compares output voltage versus load current for the five sources listed above: in short, how much current each is capable of providing. For a sort of baseline comparison, note that the output of the bench supply, the battery, and the Sunny Buddy are pretty flat. You can clearly see the point at about 240mA where the Sunny Buddy could no longer safely draw more current from the solar cell. In a charging application, that’s the point at which it would have settled in and charged the battery. Since I was actively increasing the load to stress the supplies, it folded back to a lower voltage to gracefully handle the excessive load without bursting into flames.

The solar cells, however, behave quite differently. They slowly droop until they reach a certain point, then decline increasingly rapidly until even a small increase in current draw causes the output voltage to plummet. There’s a point on that curve, in the “knee” region, where the power transferred to the load is at its peak. This point, called the maximum power point, is crucial to squeezing the most efficiency out of a solar cell.

Finding that point is the key here. The solar cell curves will be compressed along the X-axis in lower light conditions, and, while the unloaded voltage may remain quite high even in low light, the amount of current which can be drawn from the cell decreases rapidly with the amount of light available.

The Sunny Buddy locks in on that point in the curve, pulling the maximum current the cell will provide, but no more, and turning it into charge current. The circled region of the graph shows this: the highest current the small solar cell can deliver is around 180mA, but the Sunny Buddy pushes out 240mA before entering current limit. That’s an extra 33% more charge current available to your battery over a comparable 5V charger.

Efficiency

Efficiency in any power supply system can be said to be the ratio of power out to power in. This is another place where the Sunny Buddy is better than comparable linear solutions.

The Sunny Buddy is a switching supply; the output power is given by the equation Pout = Pin * Efficiency. The Sunny Buddy’s efficiency has repeatedly measured to be about 80% in tests.

Let’s consider a linear solution. To avoid getting too far into that steep region of the graph, we’ll set our charge current at 160mA. To calculate the output efficiency, we divided the output power by the input power. Looking at the voltage on the solar cell curve, we see that for 160mA the output voltage is about 7V; thus, input power is 7V * 160mA = 1142mW. Output power is 4.2V * 160mA = 672mW. Tthat’s the approximate charge voltage times the charge current. Efficiency is power in over power out: 672/1142 = 59%. Best case, that’s the percentage of the electric power generated by the cell that you’re using. It will actually be lower when the cell voltage is lower than 4.2V, which it will be over most of the charging range.

Here, again, Sunny Buddy wins: it’s using (at least) 20% more of the available power from the solar cell.

Cloudy Days

But what happens to our linear charge circuit when the sun goes behind a cloud? As I mentioned earlier, as available solar energy decreases, the graph compresses along the X-axis. If that steep region drops below the set current of our charger, things go pear-shaped fast. The available voltage plummets, and the charger stops working.

We can combat that by either setting a lower charge current in the first place, which isn’t ideal because it means on a good, sunny day, you’re losing a lot of potential solar energy by not loading the solar cell heavily enough, or by servoing our charge current to the voltage, reducing or increasing it based on the cell voltage. While that may sound simple, in practice it’s quite complex.

Enter the Sunny Buddy

The Sunny Buddy does just that: it monitors the cell voltage and stops drawing current when the voltage droop indicates the cell is being pushed a little too far. Furthermore, since the Sunny Buddy uses a switching topology rather than a linear topology, it has a better efficiency than any linear solution can provide.

Hooking It Up

There are three parts to consider when embedding the Sunny Buddy into a project: the solar panel input, battery output, and load.

Sunny Buddy Hookup

Solar Panel Input

The input side of the Sunny Buddy comes with a common barrel jack installed. SparkFun’s small, large, and huge solar panels all come with this sort of jack installed, and can be plugged directly into the Sunny Buddy.

Input diagram

There are also additional footprints for attaching 3.5mm screw terminals or an additional barrel jack to the board. Please note that if you intend to use two solar panels, you must clear solder jumper JP1 (it ships closed by default) and close solder jumper JP2 (it ships open by default). Failure to do this will result in the second supply being left unconnected. If both jumpers are left unconnected, no power will be sent to the board, and if both are shorted, the second panel will be shorted out and contribute no power to the system but may be damaged by being short circuited.

The maximum recommended input to the board is 20V; this is a stack of two of our panels. The minimum is 6V, but most solar panels should be above this.

A useful trick for monitoring the input current of a single-panel system is to clear JP1 and close JP2, then connect an ammeter between the + pads on the two 3.5mm footprints. This will allow you to monitor the current draw from the solar panel. Note that JP1 must be resoldered and JP2 reopened before attempting to use the SunnyBuddy without the meter in place!

Setting the Input Current Limit

The revised Sunny Buddy has an input set point potentiometer. This allows the user to set an input voltage at which the Sunny Buddy will reduce its current draw to maintain peak power input from the solar panel.

You’ll want the voltage at this node to be at 2.7V when the solar panel is at the “knee” voltage we discussed in the Why MPPT? section above. Some solar cell manufacturers may give you this information; the manufacturers of our panels, however, have not. You can either take the hard road and characterize your cell (ick) or take the easy road and make an educated guess that the MPPT point will be at about 90% of the voltage you see when you’re in full sun.

To find that point, plug your solar panel into the Sunny Buddy, but don’t put a battery or load on it. Measure the voltage from the “SET” pad to the “GND” pad next two it, and tweak the potentiometer until that voltage is about 3V. At that point, the Sunny Buddy will draw current until either 450mA is going to the load and the battery or the solar cell voltage is 90% of its full-sun open-circuit nominal voltage.

Battery Output

The output of the Sunny Buddy is intended to charge a single Polymer Lithium Ion cell. A 2-pin JST connector is populated, and will mate up to most of the LiPo batteries SparkFun sells.The load should be connected in parallel with the battery; again, footprints for a 3.5mm terminal or a standard .1" spaced header have been provided.

Output diagram

The charge current is set by resistor R1 in the schematic. By default it comes set to a maximum charge current of 450mA. It’s recommended that batteries not be charged at greater than their capacity rating; thus, the smallest battery that should be charged with the Sunny Buddy is 450mAh.

The revised Sunny Buddy adds an additional sense resistor footprint in parallel with the built-in resistor. The charge current is equal to .1/(R1||RSen); putting a 1-ohm resistor on the Rsen pads will increase the charge current to ~550mA. R1 can be desoldered from the board if charge currents below 450mA are desired.

Note that it is possible to set the charge current to impossible levels. If the current level is too high, the inductor will saturate, which will limit the output current artificially.

Finally, note that there’s a jumper on the board that can be cut to allow you to monitor the output current of the charger. You’ll need to reconnect the jumper pads after you’ve finished taking measurements.

The Load

The load can be connected to either the 0.1" or 3.5mm spaced pads on the right edge of the board.

It’s important that the load not be too heavy; since it is in parallel with the battery, it will steal some of the charge current from the battery when it is operating.

To avoid this, consider putting active circuitry to sleep whenever possible, or using a microcontroller to turn parts of the load on or off as they are not needed. Methods for doing this are beyond the scope of this tutorial.

Resources & Going Further

If you’re looking to get more out of your Sunny Buddy, be sure to check out these resources first:

If you’re looking for some inspiration for a project that you can embed the Sunny Buddy into, check out some of these related tutorials:

Wimp in action

The Wimp in action!


learn.sparkfun.com |CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado


Hackers in Residence - Sound and Motion Reactivity for Wearables

$
0
0

Hackers in Residence - Sound and Motion Reactivity for Wearables a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t12

A Dance of Sound, Light and Motion

At SparkFun, I wanted a smarter jacket: a color changing jacket that would react to my surroundings. The concept seemed simple enough. Using sound and motion sensing as an interface I’m able to change colors to merge with the environment. This elevates the need for buttons or switches that might otherwise take our user out of the present moment.

alt text

The finished product.

There are a number of challenges, mainly comfort and control. I find one of the keys to comfort in wearing a lit up garment is having symbiosis with the surrounding environment. However, I needed to distinguish between the high energy atmosphere of a frenetic art opening and otherwise subdued activities like sharing a meal or waiting in line. We often don’t take into account how bright our garments may be to in the eyes of others, and the aim of this project was to tackle this problem. One way to accomplish this synergy with one’s environment is to listen before emoting, or, this this case, sense before lighting too brightly or deploying patterns too quickly.

alt text

A long exposure photo displaying how sounds can be viewed across various frequencies.

I used an accelerometer and microphone to sense the environment and wearers energy level. Rapid changes in acceleration and specifically rotations of the wearer are interpreted as being in an environment where lighting may be a bit brighter and patterns cycle faster.

I used a microphone to sense the ranges and volume of various frequencies. Fairly normal frequencies of human voices and minimal volumes would be interpreted to give a fairly consistent color without much movement. If there were low frequencies and louder volumes, the design assumes music is being played and introduces more colors.

alt text

With little motion or sound, the colored spine appears to reflect the given color rather than emit.

A specific color pallet was chosen to also merge the wearer into their surrounding. A pinkish mid range is in harmony with the rest of the design to blend in during times of inactivity while blues and turquoises become present during repeated audio with more low end. These blues are in direct contrast to the rest of the design and thereby become quite apparent.

Planning it Out

SparkFun’s amazing facilities and warehouse made for the problem of choice. Generally, I choose components based on what is readily available or least costly. Given my unique circumstance, I wanted to choose the very best components to ease the development and optimize for the overall quality of the affect.

alt text

Assembling the Hardware

Here is the hardware I ended up using in the project.


Let’s go over each component in detail.

Battery Power

I love these cell phone boost charger external batteries. Having the charger, boost regulator, battery, and protection circuitry all in one packages saves a ton of time and money. You can always charge your phone from it in a pinch and carrying an extra is easy with this thin design.

Of course I have to include a Wake-on-Shake. I’m starting to put them in all my mobile projects and have all but stop using power switches to turn things off. I’d been having entirely too much fun with these.

Motion

I choose to put a combined accelerometer and gyro on board to detect certain types of motion. Specifically, I wanted to isolate when one is spinning or turning around. I find this could in the future be a compelling control signal. The up and down motion of the body could be an indicator of walking, stillness, running, or dancing.

LEDs

I developed a variety of techniques for mounting LEDs for wearable use. WS2812 LEDs are by far my favorite. By only needing 3 conductors, I can now use the best conductive ribbon to attach them to my jacket. Using this very flexible e-textile spine makes it much more resilient to any movements and folding that a normal garment might undergo.

I cut a small portion out of the data trace of the conductive ribbon under where I’ll solder each LED. This allows the data lines to not be shared by multiple LEDs, so the signal can pass cleanly. I’ve started doing this a lot at Crashspace and even helped with a tutorial if you want to try sewing and wearing these NeoPixel/WS2812 style addressable strip LEDs yourself.

alt text

alt text

I ended up affixing these within a 3d printed led housing It adds some much needed diffusion and allows the LEDs to be unbuttoned should i want to wash the jacket.

alt text

alt text

alt text

I encourage you to go more extreme with your 3d printed led diffusors, if you dare.

Sound

Microphones are fun! Yet, sound reactivity is hard. It is a ton of data to parse through. It takes some serious sophistication to even determine the frequency of incoming sound.

Luckily, there is help. An Arduino can determine what frequencies are present, but I found you don’t get much indication of the volume within each frequency range.

I ended up testing a bunch of microphones (and their pre-amps) to determine which would give me the most fidelity at louder volumes. Using a set of pure data patches I was able to generate tones, read the Arduino’s frequency analysis, and compare.

I found the sound detector performed better overall. I love the added benefits of having the preamp broken out so it is easily tuned and the sound detection portion works very well as an additional sensor.

alt text

alt text

alt text

Mic Test - Pure Data

Performing some Mic tests with Pure Data.

alt text

Graph of all the results using different mic boards.

MSGEQ7 - Graphic Equalizer Display Filter

After digging into the microphone performance and testing the software FFT. I decided a hardware solution would make more sense. The MSGEQ7 did a much better job of analyzing the sound for various frequencies. Also, delegating this responsibility to an external piece of hardware simplifies the code and frees up my Arduino to control the lighting and analyze the motion data.

The circuit for the MSGEQ7 required some components I didn’t readily have on on hand. The Spectrum Shield works very well, but it way too big to wear in any comfortable way. After consulting the eagle files, I decided the best approach it was to cut it down to a more wearable size.

At half the size it still isn’t small, but it matches the size of all my other components and will now layout quite consistently within the collar.

Cutting the Spectrum Shield

Teensy 3.1

The Teensy is nice because you can power and program it directly from USB. This works well to get thing tested and running quickly.

The 5v tolerant inputs of the new Teensy 3.1 are great for the audio part of this project as running my microphone at 5v gets me more range.

Ultimately, I’m happy to run a 3.3v micro to avoid all the voltage level conversion required to interface with most accelerometers.

The 3.3v logic also happens to work well enough for the ws2812/Neopixel LEDs, barely.

alt text

Using any Teensy is a bit more complex to get up and running. You need to add a bunch of configuration, code, and libraries to your Arduino IDE. Luckily there is a great installer available that make this very straight forward for any operating system.

The Teensy has very recently added some audio offerings, which I may utilize to replace the msgeq7 portion of this project.

Software, Integration, and Smoothing

After selecting these components it comes time for some serious code, integration, and smoothing.

EWMA: Exponentially Weighted Moving Average

I hope we’ve all learned what it means to take the average of a given dataset. The average volume wouldn’t be very interesting and certainly not very reactive. By calculating simple average over time of results will converge on a single value. This doesn’t work because even large changes in sound or motion would not even be detected. It can also be a somewhat expensive operation to always be adding to bigger numbers and dividing.

A moving average is a great optimization and it allows you to recalculate each time a new datapoint arrives. This is a great optimization but continues to lack reactivity. I want instant feedback when loud sounds occur.

Exponential weighting really helps maintain this reactivity by weighting new data much more than the past values. This allows for instant feedback upon drastic changes while still avoiding the flicking and flashing experienced from noisy data.

In doing my research I found an EWMA is very often used to analyze financial markets as they need to quickly detect sudden rises and falls without paying too much mind to the minimal changes. This blog post does an excellent job of describing EWMA in detail for our purposes of smoothing.

EWMA Correction

I found a great Arduino library for EWMA and was quickly able to apply this smoothing with different coefficients to my motion axes and sound frequency ranges.

Resources and Going Further

You can learn more by digging through the some of code that integrates these four things (EWMA, MSGEQ7, NeoPixels, and an IMU).

I hope you enjoy the project and comment on what you like.

Many, many special thanks to my SparkFun family for the amazing learning opportunity and hosting me for the all too short residency.

alt text


learn.sparkfun.com |CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

Let It Glow Holiday Cards

$
0
0

Let It Glow Holiday Cards a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t318

Introduction

Craft a glowing card for friends and family this holiday season with paper circuits - no soldering required! This tutorial will guide you through how to create simple paper circuitry using only copper tape, a coin cell battery, a LilyPad Button Board, and an LED, and it will leave you with a basic understanding of how circuits work.

alt text

alt text

alt text

Paper engineer and pop up book designer Robert Sabuda allowed us to adapt some of his free templates for use with electronics. We’ll be covering the electronics build in this tutorial and linking to Robert’s instructions for the pop up cards.

Why Aren’t We Soldering?

You may have seen Nick’s awesome Father’s Day Card tutorial and are wondering why this one is different. In classrooms or homes where supplies or budgets are limited, using tape and craft supplies helps keep complexity down. The drawback is that the connections aren’t as sturdy/permanent with tape vs solder. You can always use these templates and solder components to the copper tape if you have the supplies on hand.

Suggested Reading

If you are brand new to working with electronics, here’s some helpful reading to check out:

Materials and Tools

Here is a list of all the materials and tools you’d need to follow along:

  • Copper Tape - 5mm width (~18" of tape per card)
  • LED (2 for Christmas Tree Design) *see note below about LED choices
  • Coin Cell Battery - 12mm (CR1225)
  • LilyPad Button Board -or- LilyPad Slide Switch
  • Cardstock (2-3 pieces)
  • Vellum or Parchment Paper (optional) - creates a nice diffused effect for LEDs in window cut outs
  • Clear Tape
  • Gluestick/Glue
  • Scissors/Hobby Knife
  • Hole Punch/Screw Punch (optional) - to cut out holes in Christmas Tree Design
  • Decorating Supplies - stickers, markers, white out pen (for Gingerbread House ‘icing’)

A note on LEDs:

We recommend using the smallest LED you can find - 3mm work well because they don’t add too much bulk to your card when folded. For extra flair try using cycling RGB LEDs. We’ve also found that cutting individual LEDs from a set of LED String Lights works well - you will have to use a hobby knife to scrape the coating off of the wires before using. We’ll cover that process later in the tutorial. Feel free to experiment with different LEDs and find what works best for your project.

Step 1: Print Templates

Right-click the images below and choose “Save Link As” to download the templates to your computer. Each file has two (or three) pages which includes all pop up pieces and the circuit template.

Print your templates out on cardstock. If needed, adjust your printer’s margins or choose ‘Fit to Page’ in the print settings. The card template is slightly smaller than the paper, make sure to cut along the black border for the final card size.

Set the pop up pages aside for now. We’ll build our circuit first and then assemble the pop up once the electronics are all installed.

alt text)

Gingerbread House Template - 3 pages

Print page 2 (pop up pieces) on brown cardstock for a great gingerbread house base, or print all on a light colored cardstock and color in when you are finished. Can also be used to create a winter cottage pop up.

alt text

Christmas Tree Template - 2 pages

Looks great if printed on green cardstock, or use light colored cardstock and decorate after assembling.

alt text

Window Template - 2 pages

Use stickers or paper cut outs on vellum to create a festive silhouette scene in the window frame.

Step 2: Create Copper Traces

Time to create a path for our electricity with copper tape. The templates for both cards are fairly similar, so we’ll be demonstrating with the Gingerbread House template. Each has icons to help guide you in constructing the circuit.

alt text

Line A

Take a look at the template and find the circle marked A. Peel away a few inches of the paper backing from the copper tape and stick down along the grey line.

alt text

Cut when you reach the scissors icon.

alt text

Line B

Next we’ll place tape along Line B - but wait, what’s this corner?! To keep a solid connection of copper around corners, we’ll be using a folding technique to press the tape into shape.

Start by sticking the copper tape down until you reach the corner, then fold the tape backward on itself. Use a fingernail or pen to give it a good crease at the edge.

alt text

Then carefully move the tape down around the corner - you should see the fold forming - and press down flat against the paper. The neatness of the fold doesn’t matter that much, it will be covered by your pop up in the end. Finally, cut the tape when you reach the scissors icon.

alt text

alt text

Line C

The last copper tape line will also form a battery holder. We’ll start by folding ½" of copper tape onto itself, sticking the adhesive sides together to form a flap.

alt text

This allows the top of the copper to fold down over the coin cell battery - the positive side of the battery is the top and negative side is the bottom, which allows us to create a ‘battery sandwich’ with copper tape touching each side.

alt text

See the diagrams below to explore how this method works. We won’t be installing the battery until the end of our project, so set that aside for now. Fold the card in half along the dotted center line before moving onto the next step.

alt text

alt text

Step 3: Prepare and Place LED

Now that our copper is in place, time to add the LED. Each template has an LED symbol which shows a shaped wire - we use this method to help us remember which side is positive and negative on the LED.

Here’s excerpt from our Light-emitting Diodes (LEDs) Tutorial about LED polarity:

“In electronics, polarity indicates whether a circuit component is symmetric or not. LEDs, being diodes, will only allow current to flow in one direction. And when there’s no current-flow, there’s no light. Luckily, this also means that you can’t break an LED by plugging it in backwards. Rather, it just won’t work. The positive side of the LED is called the “anode” and is marked by having a longer “lead,” or leg. The other, negative side of the LED is called the “cathode.”

alt text

Here are directions for bending a standard LED (as shown in the image above) to prepare it for our circuit.

Using pliers (or your finger) bend the longer leg of the LED flat. Then form the wire into a zig zag shape. Be careful not to break the wire by bending back and forth over the same joint too many times.

alt text

Next, bend the other leg flat and curl into a spiral. Use the end of the pliers to lightly grab the end of the wire and curl around the tool.

alt text

Once all shaping is complete, place the LED on a table or flat surface to make sure it sits flat and upright. If not, make any adjustments now.

alt text

The Christmas Tree design looks best if the LEDs are pointed at a slight angle toward the middle of the tree and each other, see picture below.

alt text

Using LED String Lights

We’ve been experimenting with cutting up LED string lights because they use tiny LEDs that are great for flat surfaces like greeting cards. Cut one LED off of the strip, making sure to leave ~½" of wire on either side. Then use a hobby knife to scrape away the coating from the wire to expose it. Make sure to scrape all around the wire, not just the top or bottom side, to ensure that you’ll have a good connection with the tape. Sandpaper will also work, if you don’t want to use a knife.

alt text

Each LED will have four wires coming from it - two positive and two negative because the LEDs are wired in parallel. It’s hard to see immediately which is which (they don’t have the handy longer/shorter trick like normal LEDs) - but we can quickly check them against a battery. Once we know which side is positive - mark the wire with a sharpie to help identify it. It’s okay to just leave the wires straight rather than shaping them like the other LED example.

alt text

If you have super eyesight - you can check for a green marking on the LED, this is the negative side.

alt text

This picture shows an LED from a string light prepped by identifying and marking the positive wire and trimming the extra wires so that they don’t accidentally short circuit each other.

Tape Down LED

Regardless of which LED type is going into the card, line up the positive lead with the copper tape marked + and the negative with -. Use clear tape over it to hold down to the copper.

alt text

Step 4: Attach Button

alt text

Next, we’ll place the LilyPad button over the oval icon on the template facing up. It doesn’t matter which side touches postive and negative. Make sure the conductive pads on the bottom of the button touch the copper tape, then tape down the ends with clear tape. Be careful not to tape directly over the push part of the button or it may interfere with the ability to press it. You can also use a LilyPad switch instead of a button - the installation is the same.

alt text

Step 5: Insert Battery

Once all the components are installed, it’s time to test our circuit by adding a battery. Carefully slip the battery underneath the copper tape flap we made earlier, and center it inside the circle icon. Make sure the positive side of the battery (top, marked with the battery model and +) is facing up. Press the copper over the battery, and tape with clear tape.

alt text

Now, press the button, and the LED should light up!

alt text

Troubleshooting

  • Check the tape connections - use your nails or a pencil to make sure the tape is firmly adhering the components to the copper tape.
  • Check the battery - make sure it is sandwiched firmly between the top and bottom copper tape lines and that the top copper is not accidentally touching the bottom of the battery.
  • Check the wires of the LED - double check that they weren’t accidentally broken while bending them into shapes with pliers.

Here are what the finished circuits should look like:

alt textalt text

Step 6: Prepare Pop Up

Time to cut out our pop up pieces. Click the links below to visit Robert Sabuda’s website for full instructions on assembling the Gingerbread and Christmas Tree pop ups.

Gingerbread House Instructions

Note: There is an additional edit to this template - use a hobby knife to cut windows in the house so that the LED can shine through. Cut out the small circle in the base template (page 3 of the pdf) to let the LED shine through before you glue the house down.

Christmas Tree Instructions

Note: To create a string of lights effect after the pop up is cut and folded, use a hole punch or small pair of scissors to cut out the small circles marked on the back of the template. For a three dimensional look, use a glue gun to adhere a small dab of glue on the back of each hole (be careful not to glue the card to your work surface). The glue will press through and create a bulb-like shape. This may take some practice to get the right amount of glue for each ‘bulb’ - we recommend trying on scrap paper first.

alt text

alt text

Window Instructions

Begin folding the window card along the center crease, be careful not to bend the frame.

alt text

Next, carefully fold the bottom of the window frame.

alt text

alt text

To fold the top creases of the window frame, press the card flat against a table.

alt text

Your final pop up will look like this:

alt text

Use a piece of parchment paper or vellum behind the frame to create a frosted look. Tape or glue on silhouette shapes to create a holiday scene.

alt text

Step 7: Assemble and Admire

When your pop ups are constructed and ready to light, carefully place them over your copper tape circuit, and cut holes, if necessary, to allow the LED to poke through the paper. Glue or tape the corners down to adhere to the backing. Gently fold down the pop up to close the card.

alt text

Finally, use a marker or stickers to indicate where the button should be pressed.

Add any extra decorations to make the card extra special. We used a white out pen to create icing on the Gingerbread House and some candy stickers.

Now, your glowing holiday greeting is ready to mail to a friend or keep for yourself!

Resources and Going Further

Things to try:

  • Try these techniques with other pop up designs or create your own - can you figure out how to adapt the copper tape path to fit your card choice?
  • Get crafty with stickers, paint, or markers after you’ve built your card to customize it even more

Further Reading:


learn.sparkfun.com |CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

mbed Starter Kit Experiment Guide

$
0
0

mbed Starter Kit Experiment Guide a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t305

Introduction

SparkFun mbed Starter Kit

Whether you have just purchased the mbed Starter Kit or you are just checking out this page to see what mbed is all about, you are in for a treat. The mbed platform is a project created by ARM to assist with rapid prototyping on microcontrollers.

Rapid prototyping? Come again?

Yes. Rapid prototyping. ARM has created a system for programming their microcontrollers with ease. This means no more fiddling with expensive and bloated development environments or fussing with confusing programming steps. mbed.org offers an online compiler that handles most of the setup and compiling steps for you.

Don’t worry about the specific steps, we will cover them in detail in the first tutorial. By following the next few tutorials, you will become an mbed kung fu master*!

*Disclaimer: Kung fu not an actual part of mbed development.

Overview

The mbed project actually contains a large variety of mbed platforms. For this kit and the following tutorials, we will be concerned with the LPC1768.

mbed LPC1768

If you have purchased the mbed Starter Kit or the LPC1768, open up the LPC1768 box, and you will find a pinout card. This card is extremely useful for finding out which pins do what on the LPC1768.

mbed LPC1768 pinout__

Features

Here are the technical specifications of the LPC1768:

  • NXP LPC1768 MCU
    • ARM® Cortex™-M3 Core
    • 96MHz
    • 32KB RAM
    • 512KB FLASH
    • Ethernet, USB Host orDevice, SPI x2, I2C x2, UART x3, CAN, PWM x6, ADC x6, GPIO
  • Platform form factor
    • 54x26mm
    • 40-pin 0.1" pitch DIP package
    • 5V USB or 4.5-9V supply
    • Built-in USB drag ‘n’ drop FLASH programmer

Suggested Reading

Table of Contents

Now for the part you have been waiting for. The tutorials! This is where you get to open your mbed kit and play with all those cool parts. You should start with Tutorial #1 in order to get familiar with mbed.org and the programming environment.

mbed blinky circuitTutorial 1 - Getting Started
We setup the mbed.org development environment and create our first program: Blinky!
mbed rgb led and buttonsTutorial 2 - Buttons and PWM
Let’s make some light! We use some buttons to control the colors of an RGB LED
mbed lcd demoTutorial 3 - Graphic LCD
The mbed kit includes a 1.44" LCD that we can make do cool things. We learn how to draw text and shapes on the LCD.
mbed accelerometer lcdTutorial 4 - Accelerometer
Now we start to pick things up. Literally. Using the accelerometer, we can interact with the mbed by tilting it in different directions.
mbed internet clockTutorial 5 - Internet Clock
The LPC1768 has the ability to connect to the Internet. Using an Ethernet cable, we can read the current time from an Internet server and display the time on our LCD.
mbed usb host keyboardTutorial 6 - USB Host and Threading
Our mbed board can act like a USB host. This means that we can connect things like keyboards to it.
mbed usb device mouseTutorial 7 - USB Device
In addition to acting like a USB host, the mbed can also act like a USB device! This means that we can have it control the mouse pointer on our computer, for example.
mbed temperature loggingTutorial 8 - Temperature Logging
Want to see how the temperature varies over time in an area? We connect a temperature sensor and an SD card to the mbed to log temperature measurements.
mbed pwm soundsTutorial 9 - PWM Sounds
Let’s make some music! We can use pulse-width modulation (PWM) to control sounds out of a speaker or set of headphones.
mbed soundboardTutorial 10 - Hardware Soundboard
In the final project, we load some sound clips onto our SD card and use the mbed to play one whenever we push a button.

Welcome to the world of mbed! In the following series of tutorials, we will show you how to configure your mbed.org account, connect some hardware, and program your mbed controller to do some cool things. Each tutorial will list the required components, but if you are just starting out with mbed, we recommend you get the mbed Starter Kit, which will provide all the necessary hardware to complete the tutorials.

In this tutorial, we will unbox the mbed LPC1768, connect it to our computer, configure our mbed.org profile, and write our first blinking LED program.

mbed basic blinky circuit

Account Setup

For this first tutorial, we will be using the LPC1768 and the USB mini-B cable. So, open your mbed NXP LPC1768 box and remove the LPC1768 controller and USB cable.

mbed LPC1768 and USB cable

Plug one end of the USB cable into the LPC1768 and the other end into your computer. The blue power LED should light up.

mbed power LED

After a few seconds, your computer should recognize the mbed controller as a standard USB drive. Open up a Windows Explorer (Windows) or Finder (OS X) and navigate to the mbed drive.

mbed.htm link

Double-click on the MBED.HTM link, which should open up a webpage that asks you to create a new mbed account.

mbed landing page

Click “Signup” and follow the prompts to create a new mbed.org account. Once you have created an account, navigate to developer.mbed.org.

mbed homepage

Click on “Login or signup” if you are not already signed in. Once signed in, click on “Compiler” in the top right. You will be presented with mbed’s online compiler.

mbed compiler

The Code

In the upper-left corner of the mbed Compiler, select “New” and then “New Program.”

mbed new program

You will see a prompt appear asking you to name your new program. Make sure that “Blinky LED Hello World” is selected for your Template and that “mbed_blinky” is set as your Program Name.

mbed blinky template

Click “OK” and you will see your new program appear in your workspace.

mbed blinky workspace

Click on “main.cpp” in the pane on the left side to open up our C++ program.

mbed blinky main

The code imports the mbed.h library, configures the pin for the LPC1768’s onboard LED to output, and blinks the LED forever. It has been copied here for reference.

language:c
#include "mbed.h"

DigitalOut myled(LED1);

int main() {
    while(1) {
        myled = 1;
        wait(0.2);
        myled = 0;
        wait(0.2);
    }
}

On the top bar, click “Compile.”

mbed compile button

This will start the compile process and download the program as a binary file. Depending on your browser settings, this might be automatically downloaded. If you are asked where to download the file, choose your default Downloads folder.

mbed blinky compile

Open up an Explorer (or Finder on OS X) window and navigate to your Downloads folder. You will see your blinky program as a .bin file.

mbed blinky download

Copy the .bin file to your MBED drive.

mbed blinky copy file

If you look in the MBED drive, you should see two files: the original MBED.HTM link and your new blinky program.

mbed blinky file copied

Without disconnecting the USB cable, press the button in the middle of the LPC1768. You should see the bottom left LED begin to flash off and on. The blinking LED shows that your code is running!

mbed blinking LED

Concepts

This is our first program with the mbed, so we should talk about what is going on.

Setup and Loop

If you have used Arduino in the past, it might come as a surprise that you were writing code in a language very close to C and C++. One thing you should be aware of is that Arduino wraps up the setup and loop stages into nice functions for you. For example, you might see this in Arduino:

language:c
void setup() {

    // Your setup code goes here

}

void loop() {

    // Your loop code goes here

}

In Arduino, the setup code runs once, and the loop code runs forever.

In mbed (and most other embedded systems), we must create our own setup and loop sections within main(). Every C and C++ program must have a main() function, as this is the entry point for the program (i.e. this is where the program begins execution when you run it).

Using our concepts of setup and loop, this is what the basic template looks like in mbed:

language:c
int main() {

    // Your setup code goes here

    while(1) {

        // Your loop code goes here

    }
}

Much like in the Arduino example, the program executes the setup code once (as soon as it enters the main() function) and executes the loop code forever. Notice that we explicitly put the loop code inside of a while loop. It is possible to make the while loop exit, and the program would stop running. You would need to reset the microcontroller to restart the program.

Header Files

The very first line in our blinky program is

language:c
#include "mbed.h"

This tells the compiler to include (i.e. copy into our program) a separate file (mbed.h in this case) when we compile. mbed.h is a header file that declares a set of functions, constants, classes, etc. for our use. Many times, the implementation of these functions, constants, classes, etc. are defined in a separate library, and the header file provides an interface. As long as we include the header file and the header file and library are in our search path (for our mbed programs, just make sure that the library is copied into our project directory - shown by the little gear icon in this example), we can use the functions, constants, classes, etc. listed in the header file.

mbed project directory

Going Further

This is just the beginning! You got a taste of the mbed Compiler and built your first program. Now that you understand how to use the mbed Compiler, we will move on to more advanced topics and show you how to connect other pieces of hardware to make the LPC1768 do fun and interesting things.

Beyond the Tutorial

  • Can you make the LED blink slower?
  • Can you make another LED blink?
  • Can you make an LED blink exactly 10 times and then stop? (Hint: the while(1) loop continues forever. How would you modify that to stop after 10 times?)

Digging Deeper

  • Read about mbed’s SDK
  • Read about mbed’s HDK
  • Read about mbed’s Compiler
  • Read about mbed’s website
  • Take a look at mbed’s Handbook, which has official mbed libraries
  • Take a look at mbed’s Cookbook, which has user-submitted libraries and projects

Experiment 2: Buttons and PWM

Now that you have had a chance to set up your mbed account and blink an LED, we will move on to simple human interaction: pushbuttons! In this tutorial, we add 3 pushbuttons to the LPC1768 and use them to control the colors in an RGB LED.

mbed pwm rgb circuit

The Circuit

This circuit can be made with parts in the SparkFun mbed Starter Kit. Also, keep in mind that the LPC1768 box contains a USB mini-B cable for programming and power.

Parts List

Schematic

mbed Buttons and RGB LED schematic

Click on schematic to view larger image.

Connections

Connect the LPC1768 to the buttons and LED in the following fashion.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction. Polarized components are highlighted with a yellow warning triangle in the table below.

Fritzing Diagram

mbed buttons rgb led fritzing

Be careful with the direction of the LED (polarity matters!). In the diagram, the flat edge (see the Tips section below) is facing to the left.

Note that the colors of the wires do not matter. Feel free to use any color you like! Do not worry if your kit does not have 5 black wires.

Hookup Table

Place the LPC1768 in the first breadboard with pin VOUT in position i1 and pin 20 in position b20.

Connect the rest of the components as follows:

ComponentBreadboard 1Breadboard 2
b25 (RED)b26 (GND)b27 (GREEN)b28 (BLUE)
330 Resistore25g25
330 Resistore27g27
330 Resistore28g28
Pushbuttond6d8g6g8
Pushbuttond14d16g14g16
Pushbuttond22d24g22g24
10K Resistori6( + )
10K Resistori14( + )
10K Resistori22( + )
Jumper Wirej1( + )
Jumper Wirea1( - )
Jumper Wirea5h6
Jumper Wirea6h14
Jumper Wirea7h22
Jumper Wirej20j25
Jumper Wirej19j27
Jumper Wirej18j28
Jumper Wirea26( - )
Jumper Wirea8( - )
Jumper Wirea16( - )
Jumper Wirea24( - )

Tips

Pushbuttons

The leads across each other on the pushbuttons are always connected to each other. The leads on the same side are only connected when button is pressed.

push button diagram

LED

You can use a set of needle nose pliers to bend the LED’s leads and a pair of cutters to fit the LED in the breadboard. Note that there is a flat side on the plastic ring around the bottom of the LED. This denotes the side with the pin that controls the red color. See this tutorial to learn more about polarity.

RGB LED common cathode annotated

Resistors

330 ohm resistors are given by the color code “orange orange brown.”

330 ohm resistors

330 ohm resistors

10K ohm resistors are given by the color code “brown black orange.”

10K ohm resistors

10K ohm resistors

The Code

If you have not done so already, sign into your mbed.org account. Go to the Compiler and create a new program. Leave the template as “Blinky LED Hello World” and give it a name such as “rgb_buttons.” Click OK and wait for your new program to be created.

Once that is done, click “main.cpp” under your project folder (e.g. “rgb_buttons”) in the left “Program Workspace” pane. Delete all of the code in main.cpp so you are left with a blank project (we still want to use the “Blinky LED Hello World” template, as it automatically links “mbed.h” for us).

blank mbed project

Program

Copy the following code into main.cpp of your rgb_buttons project.

language:c
#include "mbed.h"

// Define buttons
InterruptIn button_red(p5);
InterruptIn button_green(p6);
InterruptIn button_blue(p7);

// Define LED colors
PwmOut led_red(p21);
PwmOut led_green(p22);
PwmOut led_blue(p23);

// Interrupt Service Routine to increment the red color
void inc_red() {

    float pwm;

    // Read in current PWM value and increment it
    pwm = led_red.read();
    pwm += 0.1f;
    if (pwm > 1.0f) {
        pwm = 0.0f;
    }
    led_red.write(pwm);
}

// Interrupt Service Routine to increment the green color
void inc_green() {

    float pwm;

    // Read in current PWM value and increment it
    pwm = led_green.read();
    pwm += 0.1f;
    if (pwm > 1.0f) {
        pwm = 0.0f;
    }
    led_green.write(pwm);
}

// Interrupt Service Routine to increment the blue color
void inc_blue() {

    float pwm;

    // Read in current PWM value and increment it
    pwm = led_blue.read();
    pwm += 0.1f;
    if (pwm > 1.0f) {
        pwm = 0.0f;
    }
    led_blue.write(pwm);
}

// Main loop
int main() {

    // Initialize all LED colors as off
    led_red.write(0.0f);
    led_green.write(0.0f);
    led_blue.write(0.0f);

    // Define three interrupts - one for each color
    button_red.fall(&inc_red);
    button_green.fall(&inc_green);
    button_blue.fall(&inc_blue);

    // Do nothing! We wait for an interrupt to happen
    while(1) {
    }
}

Run

Click the “Compile” button to download a binary file with your compiled program. Copy that file to the LPC1768. You can choose to delete the previous mbed_blinky_LPC1768.bin or just leave it there. If you have more than one .bin file on the mbed when you press the restart button, the mbed will choose the newest file to load and run.

Press the LPC1768’s restart button. You should be able to press any of the 3 buttons on your breadboard to increment the red, green, and blue intensity of the LED. Note that when you reach the maximum brightness, the intensity resets to 0.

mbed running rgb led pwm

Concepts

What is going on in our program? We should understand a few concepts about our seemingly simple RGB LED and button program that are crucial in embedded systems.

Pull-up Resistors

We use 10kΩ pull-up resistors to prevent shorting 3.3V to ground whenever we push one of the buttons. Additionally, the pull-up resistors on the microcontroller (LPC1768) pin holds the pin at 3.3V by default until the button is pushed. Once pushed, the line is pulled down to ground, so the pin goes from 3.3V to ground. We can use that falling edge (3.3V to 0V) to trigger an interrupt within the microcontroller. To learn more about pull-up resistors, see our tutorial here.

Functions

If you are not familiar with C syntax, you might want to brush up on some of the basics.

In the above code, we created 3 functions: inc_red(), inc_green(), inc_blue(). Functions generally perform some action when called, and replace the much-maligned GOTO statement. They also allow us to re-use code without having to copy-and-paste sections of code over and over again.

Each time we call one of the functions (e.g. inc_green()), the lines of code within that function are called, and then the function exits, returning program execution to just after the function call.

Notice that we placed the three functions above main(). When the compiler looks at the code, it needs to have functions declared before they are used in the code (within main() in this case).

If you put main() before the functions, you would get a compiler error. That’s because the compiler does not know what int_red(), etc. are when it sees them in main(). Try it!

Objects

We are using C++ to write all of our programs. If you have never used C++ before, the syntax might appear a bit foreign. We recommend reading about some basic C++ syntax first.

In the program, we create objects for each of our buttons and LEDs. For example:

language:c
InterruptIn button_red(p5);

and

language:c
PwmOut led_red(p21);

button_red is an instance of class InterruptIn. Think of a class as a “blueprint” that lets us create any number of instances (i.e. objects). Each instance is tied to a variable (e.g. button_red). In this case, button_red is an InterruptIn object.

Objects have special properties that let us call functions within that object (called “member functions”) and manipulate data stored in the object (data in objects is stored as “data members”). For example, we create a PwmOut object named led_red. Later in the code, we call the member function led_red.write(0.0f), which tells the led_red object to perform some action (change the PWM of the associated pin in this case - see PWM below!).

We pass in the parameter p5 (a special variable known to the mbed compiler - it points to the location of pin 5 in software) when we create an InterruptIn object. This tells the mbed which pin to bind the interrupt to.

Now that we have created an InterruptIn object, we can call member fucntions within that object. The InterruptIn class defines a fall() member function, which allows us to set a function to be called whenever a HIGH-to-LOW transition occurs on the pin (pin 5 in this case).

language:c
button_red.fall(&inc_red);

Note that the ‘&’ symbol is used to indicate the address of the inc_red function.

Interrupts

Interrupts are an integral part of embedded systems and microcontrollers. Most programs that you might be used to run sequentially, meaning that the program executes each line in order (and jumps or loops where necessary). In contrast, many microcontrollers rely on subroutines known as “Interrupt Service Routines” to handle external and internal events.

In our mbed program, we “attach” an interrupt to our button pins and tie this interrupt to a function call (e.g. inc_red()). The line

button_red.fall(&inc_red);

says that whenever we see a falling digital signal (i.e. from 3.3V to 0V), we must stop whatever we were doing and execute the function inc_red(). This is similar to callbacks often found in programming but can be tied to external (i.e. outside the microcontroller) events.

YouTube user Patrick Hood-Daniel offers a great explanation of interrupts and some example code in a different microcontroller (Atmel AVR ATmega32):

PWM

To control the brightness of the LEDs, we do not vary the current going into the LED. Rather, we rapidly turn the LED off and on to give the appearance of a dimmer LED. This is known as “Pulse-Width Modulation” (PWM). Note that we are flipping the LED off and on so fast that generally our eyes cannot see the flickering.

We adjust the “duty cycle” of this flipping process in order to control the brightness. Duty cycle just refers to how long our LED stays on in relation to how long it stays off.

duty cycle example

The higher the duty cycle (e.g. 75% in the image above), the brighter the LED will appear to be. At lower duty cycles (e.g. 25%) the LED will hardly appear to be on. For a full tutorial on PWM, see Pulse-width Modulation.

In our rgb_buttons program, we use mbed’s built-in PwmOut object to control PWM on several of the LPC1768 pins. We can read the PWM value with the .read() method and set a new PWM value with .write(). We use a floating point number to specify the duty cycle. This can be between 0.0 (0% duty cycle) to 1.0 (100% duty cycle).

Going Further

We’ve covered three important concepts in this tutorial: user input with buttons (using pull-up resistors), interrupts, and PWM. If these topics provide some confusion, feel free to read through the “Digging Deeper” section to learn more about these topics in greater detail.

Beyond the Tutorial

  • See how the LED changes when you press a button down? Can you make it so that the LED changes when you release a button?
  • Since we are using interrupts, our while(1){} loop is empty. Make something happen while waiting for a button push! For example, flash another LED in that while loop.
  • Can you re-create the functionality of the program without using any interrupts?
  • You might notice that the LED changes accidentally sometimes when you release a button. This is caused by a phenomenon known as contact bounce. Can you create a way to remove contact bounce (known as “debouncing”)? This can be done in hardware or software.

Digging Deeper

Experiment 3: Graphic LCD

Let’s make some graphics! In this tutorial, we walk you through connecting your Serial Miniature Graphic LCD to the mbed LPC1768 and making some shapes and text. This tutorial is important as we will use the LCD in the next few tutorials, so pay close attention!

mbed LCD demo circuit

Suggested Reading

The Circuit

This circuit can be made with parts in the SparkFun mbed Starter Kit. Also, keep in mind that the LPC1768 box contains a USB mini-B cable for programming and power.

Parts List

Schematic

mBed 4D graphic LCD schematic

Click on schematic to view larger image.

Connections

Before connecting the LCD to your breadboard, we recommend you carefully bend the 3.3V pin on the LCD back so that it does not short to the RESET pin. This can be accomplished with a set of needle nose pliers. You will likely never need 3.3V from the LCD, as you can get 3.3V from the VOUT pin on the LPC1768. The other pins in the second row can be shorted to pins in the first row and not affect the LCD’s operation.

alt text

Plug the LCD into your breadboard and connect it to the LPC1768 as shown.

Fritzing Diagram

mbed 4d lcd fritzing

Hookup Table

Place the LPC1768 in a breadboard with pin VOUT in position i1 and pin 20 in position b20.

Connect the rest of the components as follows:

ComponentBreadboard
uLCD-144-G2*h26 (RES)h27 (GND)h28 (RX)h29 (TX)h30 (+5V)
Jumper Wirej2f30
Jumper Wirea1( - )
Jumper Wirea9f28
Jumper Wirea10f29
Jumper Wirea11f26
Jumper Wire( - )f27

* Pins not listed are not used.


The Code

For this tutorial, we will be using an mbed library. Libraries can be found under the Handbook for official, mbed-supported libraries or the Cookbook for user-created mbed libraries.

Libraries

mbed.org user Jim Hamblen modified a 4D LCD library to work with our uLCD-144-G2. We copied (also known as “forked”) his library for use in this tutorial.

Go to mbed.org and sign in to your account.

Navigate to the mbed 4DGL-uLCD-SE library page.

mbed 4D ulcd library

Click “Import this library” on the right side of the page. You will be brought to the mbed Compiler and asked to import the library. Fill in a program name (e.g. “ulcd_demo”) for “New Program” and click “Import.”

mbed import 4D ulcd library

Since the import process imported only the 4DGL-uLCD-SE library, we need to add the mbed library.

In the Compiler, right-click on the “ulcd_demo” project, highlight “Import Library…” and select “From Import Wizard…”

import mbed library

That will bring you to the Import Wizard page. In the “Search criteria…” on the right type in “mbed” and click the “Search” button (Note: the mbed library is likely already listed, but it is good practice to know how to search for libraries).

search mbed libraries

The mbed library should be the first listing.

mbed library listing

Double-click the entry (highlighted in the picture) to import the library. This will automatically load the library into your “ulcd_demo” project.

mbed import library

Program

With our libraries loaded, we can create our LCD program. Create a new file in our project by right-clicking on the “ulcd_demo” project in the left pane and selecting “New File…”

select new file in mbed

You will be prompted to name your new file. Call it “main.cpp” and click the “OK” button.

giving a name to the new file in mbed

The Compiler will automatically open the new main.cpp in the workspace.

mbed main workspace

Enter the following code so that we can test out our 4D serial LCD.

language:c
// Demo for the uLCD-144-G2 based on the work by Jim Hamblen

#include "mbed.h"
#include "uLCD_4DGL.h"

// TX, RX, and RES pins
uLCD_4DGL uLCD(p9,p10,p11);

int main() {

    int x;
    int y;
    int radius;
    int vx;

    // Set our UART baudrate to something reasonable
    uLCD.baudrate(115200);

    // Change background color (must be called before cls)
    uLCD.background_color(WHITE);

    // Clear screen with background color
    uLCD.cls();

    // Change background color of text
    uLCD.textbackground_color(WHITE);

    // Make some colorful text
    uLCD.locate(4, 1);      // Move cursor
    uLCD.color(BLUE);
    uLCD.printf("This is a\n");
    uLCD.locate(5, 3);      // Move cursor
    uLCD.text_width(2);     // 2x normal size
    uLCD.text_height(2);    // 2x normal size
    uLCD.color(RED);        // Change text color
    uLCD.printf("TEST");
    uLCD.text_width(1);     // Normal size
    uLCD.text_height(1);    // Normal size
    uLCD.locate(3, 6);      // Move cursor
    uLCD.color(BLACK);      // Change text color
    uLCD.printf("of my new LCD");

    // Initial parameters for the circle
    x = 50;
    y = 100;
    radius = 4;
    vx = 1;

    // Make a ball bounce back and forth
    while (1) {

        // Draw a dark green
        uLCD.filled_circle(x, y, radius, 0x008000);

        // Bounce off the edges
        if ((x <= radius + 1) || (x >= 126 - radius)) {
            vx = -1 * vx;
        }

        // Wait before erasing old circle
        wait(0.02);         // In seconds

        // Erase old circle
        uLCD.filled_circle(x, y, radius, WHITE);

        // Move circle
        x = x + vx;
    }
}

Run

Compile the program and copy the downloaded file to the mbed. Press the mbed’s restart button to see the LCD come to life with your program!

mbed LCD demo running

Concepts

We touched on a few important concepts in this tutorial that you may want to understand.

Serial Communications

To communicate between the mbed and the LCD, we are relying on a protocol known as UART. While you can create a program that emulates UART, it is far easier to rely on the mbed’s built-in UART hardware peripherals. We are using pin 9 and pin 10, which are the TX and RX lines, respectively, of one of the LPC1768’s UART peripherals. To read more about UART and serial communications, see this tutorial.

Libraries

Many software programs rely on “libraries.” A library is a separate program or programs that may be called upon to perform one or several functions. We interface with libraries by linking to them in our project (the “Import” step in the mbed Compiler) and using the “#include” command in our main program. This tells the compiler to include the header file (“.h”), which makes functions in the library available to us (e.g. the uLCD_4DGL class and methods, such as background_color()). Many mbed libraries can be found in the Handbook and the Cookbook.

For this guide, we are using forked tutorials so that the versions stay the same. When you start making projects on your own, we highly recommend using libraries from the original author (or write your own!). As you start developing projects using other people’s libraries, you’ll notice that they might update their library from time to time. If you see a little green circular arrow around the library icon in your project, that means the library has been updated. To update the library to the latest revision, right-click on the library in your project viewer and select “Update…”

update library in mbed compiler

The Super Loop

Many simple embedded systems use the concept of “setup” and “loop” (more powerful embedded systems often use a Real-Time Operating System). For these tutorials, we rely on setting up some parameters and then looping forever within a while loop. This type of structure is known as a super loop architecture.

For mbed, the super loop architecture looks like:

language:c
int main() {

    // Setup code goes here

    while (1) {

        // Loop forever code goes here

    }
}

We can declare functions outside of main, which can be called within either our setup or loop code. Additionally, we can declare variables outside of main (and other functions), which are known as “global variables”.

This super loop template is a great starting place for many simple embedded programs.

Graphics

The realm of computer graphics is vast. We only touched on the beginning with simple text and shapes. Even if we do not go in-depth into graphics, we recommend you familiarize yourself with some graphics terms such as framebuffer, frame rate, and refresh rate.

Going Further

Now that you have learned about libraries and graphical displays, you are well on your way to becoming an mbed expert. We will be using the LCD in the coming tutorials, so don’t disconnect it yet!

Beyond the Tutorial

  • Can you make the circle bounce up and down as well as side to side?
  • Can you make the circle grow and shrink in size?
  • Can you make the circle speed up and slow down?
  • Can you make the text move around the screen?
  • Can you make a scrolling text marquee? (Hint: Look at how we create text and how we move objects around the screen)
  • Can you draw a rectangle instead of a circle? (Hint: see Jim Hamblen’s Demo Code)

Digging Deeper

Experiment 4: Accelerometer

Using the graphic LCD from the previous tutorial, we will connect a sensor to add an interactive component to our project. We can use an MMA8452Q 3-axis accelerometer to move a ball around the screen for a cool demo.

mbed LCD accelerometer circuit

Suggested Reading

The Circuit

This circuit can be made with parts in the SparkFun mbed Starter Kit. Also, keep in mind that the LPC1768 box contains a USB mini-B cable for programming and power.

Parts List

Schematic

mbed 4D graphic LCD and accelerometer schematic

Click on schematic to view larger image.

Connections

Connect the LPC1768 to the LCD and accelerometer in the following fashion. Note that the LCD uses the same connections as in Part 3.

Fritzing Diagram

mbed 4d lcd accelerometer fritzing

Hookup Table

Place the LPC1768 in a breadboard with pin VOUT in position i1 and pin 20 in position b20.

Connect the rest of the components as follows:

ComponentBreadboard
uLCD-144-G2*h26 (RES)h27 (GND)h28 (RX)h29 (TX)h30 (+5V)
MMA8452*b25 (GND)b28 (SCL)b29 (SDA)b30 (3.3V)
Jumper Wirej2f30
Jumper Wirea1( - )
Jumper Wirea9f28
Jumper Wirea10f29
Jumper Wirea11f26
Jumper Wire( - )f27
Jumper Wire( - )d25
Jumper Wirej14d28
Jumper Wirej13d29
Jumper Wirej1d30

* Pins not listed are not used.


The Code

We will be building on the previous tutorial. In addition to importing an mbed library from the Cookbook for the LCD, we will be building our own library for the MMA8452Q accelerometer.

Libraries

Navigate to the developer.mbed.org, login, and navigate to your Compiler.

Right-click on “My Programs” and create a new program.

mbed new program

Give your program an appropriate name (such as “ulcd_accel”), keep the Template as “Blinky LED Hello World,” and click OK.

mbed new program template

Navigate to the 4DGL-uLCD-SE library page.

mbed 4DGL-uLCD-SE library page

Click “Import this library” on the right side of the page. You will be brought to the mbed Compiler and asked to import the library. For “Target Path,” select our “ulcd_accel” project and click “Import.”

importing a library into our project

The library should now appear under our project in the Program Workspace.

library in our project

Now, we get to create our own library! Right-click on the program in the left pane and select “New Library…”

create a new library

Name your library “MMA8452Q” and click OK.

name our new library

Right-click on the newly created library and select “New File…”

creating a new file

Name your new file “MMA8452Q.h” and click OK.

naming a new file

Repeat the same file creation process to make another file: “MMA8452Q.cpp”. Your project folder should contain a main.cpp, the mbed library, the 4DGL-uLCD-SE library, and our newly created MMA8452Q library (with our blank .h and .cpp files).

mbed ulcd_accel project directory

Click on the “MMA8452Q.h” file to open up the blank header (.h) file. Copy the following code into the file.

language:c
// Library for our MMA8452Q 3-axis accelerometer
// Based on the MMA8452Q Arduino Library by Jim Lindblom (SparkFun Electronics)

#ifndef MMA8452Q_H
#define MMA8452Q_H

#include "mbed.h"

// Register definitions
#define REG_STATUS          0x00
#define OUT_X_MSB           0x01
#define OUT_X_LSB           0x02
#define OUT_Y_MSB           0x03
#define OUT_Y_LSB           0x04
#define OUT_Z_MSB           0x05
#define OUT_Z_LSB           0x06
#define REG_WHO_AM_I        0x0D
#define REG_XYZ_DATA_CFG    0x0E
#define REG_CTRL_REG1       0x2A

// WHO_AM_I check
#define FACTORY_ID          0x2A

// Scale definitions
#define SCALE_2G            2
#define SCALE_4G            4
#define SCALE_8G            8

// Data rates
#define ODR_800HZ           0
#define ODR_400HZ           1
#define ODR_200HZ           2
#define ODR_100HZ           3
#define ODR_50HZ            4
#define ODR_12_5HZ          5
#define ODR_6_25HZ          6
#define ODR_1_56HZ          7

// Init values
#define DEFAULT_FSR         SCALE_2G
#define DEFAULT_ODR         ODR_800HZ


// Class declaration
class MMA8452Q
{
    public:
        MMA8452Q(PinName sda, PinName scl, int addr);
        ~MMA8452Q();
        bool init();
        uint8_t available();
        void setScale(uint8_t fsr);
        void setODR(uint8_t odr);
        void standby();
        void active();
        float readX();
        float readY();
        float readZ();
        uint8_t readRegister(uint8_t reg);
        void writeRegister(uint8_t reg, uint8_t data);

    private:
        I2C m_i2c;
        int m_addr;
        int scale;
};

#endif

Click “Save”. Note that since we are not compiling our library files right away, we want to save them so we can work on other files. That way, if we lose power or accidentally close our browser, we won’t lose our work (don’t worry, our library files will get compiled later). Save often!

Click on “MMA8452Q.cpp” to open the blank program (.cpp) file. Copy the following code into the file.

language:c
// Library for our MMA8452Q 3-axis accelerometer
// Based on the MMA8452Q Arduino Library by Jim Lindblom (SparkFun Electronics)

#include "mbed.h"
#include "MMA8452Q.h"

// Constructor
MMA8452Q::MMA8452Q(PinName sda, PinName scl, int addr) : m_i2c(sda, scl), m_addr(addr)
{
    // Initialize members
    scale = DEFAULT_FSR;
}

// Destructor
MMA8452Q::~MMA8452Q()
{

}

// Initialization
bool MMA8452Q::init()
{
    // Check to make sure the chip's ID matches the factory ID
    uint8_t c = readRegister(REG_WHO_AM_I);
    if( c != FACTORY_ID ) {
        return false;
    }

    // Set default scale and data rate
    standby();
    setScale(DEFAULT_FSR);
    setODR(DEFAULT_ODR);
    active();

    return true;
}

// Set the full-scale range for x, y, and z data
void MMA8452Q::setScale(uint8_t fsr)
{
    uint8_t config = readRegister(REG_XYZ_DATA_CFG);
    scale = fsr;
    config &= 0xFC;                     // Mask out FSR bits
    fsr = fsr >> 2;                     // Trick to translate scale to FSR bits
    fsr &= 0x03;                        // Mask out acceptable FSRs
    config |= fsr;                      // Write FSR bits to config byte
    writeRegister(REG_XYZ_DATA_CFG, config);              // Write config back to register
}

// Set the Output Data Rate
void MMA8452Q::setODR(uint8_t odr)
{
    uint8_t ctrl = readRegister(REG_CTRL_REG1);
    ctrl &= 0xCF;                       // Mask out data rate bits
    odr &= 0x07;                        // Mask out acceptable ODRs
    ctrl |= (odr << 3);                 // Write ODR bits to control byte
    writeRegister(REG_CTRL_REG1, ctrl); // Write control back to register
}

// Set accelerometer into standby mode
void MMA8452Q::standby()
{
    uint8_t c = readRegister(REG_CTRL_REG1);
    c &= ~(0x01);                       // Clear bit 0 to go into standby
    writeRegister(REG_CTRL_REG1, c);    // Write back to CONTROL register
}

// Set accelerometer into active mode
void MMA8452Q::active()
{
    uint8_t c = readRegister(REG_CTRL_REG1);
    c |= 0x01;                          // Set bit 0 to go into active mode
    writeRegister(REG_CTRL_REG1, c);    // Write back to CONTROL register
}

// Read X registers
float MMA8452Q::readX()
{
    int16_t x = 0;
    float cx = 0;

    // Read MSB and LSB from X registers
    x = readRegister(OUT_X_MSB);
    x = x << 8;
    x |= readRegister(OUT_X_LSB);
    x = x >> 4;

    // Calculate human readable X
    cx = (float)x / (float)2048 * (float)(scale);

    return cx;
}

// Read Y registers
float MMA8452Q::readY()
{
    int16_t y = 0;
    float cy = 0;

    // Read MSB and LSB from Y registers
    y = readRegister(OUT_Y_MSB);
    y = y << 8;
    y |= readRegister(OUT_Y_LSB);
    y = y >> 4;

    // Calculate human readable Y
    cy = (float)y / (float)2048 * (float)(scale);

    return cy;
}

// Read Z registers
float MMA8452Q::readZ()
{
    int16_t z = 0;
    float cz = 0;

    // Read MSB and LSB from Z registers
    z = readRegister(OUT_Z_MSB);
    z = z << 8;
    z |= readRegister(OUT_Z_LSB);
    z = z >> 4;

    // Calculate human readable Z
    cz = (float)z / (float)2048 * (float)(scale);

    return cz;
}

// Raw read register over I2C
uint8_t MMA8452Q::readRegister(uint8_t reg)
{
    uint8_t dev_addr;
    uint8_t data;

    // I2C address are bits [6..1] in the transmitted byte, so we shift by 1
    dev_addr = m_addr << 1;

    // Write device address with a trailing 'write' bit
    m_i2c.start();
    m_i2c.write(dev_addr & 0xFE);

    // Write register address
    m_i2c.write(reg);

    // Write a start bit and device address with a trailing 'read' bit
    m_i2c.start();
    m_i2c.write(dev_addr | 0x01);

    // Read single byte from I2C device
    data = m_i2c.read(0);
    m_i2c.stop();

    return data;
}

// Raw write data to a register over I2C
void MMA8452Q::writeRegister(uint8_t reg, uint8_t data)
{
    uint8_t dev_addr;

    // I2C address are bits [6..1] in the transmitted byte, so we shift by 1
    dev_addr = m_addr << 1;

    // Write device address with a trailing 'write' bit
    m_i2c.start();
    m_i2c.write(dev_addr & 0xFE);

    // Write register address
    m_i2c.write(reg);

    // Write the data to the register
    m_i2c.write(data);
    m_i2c.stop();
}

Click “Save”.

And that’s it! We just created our very first library in mbed. Because the library is contained within our project, everything is automatically linked at compile time. We just need to write #include “MMA8452Q.h” in our main program to use the MMA8452Q accerlerometer functions.

Program

Click on “main.cpp” under our “ulcd-accel” project to open up our main program file. Because we selected the “Blinky” template, there will be some code in the file already. Go ahead and delete everything in “main.cpp”. Copy and paste in the following code.

language:c
// Demo for the uLCD-144-G2 and MMA8452Q 3-axis accelerometer

#include "mbed.h"
#include "MMA8452Q.h"
#include "uLCD_4DGL.h"

// Graphic LCD - TX, RX, and RES pins
uLCD_4DGL uLCD(p9,p10,p11);

// Accelerometer - SDA, SCL, and I2C address
MMA8452Q accel(p28, p27, 0x1D);

int main() {

    // Initialize uLCD
    uLCD.baudrate(115200);
    uLCD.background_color(BLACK);
    uLCD.cls();

    // Initialize accelerometer
    accel.init();

    // Initial parameters for the circle
    float x = 64;
    float y = 64;
    int radius = 4;
    int speed = 4;

    // Make a ball "fall" in direction of accelerometer
    while (1) {

        // Draw a red circle
        uLCD.filled_circle((int)x, (int)y, radius, RED);

        // Wait before erasing old circle
        wait(0.02);         // In seconds

        // Erase old circle
        uLCD.filled_circle((int)x, (int)y, radius, BLACK);

        // Move circle. IMPORTANT! Notice how we adjust for sensor orientation!
        x -= (speed * accel.readY());
        y -= (speed * accel.readX());

        // Make circle sit on edges
        if ( x <= radius + 1 ) {
            x = radius + 1;
        } else if ( x >= 126 - radius ) {
            x = 126 - radius;
        }
        if ( y <= radius + 1 ) {
            y = radius + 1;
        } else if ( y >= 126 - radius ) {
            y = 126 - radius;
        }
    }
}

Run

Compile the program and copy the downloaded file to the mbed. Press the mbed’s restart button to see the LCD display a little red ball. Pick up the breadboard and tilt it in different directions. You should see the ball start to move around!

mbed running LCD accelerometer demo

Concepts

We touched on a few important concepts in this tutorial that you may want to understand.

I2C

I2C (or “Inter-Integrated Circuit”) is a communications protocol built by Philips in the 1980s. As I2C is a bus protocol, it allows for multiple masters and multiple devices to reside on the same bus and relies on addresses to communicate to specific devices. In our example, we used mbed’s I2C library to talk to the accelerometer. To read more about the history of I2C, see this Wikipedia article.

Libraries

In the last tutorial, we imported an existing library. In this tutorial, we created a new library to make accessing the accelerometer easier. If you feel that you have a solid, well documented library that you want to share with others, read through mbed’s Collaboration guide and specifically, how to write and publish a library.

Header Files

When we made our library, we created two files: a .h file and a .cpp file. The .h file is known as a header file. The header file contains declarations (variables, functions, classes, etc.) for other files in the program to use.

In our main file (main.cpp), we include all of the declarations from the header file (MMA8452Q.h) with the statement

language:c
#include "MMA8452Q.h"

This, in effect, copies everything from the header file to the #include line.

You will also notice that we included the same header file in the MMA8452Q.cpp file. We declare all of our classes, functions, and variables in the header file and define them in the .cpp file (read about the difference between declare and define).

When we compile our program, the compiler sees that we have declared the MMA8452Q class in the included header file, so we can use it in our main program. It will also compile the MMA8452Q.cpp file into an object file.

During the linking phase, the object files are combined into a single executable that is downloaded to your computer as a .bin file.

Floating Point

If you are carefully reviewing the example code, you might have noticed the keyword “float.” If you have never dealt with floating point numbers, you might want to read up on how they work. Kip Irvine provides a great floating point tutorial. If you are interested in the history of floating point, see this Wikipedia article.

Going Further

We made an accelerometer do some cool stuff on a graphical display. If you are following the tutorials in order, you will need the LCD for one more!

Beyond the Tutorial

  • Can you make a digital bubble level? (Hint: think about how a bubble works and adjust how we move the circle)
  • Can you make the ball bounce off the sides? (Hint: look at how we make the ball “sit on edges” and make it bounce instead)
  • Can you make a basic ball-in-a-maze game? (Hint: look at how we draw shapes with the LCD library and how to make the ball sit on edges)

Digging Deeper

Experiment 5: Internet Clock

With the graphic LCD still connected, we hook up an Ethernet jack to our mbed to get it on the Internet. We will use the Network Time Protocol (NTP) to fetch the current time (in UTC/GMT) and display it on the LCD.

IMPORTANT: You will need access to an Internet-connected router with an open Ethernet port for this tutorial.

mbed Internet clock circuit

Suggested Reading

The Circuit

This circuit can be made with parts in the SparkFun mbed Starter Kit. Also, keep in mind that the LPC1768 box contains a USB mini-B cable for programming and power.

Parts List

Schematic

mbed Internet Clock schematic

Click on schematic to view larger image.

Connections

Connect the LPC1768 to the LCD and Ethernet jack in the following fashion. Note that the LCD uses the same connections as in Part 3.

Fritzing Diagram

mbed Internet Clock Fritzing

Hookup Table

Place the LPC1768 in the first breadboard with pin VOUT in position i1 and pin 20 in position b20.

Connect the rest of the components as follows:

ComponentBreadboard 1Breadboard 2
uLCD-144-G2*h26 (RES)h27 (GND)h28 (RX)h29 (TX)h30 (+5V)
RJ45 MagJack Breakout*c9 (P1)c10 (P2)c15 (P7)c16 (P8)
Jumper Wirej2f30
Jumper Wirea1( - )
Jumper Wirea9f28
Jumper Wirea10f29
Jumper Wirea11f26
Jumper Wire( - )f27
Jumper Wirej5e16
Jumper Wirej6e15
Jumper Wirej7e9
Jumper Wirej8e10

* Pins not listed are not used.


The Code

We will be relying heavily on pre-built libraries for this project. We need the same LCD library from the previous two tutorials as well as mbed’s Ethernet and NTP libraries.

Libraries

Navigate to the mbed.org, login, and navigate to your Compiler.

Create a new program with the “Blinky LED Hello World” template. Name it something like “internet_clock.”

Navigate to the following pages and import each library into your “internet_clock” program.

The mbed library should already be imported if you used the “Blinky” template.

mbed Internet Clock libraries

Program

Click on “main.cpp” in your project, remove the template code, and copy in the following code.

language:c
// Internet Clock with LCD based on the work by Jim Hamblen and Tyler Lisowski

#include "mbed.h"
#include "EthernetInterface.h"
#include "NTPClient.h"
#include "uLCD_4DGL.h"

// Parameters
char* domain_name = "0.uk.pool.ntp.org";
int port_number = 123;

// Networking
EthernetInterface eth;
NTPClient ntp_client;

// Graphic LCD - TX, RX, and RES pins
uLCD_4DGL uLCD(p9,p10,p11);

int main() {

    time_t ct_time;
    char time_buffer[80];

    // Initialize LCD
    uLCD.baudrate(115200);
    uLCD.background_color(BLACK);
    uLCD.cls();

    // Connect to network and wait for DHCP
    uLCD.locate(0,0);
    uLCD.printf("Getting IP Address\n");
    eth.init();
    if ( eth.connect() == -1 ) {
        uLCD.printf("ERROR: Could not\nget IP address");
        return -1;
    }
    uLCD.printf("IP address is \n%s\n\n",eth.getIPAddress());
    wait(1);

    // Read time from server
    uLCD.printf("Reading time...\n\r");
    ntp_client.setTime(domain_name, port_number);
    uLCD.printf("Time set\n");
    wait(2);
    eth.disconnect();

    // Reset LCD
    uLCD.background_color(WHITE);
    uLCD.textbackground_color(WHITE);
    uLCD.color(RED);
    uLCD.cls();
    uLCD.text_height(2);

    // Loop and update clock
    while (1) {
        uLCD.locate(0, 1);
        ct_time = time(NULL);
        strftime(time_buffer, 80, "    %a %b %d\n    %T %p %z\n    %Z\n", \
                                                localtime(&ct_time));
        uLCD.printf("    UTC/GMT:\n%s", time_buffer);
        wait(0.1);
    }
}

Run

Compile the program and copy the downloaded file to the mbed. Connect the Ethernet cable from an Internet-connected router/switch/hub to your project’s MagJack breakout. Press the mbed’s restart button, and you should see the LCD come to life with connection details. After a few seconds, the LCD should change to show the current time (in UTC/GMT format).

mbed running Internet clock demo

Concepts

Connecting something to the Internet opens up a whole new world. There is a lot going on to communicate to a remote server, so we recommend looking into a few concepts to familiarize yourself with how the Internet works.

OSI Model

Ethernet is just one small component in making devices talk over the Internet. Many protocols make up Internet communications and can be thought of like an onion. Each protocol layer corresponds to a layer within the onion, with your custom message (in this case, a request for time using NTP) in the middle. Several other layers are stacked on top of your message in order to make the communications through the Internet work. If you would like to understand how these protocols work, start with the 7-layer Open Systems Interconnection (OSI) model.

TCP and UDP

TCP and UDP are the two most important Transport Layer protocols. Transmission Control Protocol (TCP) is mostly used by services that require a guaranteed delivery, such as websites and email. On the other hand, we were using the User Datagram Protocol (UDP) to send and receive time information with NTP.

Application Layer Protocols

Luckily, the mbed handles most of the protocols for us, with the help of some libraries. When we are writing applications in the mbed (or any system), we are mostly concerned with the application layer to make devices talk to each other (as the lower levels are already implemented for us). In this tutorial, we relied on the Network Time Protocol (NTP) to talk to a time server on the Internet. When it comes to programming embedded devices, the Dynamic Host Configuration Protocol (DHCP), the Hypertext Transfer Protocol (HTTP), and the File Transfer Protocol (FTP) are also important.

Timekeeping

Embedded systems have several methods to keeping time. The two most popular ways are counting clock cycles and using a real-time clock (RTC).

If we know the frequency of the processor’s clock, then we can calculate how many clock cycles we need to wait if we want to delay by a certain amount of time. For example, if we have a 100MHz clock, we know that a cycle happens every 0.01 microseconds (1 / 100MHz = 0.01 microseconds). If we want to delay 20 milliseconds, then we would have the processor do nothing for 2,000,000 cycles (0.01 microseconds x 2,000,000 = 20,000 microseconds = 20 milliseconds).

These delay functions have been wrapped up for you with mbed. To delay for a number of seconds, use wait(). The other two functions, wait_ms() and wait_us(), allow you to delay by a number of milliseconds and microseconds, respectively.

Unfortunately, waiting by cycles is often not precise. Your clock speed may be slightly off (thanks to things like temperature), or your wait() function might be interrupted by other code, which would throw off your ability to count exactly how much time has passed. Fortunately, there is a piece of hardware that can keep time much more accurately: the real-time clock.

RTCs are often a separate chip with its own clock that has the sole purpose of keeping track of time. Many times (such as in the case of your computer), the RTC will have a small battery attached so that it will remember the time even when you turn off your computer.

Luckily for us, the mbed has an RTC already built in to its circuitry. The mbed library handles talking to the RTC module so we can set and read the time. We call set_time() to set the current time on the RTC and localtime() to read the time. Note that in the Internet Clock example, we use setTime(), a method in NTPClient, to set the RTC time. We then use localtime() to retrieve the time.

To read more about real-time clocks, see this article.

Going Further

By connecting our mbed to the Internet, we opened up many new possibilities. We won’t continue with the Internet in this tutorial series, but feel free to try out some of the suggested projects in “Beyond the Tutorial” to learn more about making devices talk to each other!

Beyond the Tutorial

  • Adjust the clock to your timezone
  • Display your current location using IP-based geolocation (Hint: read this article)
  • Using HTTP, can you download the contents of a website and display the HTML on your LCD? (Hint: see the HTTPClient library)
  • Make a feed on data.sparkfun.com and push some data to it (Hint: see this guide on pushing data to data.sparkfun)
  • Try running an HTTP Server on the mbed

Digging Deeper

Experiment 6: USB Host and Threading

In this tutorial, we turn the mbed LPC1768 into a USB host. For this, we will use mbed’s USBHost library and the USB Type A Female Breakout. Leave the LCD connected, as we will use it to display characters from a USB keyboard. Additionally, we introduce the concept of threading so that we can essentially do 2 things at once (specifically, listen for keystrokes and blink an LED).

IMPORTANT: You will need a USB keyboard for this tutorial.

mbed USB host keyboard circuit

Suggested Reading

The Circuit

This circuit can be made with parts in the SparkFun mbed Starter Kit. Also, keep in mind that the LPC1768 box contains a USB mini-B cable for programming and power.

Parts List

In addition to the listed parts, you will also need a USB keyboard to complete the tutorial.

Schematic

mbed USB Host schematic

Click on schematic to view larger image.

Connections

Connect the LPC1768 to the LCD and USB breakout in the following fashion. Note that the LCD uses the same connections as in Part 3.

Fritzing Diagram

mbed usb host fritzing

Hookup Table

Place the LPC1768 in a breadboard with pin VOUT in position i1 and pin 20 in position b20.

Connect the rest of the components as follows:

ComponentBreadboard
uLCD-144-G2*h26 (RES)h27 (GND)h28 (RX)h29 (TX)h30 (+5V)
USB Type A Female Breakoutb26 (VCC)b27 (D-)b28 (D+)b29 (GND)
Jumper Wirej2d26
Jumper Wiree26f30
Jumper Wirea1( - )
Jumper Wirea9f28
Jumper Wirea10f29
Jumper Wirea11f26
Jumper Wire( - )f27
Jumper Wirej9e27
Jumper Wirej10e28
Jumper Wire( - )e29

* Pins not listed are not used.


The Code

For this tutorial, we will be using the LCD and USB Host libraries. In our main.cpp, we create a thread that runs the USB Host function separately from the rest of the program. This allows us to blink an LED and have it not interrupt or be interrupted by keyboard input.

Libraries

Navigate to the mbed.org, login, and navigate to your Compiler.

Create a new program with the “Blinky LED Hello World” template. Name it something like “usb_host.”

Navigate to the following pages and import each library into your “usb_host” program.

The mbed library should already be imported if you used the “Blinky” template.

mbed USB Host libraries

Program

Click on “main.cpp” in your project, remove the template code, and copy in the following code.

language:c
// USB host keyboard and LCD demo

#include "mbed.h"
#include "USBHostKeyboard.h"
#include "uLCD_4DGL.h"

// LED to demonstrate multi-threading
DigitalOut led(LED1);

// Graphic LCD - TX, RX, and RES pins
uLCD_4DGL uLCD(p9,p10,p11);

// Callback function from thread
void onKey(uint8_t key) {
    uLCD.printf("%c", key);
}

// Function that runs continuously in the thread
void keyboard_task(void const *) {

    USBHostKeyboard keyboard;

    while(1) {

        // Try to connect a USB keyboard
        uLCD.printf("Waiting...\n");
        while(!keyboard.connect()) {
            Thread::wait(500);
        }
        uLCD.printf("Connected!\n");

        // When connected, attach handler called on keyboard event
        keyboard.attach(onKey);

        // Wait until the keyboard is disconnected
        while(keyboard.connected()) {
            Thread::wait(500);
        }
        uLCD.printf("\nDisconnected!\n");
    }
}

// Main - the program enters here
int main() {

    // Initialize LCD
    uLCD.baudrate(115200);
    uLCD.background_color(BLACK);
    uLCD.cls();
    uLCD.locate(0,0);

    // Create a thread that runs a function (keyboard_task)
    Thread keyboardTask(keyboard_task, NULL, osPriorityNormal, 256 * 4);

    // Flash an LED forever
    while(1) {
        led=!led;
        Thread::wait(500);
    }
}

Run

Compile the program and copy the downloaded file to the mbed. Connect a USB keyboard to the USB breakout board.

mbed with USB breakout board and keyboard

Press the mbed’s restart button, and the LCD should show “Waiting…” If the keyboard was connected properly, you should see “Connected” on the LCD. Once you see “Connected,” start typing! You will see your keystrokes appear on the LCD.

NOTE #1: If you have some trouble getting the keyboard to connect, make sure the keyboard is plugged in and try resetting the mbed.

NOTE #2: The USBHost library is in beta and has some issues connecting USB devices sometimes. Not all keyboards will work with this demo.

Also, if you try typing too fast, you will see repeat keys. This is because the mbed does not process two simultaneous key presses correctly.

mbed running keyboard demo on LCD

Concepts

We covered two important concepts in this tutorial: USB and threading. Both create a unique set of opportunities for embedded systems.

Callbacks

In our program, we define an onKey() function. This is a callback.

onKey(uint8_t key) is a function that is declared in the USBHostKeyboard library, but the definition is left to us to implement. Callbacks are executed whenever an event occurs in another piece of code (within the USBHostKeyboard code, in this case).

We define onKey() in our code (it prints the received character to the LCD), and then we pass the onKey() function to our USBHostKeyboard object with the following line:

language:c
keyboard.attach(onKey);

This lets the USBHostKeyboard object know where to find the onKey() callback function. After that, whenever a keystroke occurs on the connected keyboard, the onKey() function is called.

USB Host

Universal Serial Bus (USB) has been around for many years. Created in the mid-1990s, USB has been the most popular way to connect peripherals to computers. As a result, many embedded systems support USB communications.

While many embedded systems can support being a USB Device, having USB Host capabilities is only seen in more powerful processors. Being able to act as a host means that we can plug in a number of devices normally reserved for computers: keyboards, mice, flash drives, etc. If you really want to get involved in USB development, this book is a great place to start.

Threading

If you are carefully reviewing the code, you might have noticed the keyword “Thread” appear. This is a function built into the mbed library that allows us to run multiple processes at the same time (well, not quite. The processor relies on a technique called Scheduling to determine which process gets run, since only one can run at a time in reality). It is important to understand that our mbed is powerful enough to allow us to run multiple threads (many, smaller microcontrollers, such as the ATmega 328p, of Arduino fame, have trouble with multiple threads).

When a Thread is created, as in our USB Host example, it calls the function given in its parameters (keyboard_task, in this case). The threaded function runs while the rest of the program continues at the same time (in theory, the “Flash an LED forever” section runs while “keyboard_task” is executing simultaneously).

If you would like more control over threads and the scheduling, take a look at mbed’s Real Time Operating System (RTOS) library.

Going Further

Adding USB lets us connect many different peripherals to our mbed. Additionally, we learned about threading, which lets us run multiple processes at the same time.

Beyond the Tutorial

  • Make the backspace key actually delete characters on the LCD
  • Use the graphics functions of the LCD to control a ball with the keyboard’s arrow keys
  • Use a mouse to control a ball around the LCD (Hint: see USBHostMouse)
  • Read some files on a USB flash drive (Hint: see USBHostMSD)

Digging Deeper

Experiment 7: USB Device

This tutorial covers USB devices with the mbed LPC1768. Using a USB mini-B breakout and some buttons, we enumerate the mbed as a USB mouse and control the computer’s pointer with the buttons.

mbed USB device circuit

Suggested Reading

The Circuit

This circuit can be made with parts in the SparkFun mbed Starter Kit. Also, keep in mind that the LPC1768 box contains a USB mini-B cable for programming and power.

Parts List

Schematic

mbed usb device schematic

Click on schematic to view larger image.

Connections

Connect the LPC1768 to the USB mini-B breakout and buttons.

Fritzing Diagram

mbed USB Device fritzing

Hookup Table

Place the LPC1768 in the first breadboard with pin VOUT in position i1 and pin 20 in position b20.

Connect the rest of the components as follows:

ComponentBreadboard 1Breadboard 2
Mini USB Breakout*h25 (GND)h27 (D+)h28 (D-)h29 (VCC)
Pushbuttond2d4g2g4
Pushbuttond10d12g10g12
Pushbuttond18d20g18g20
Pushbuttond26d28g26g28
10K Resistori2( + )
10K Resistori10( + )
10K Resistori18( + )
10K Resistori26( + )
Jumper Wirej1( + )
Jumper Wirea1( - )
Jumper Wirea2f29
Jumper Wiref25( - )
Jumper Wirej9f28
Jumper Wirej10f27
Jumper Wirea5h2
Jumper Wirea6h10
Jumper Wirea7h18
Jumper Wirea8h26
Jumper Wire( - )h4
Jumper Wire( - )h12
Jumper Wire( - )h20
Jumper Wire( - )h28

* Pins not listed are not used.


The Code

In order to make the mbed act like a USB mouse for this walkthrough, we will rely on mbed’s USBDevice library. This library contains all the necessary functions to enumerate as a USB device to a computer and function as a mouse.

Libraries

Navigate to the mbed.org, login, and navigate to your Compiler.

Create a new program with the “Blinky LED Hello World” template. Name it something like “usb_device.”

Navigate to the following pages and import each library into your “usb_device” program.

The mbed library should already be imported if you used the “Blinky” template.

mbed USB Device libraries

Program

Click on “main.cpp” in your project, remove the template code, and copy in the following code.

language:c
// USB Device demo - control mouse pointer with buttons

#include "mbed.h"
#include "USBMouse.h"

// USB Mouse object
USBMouse mouse;

// Define buttons
DigitalIn button_up(p5);
DigitalIn button_down(p6);
DigitalIn button_left(p7);
DigitalIn button_right(p8);

DigitalOut myled(LED1);

int main() {
    int x = 0;
    int y = 0;


    while (1) {

        // Determine mouse pointer horizontal direction
        x = button_left ^ button_right;
        if ( button_right ) {
            x = -1 * x;
        }

        // Determine mouse pointer vertical direction
        y = button_up ^ button_down;
        if ( button_down ) {
            y = -1 * y;
        }

        // Move mouse
        mouse.move(x, y);

        // Wait for next cycle
        wait(0.001);
    }
}

Run

Compile the program and copy the downloaded file to the mbed. Disconnect the USB mini-B that you used to program your mbed and connect it into the USB mini-B breakout board.

USB cable plugged into breakout board

Make sure that the other end of the USB cable is plugged into your computer and press the mbed’s restart button. Your computer should tell you that a USB input device has been detected. Start pressing the four buttons on the breadboard.

mbed running as a USB mouse

Your mouse pointer should start moving around!

moving mouse pointer

Concepts

We really only covered one important new concept in this tutorial: USB devices. Instead of acting as a USB host to accept peripherals, we turned the mbed into a USB peripheral. This allowed us to plug the mbed into a computer and control some functions normally assigned to dedicated accessories (a mouse, in this case).

USB Device

A lot of things need to happen to show up as a USB device on a computer. The process of attaching a device, getting assigned a unique identifier and a driver is called “USB enumeration.” Luckily, the mbed USBDevice library handles all of the device-side enumeration details for us.

Being able to enumerate as a USB device opens up a world of possibilities for us. We can make the mbed act as a mouse, a keyboard, an audio device, a mass storage device, and so on. Note that the LPC1768 only supports USB Full-Speed, which means that the higher rates of USB 2.0 and 3.0 are not available to us. If you wanted to make your own mbed Flash Drive, it would be quite slow.

If you want to get really involved in USB device development, see Jan Axelson’s USB Complete book.

Going Further

Becoming a USB device lets us interact with many different computers and mobile devices. You could even make your own keyboard and mouse!

Beyond the Tutorial

  • Make the buttons act as mouse clicks instead of moving the pointer
  • Make the buttons act as keyboard keys (Hint: see USBDevice Keyboard)
  • Create a program that automatically opens up a text editor and types out a message to the user whenever the mbed is plugged in as a USB device

Digging Deeper

Experiment 8: Temperature Logging

We are going to move on to a very important topic for embedded systems: sensor data logging! Many microcontroller projects are built around the concept of taking some sort of measurement (temperature, distance, light, acceleration, GPS coordinates, heart rate, etc.) and logging it. This data is examined (later or in real time) to look for patterns or notify the user of some kind of anomoly.

In this tutorial, we will have the mbed LPC1768 take measurements from a temperature sensor, log the data to a micro SD card, and print out the contents of the SD card to a console.

mbed temperature logging circuit

Suggested Reading

The Circuit

This circuit can be made with parts in the SparkFun mbed Starter Kit. Also, keep in mind that the LPC1768 box contains a USB mini-B cable for programming and power.

Parts List

Schematic

mbed temperature logging schematic

Click on schematic to view larger image.

Connections

Connect the LPC1768 to the micro SD card breakout board and TMP36 temperature sensor. Insert a micro SD card into the breakout board.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction. Polarized components are highlighted with a yellow warning triangle in the table below.

Fritzing Diagram

mbed temperature logging fritzing

Hookup Table

Place the LPC1768 in a breadboard with pin VOUT in position i1 and pin 20 in position b20.

Connect the rest of the components as follows:

ComponentBreadboard
MicroSD Transflash Breakout*g24 (CS)g25 (DI)g26 (VCC)g27 (SCK)g28 (GND)g29 (DO)
Temperature Sensor - TMP36c28 (V+)c29 (SIGNAL)c30 (GND)
Jumper Wirej1( + )
Jumper Wirea1( - )
Jumper Wirea5f25
Jumper Wirea6f29
Jumper Wirea7f27
Jumper Wirea8f24
Jumper Wire( - )f28
Jumper Wire( + )f26
Jumper Wirea15a29
Jumper Wire( - )a30
Jumper Wire( + )a28

* Pins not listed are not used.


Tips

Make sure you face the TMP36 temperature sensor the correct way. The flat side of the black package body is considered the front. See this tutorial to learn more about polarity.

TMP36 pinout

The Code

We plan to read an analog voltage from the sensor, and to do this, we rely on the mbed’s analog-to-digital converter (ADC) built into the chip. Every time we read this value, we convert it to an actual temperature in degrees Celsius and log it to the SD card. Additionally, we will be using the mbed’s built-in USB-to-Serial device to print our logged values to a console on our computer.

Software

Windows

If you are on Windows, we will be relying on a program called “PuTTY.” You are also welcome to use any number of other serial terminal programs, such as CoolTerm or Realterm.

Navigate to the PuTTY homepage and download putty.exe.

There is no installation process, so just copy putty.exe to some place you will remember, such as your desktop.

Additionally, we need to install a Serial Port driver if you are on Windows. Navigate to mbed’s Windows serial configuration page and download the latest driver.

Double click the downloaded file and follow the on-screen instructions to install the driver.

Mac OS X

Good news! If you are on a Mac, you already have the necessary serial drivers and program. We will be using the screen command.

Linux

Just like Mac, you should have the serial driver and tools already installed. If not, look into getting screen or another serial console tool.

If you need to install screen, see this guide for yum or this guide for apt-get.

Libraries

Navigate to the mbed.org, login, and navigate to your Compiler.

Create a new program with the “Blinky LED Hello World” template. Name it something like “temp_logging.”

Navigate to the following pages and import each library into your “temp_logging” program.

The SDFileSystem library should appear in your temp_logging project.

mbed logging imported library

Program

Click on “main.cpp” in your project, remove the template code, and copy in the following code.

language:c
// Temperature logging demo - record temperatures to SD card and print them to
// the console every 10 seconds

#include "mbed.h"
#include "SDFileSystem.h"

// Analog input (pin 15)
AnalogIn ain(p15);

// USB serial (tx, rx)
Serial pc(USBTX, USBRX);

// SD card (SPI pins)
SDFileSystem sd(p5, p6, p7, p8, "sd");

// Timer for our timestamps
Timer timer;

int main() {

    FILE *file;
    float voltage_in;
    float degrees_c;
    int i;
    int c;

    // Start our timer
    timer.start();

    // Open file for writing
    file = fopen("/sd/temp_data.txt", "w");
    if ( file == NULL ) {
        error("ERROR: Could not open file for writing!\n\r");
        return -1;
    }

    // Tell the user we need to wait while we collect some data
    pc.printf("\nCollecting data (Do not remove SD Card!) ...\n\r");

    // Collect temperatures with timestamps every second
    for(i = 0; i < 10; i++) {
        voltage_in = ain * 3.3;
        degrees_c = (voltage_in - 0.5) * 100.0;
        fprintf(file, "%2.2fs: %3.1f deg C\n\r", timer.read(), degrees_c);
        wait(1);
    }

    // Close file and re-open it for reading
    fclose(file);
    file = fopen("/sd/temp_data.txt", "r");
    if ( file == NULL ) {
        error("ERROR: Could not open file for reading!\n\r");
        return -1;
    }

    // Print results to console
    pc.printf("Temperature data:\n\r");
    while(1) {
       c = fgetc(file);
       if ( c == EOF ) {
           break;
       }
       pc.putc(c);
    }

    // Close the file and finish
    fclose(file);
    pc.printf("Done! Safe to remove SD card\n\r");

    return 0;
}

Run

Windows

Compile the program and copy the downloaded file to the mbed.

Click the Windows Start button and search for “device manager.”

searching for device manager

Click on “Device Manager.” You should see the Device Manager open up. Click to expand “Ports (COM & LPT).” Make a note of which COM port is listed as the “mbed Serial Port” (COM12, in this example).

Note: If you do not see the mbed Serial Port listed, you need to install (or re-install) the mbed Windows serial driver.

Device Manager with mbed Serial Port

Double-click the putty.exe icon to start PuTTY. In the left pane, click “Terminal” to configure PuTTY. Check “Implicit CR in every LF” so that text appears properly aligned in our console.

PuTTY terminal configuration

Click “Session” in the left pane. Click the “Serial” radio button and change “Serial line” to your COM port (COM12 in this example). Leave speed at 9600. Click “Open” to start a serial terminal.

PuTTY serial configuration

Press the mbed’s reset button. You should see some text appear in the console. Wait 10 seconds while the mbed makes some temperature readings, and it will print them to the terminal.

mbed serial terminal output

If you see a message like “ERROR: Could not open file for writing!” it means that you do not have an SD card plugged in, you do not have the SD Card breakout connected properly, or the SD card is not formatted properly.

If you plug the SD card into your computer and open up the “temp_data.txt” file with a text editor (located in the SD card’s root directory), you should see the logged data.

text file with logged temperature data

Mac OS X

First, we need to find out which USB serial port the mbed is attached to. Unplug the mbed. Open up Finder and navigate to Applications → Utilities → Terminal.

Enter the following command:

ls /dev/tty.*

Make a note of which devices appeared. Plug the mbed back into your Mac and enter the command again:

ls /dev/tty.*

A new tty device should appear. For example, in my case, I saw “tty.usbmodem1452” show up. Make a note of which new tty device appeared. Open a serial terminal using the screen command:

screen /dev/tty.<your USB serial device> 9960

Press the reset button on your mbed and wait while temperature data is collected. After about 10 seconds, you should see the temperature data appear in your Terminal.

Printout of temperatures on Mac

You can also plug the SD card into your computer and open the “temp_data.txt” file with a text editor (located in the SD card’s root directory).

Saved text file on Mac

Linux

To begin, we need to find out which USB serial port the mbed is attached to. Unplug the mbed. Open a terminal and enter:

ls /dev/tty*

Plug the mbed back into your computer and enter the command again:

ls /dev/tty*

A new tty device should appear. In my case, I saw “/dev/ttyACM0” show up. Make a note of which new tty device appeared. Use the screen command to open a serial terminal to the mbed:

sudo screen /dev/<your tty device> 9960

Note that you will likely need root access to open the serial terminal!

Press the reset button on your mbed and wait while temperature data is collected. After about 10 seconds, you should see the temperature data appear in your Terminal.

Printout of temperatures on Linux

You can also plug the SD card into your computer and open the “temp_data.txt” file with a text editor (located in the SD card’s root directory).

Saved text file on Linux

Concepts

In this tutorial, we introduced several new concepts. In particular, sending text over serial to a terminal is incredibly useful for debugging and interacting with your project.

Serial Terminal

The serial terminal dates back the first computers and mainframes of the 1960s. In order to interact with a mainframe, several terminals were connected to the mainframe, often with an RS-232 serial connection. These terminals offered a simple keyboard and monitor with a command line interface. Users could type commands and get a response back from the mainframe.

With the rise of the graphical user interface (GUI), such as Windows, terminal programs became emulated inside of the GUI and usually only reserved for more advanced functions. Because many low-power embedded systems, such as the LPC1768, are incapable of running a GUI, we rely on a serial terminal to communicate with the device. Check out our tutorial on Serial Terminal Emulators) for more info.

We use a USB cable to send and receiver serial commands from the computer to the LPC1768. The mbed platform converts the USB signals to UART, which is interpreted by the LPC1768 processor. By using a program like PuTTY, we can send serial commands over that USB channel. If we write serial commands in our mbed program, we can create a communications link between the mbed and our serial terminal. This allows us to interact with the mbed in real time!

Using a serial terminal like this is crucial in working with embedded systems. We can add printf statements in our program that provides status updates, gives the contents of variables, and informs us of errors. Using a serial terminal in this manner is extremely helpful in debugging our embedded programs.

Analog to Digital Converter (ADC)

We used the mbed’s internal ADC to take measurements from the temperature sensor. The TMP36 Temperature Sensor works by amplifying the voltage drop across the base and emitter of a transistor as temperature changes.

Pins 15 - 20 on the LPC1768 are capable of analog to digital conversions. Voltages between 0V and 3.3V are broken up (quantized) into steps. The LPC1768 uses a 12-bit value to denote the ADC readings, which means that there are 4096 possible values for voltages. In other words, 0V - 3.3V are broken down into 0.0008057V steps. Reading 0 on the ADC indicates 0V, reading 1 indicates 0.0008057V, reading 2 indicates 0.0016114V and so on.

However, note that in our program, we read the analog value (ain) as a float value between 0.0 and 1.0, where 1.0 is 3.3V. So, in order to determine the actual measured voltage, we multiplied ain * 3.3. Using the measured voltage, we calculated the temperature in Celsius by the equation (Vmeas - 0.5) * 100.0, as per the TMP36 datasheet.

If you would like to read more about ADC, see this Wikipedia article.

Serial Peripheral Interface (SPI)

SPI is a de facto communications bus standard, which means that its pins and protocol are just accepted by industry (versus being spelled out in an actual standard by a governing body, like I2C). SPI generally requires 4 pins: SCK, MISO, MOSI, and CS. Because MISO and MOSI transmit data simultaneously, full duplex communications are possible. SPI is capable of faster transfer speeds than I2C, but can only have 1 master and usually needs 1 extra pin dedicated for each device added on the bus. Read more about SPI here.

SD Cards

Secure Digital (SD) cards grew out of MultiMediaCards (MMC) in 1999 as a small, transportable form factor for non-volatile flash memory. There are several ways to transfer data to and from SD cards: SPI Mode, One-Bit SD Bus Mode, and Four-Bit SD Bus Mode. We used SPI in this project, as it is the easiest to use and does not require an SD host license. Four-Bit mode, on the other hand, requires a host license and offers much faster transfer speeds. Read more about the SD format here.

FAT File System

The mbed SDFileSystem library relies on the File Allocation Table (FAT) file system to read and write files in the SD card. The FAT file system is an old and extremely simple file structure system that is still used by most low storage volume flash media (e.g. SD cards, flash drives, etc.) today. It is supported by every major operating system. In basic terms, the front section of the disk partition is reserved for the file allocation table, which is a simple index that contains the name of the file (or folder) and its location in the partition. Reading the FAT gives you all the files and folders within the disk partition, and you can use this information to read, write, and modify specific files. You can learn more about the FAT file system here.

File Descriptor

In order to read and write to a file (located in our FAT file system!), we need to use a file descriptor to access that file.

In our program, we create a file descriptor with

language:c
FILE *file;

The pointer *file will be used as a handle to manage all of our file operations.

We then open a file from our FAT file system (namely, the temp_data.txt file on our SD card) and assign it to our handle. Notice the “w” parameter, which asks for “write” permissions to the file. If the file does not exist, it is created.

language:c
file = fopen("/sd/temp_data.txt", "w");

After we attempt to open the file, we check to make sure that the file was indeed opened for writing:

langauge:c
if ( file == NULL ) {
    error("ERROR: Could not open file for writing!\n");
    return -1;
}

If the file was not opened successfully, the file variable does not point to anything (i.e. NULL). In this case, we print an error and stop the program.

We use the fprintf() function to write characters to the file.

language:c
fprintf(file, "%2.2fs: %3.1f deg C\n", timer.read(), degrees_c);

Notice that we passed in the file handle as our first parameter, which tells fprintf() where to put the characters.

Once we are done writing to the file, we close it with

language:c
fclose(file);

It’s always a good idea to close a file when you are done with it! Otherwise, you might corrupt the file (or, worse, the filesystem) if your program starts to behave unexpectedly with a file still open.

We can perform a similar procedure to read from a file. In our example, we use fgetc() to read characters from the file one at a time.

Lack of Super Loop

What happened to our while(1) statement? All of our other examples included this loop-forever statement to make up our super loop architecture. In this tutorial, we only wanted the program to run once and then stop. To do this, we do not include a while(1) statement and exit main() with

language:c
return 0;

After our program executes the return line in main(), the program stops running. We need to restart the mbed board (with the button) to run the program again.

Generally, it is good practice to include an empty while loop:

language:c
while (1) { }

to end your program in an embedded system. We did not include it to show that you can get away without it, and the program will still execute (only once, though!).

You can read more about return values from main().

Going Further

Sensor reading and logging is one of the most useful features of embedded systems. Additionally, we looked at how we can use a terminal program to interact with the mbed, which is important for debugging projects.

Beyond the Tutorial

  • Right now, the SD card is at risk for being ruined if you remove it or shut off power in the middle of a write operation. Change the code so that the file is only ever opened and written to just after a measurement is made.
  • Change the code so that measurements are taken once per minute and do not stop after just 10 readings.
  • Make the mbed consume less power between readings (Hint: see the PowerControl library)
  • Have the mbed post the collected data once per day on a data.sparkfun.com data stream. You’ll be able to see some interesting patterns in the temperature data after a few days!

Digging Deeper

Experiment 9: PWM Sounds

Let’s make some music! By using the pulse-width modulation (PWM) pins on the mbed LPC1768 and a speaker (or headphones), we can make rudimentary sounds. By controlling the PWM frequency, we can create specific notes in the music scale. While it won’t sound like a full-size orchestra, the notes (and perhaps the song) will be recognizable.

This tutorial will cover how to connect a headphone jack to the mbed and control the PWM pins to create basic sounds.

Note: You will need a set of headphones or speakers to hear the sounds.

mbed PWM sounds circuit

Suggested Reading

The Circuit

This circuit can be made with parts in the SparkFun mbed Starter Kit. Also, keep in mind that the LPC1768 box contains a USB mini-B cable for programming and power.

Parts List

In addition to the listed parts, you will also need a set of headphones or speakers (with a 3.5mm plug) to complete the tutorial.

Schematic

mbed pwm music schematic

Click on schematic to view larger image.

Connections

Connect a PWM output pin of the LPC1768 to the TIP of the audio jack breakout. Also, connect the tip to RING1 of the audio jack in order to get sound out of both the left and right speakers. Do not connect anything to RING2!

Fritzing Diagram

mbed pwm music maker fritzing

Hookup Table

Place the LPC1768 in a breadboard with pin VOUT in position i1 and pin 20 in position b20.

Connect the rest of the components as follows:

ComponentBreadboard
TRRS 3.5mm Jack Breakout*b27 (TIP)b28 (RING1)b30 (SLEEVE)
Jumper Wirea1d30
Jumper Wirej20e27
Jumper Wirec27c28

* Pins not listed are not used.


The Code

To make sounds, we need to modulate our PWM pin with a particular frequency. Luckily, we can control the precise frequency of the PWM within the mbed. If you looked into how PWM works, you’ll notice that it is a square wave. Square waves do not make the most pleasant sound, but it will be good enough for our purposes.

Program

This demo is simple! We don’t need any libraries.

Navigate to the mbed.org, login, and navigate to your Compiler.

Create a new program with the “Blinky LED Hello World” template. Name it something like “pwm_song.”

Click on “main.cpp” in your project, remove the template code, and copy in the following code.

language:c
// Plays a familiar melody using PWM to the headphones. To find the frequencies
// of notes, see http://en.wikipedia.org/wiki/Piano_key_frequencies
// Based on the "speaker_demo_PWM" program by Jim Hamblen

#include "mbed.h"

#define VOLUME 0.01
#define BPM 100.0

PwmOut pwm_pin(p21);

// Plays a sound with the defined frequency, duration, and volume
void playNote(float frequency, float duration, float volume) {
    pwm_pin.period(1.0/frequency);
    pwm_pin = volume/2.0;
    wait(duration);
    pwm_pin = 0.0;
}

int main()
{
    float beat_duration;

    // Calculate duration of a quarter note from bpm
    beat_duration = 60.0 / BPM;

    // Loop forever
    while(1) {

        // First measure
        playNote(391.995, (beat_duration - 0.1), VOLUME);
        wait(0.1);
        playNote(391.995, (beat_duration - 0.1), VOLUME);
        wait(0.1);
        playNote(391.995, (beat_duration - 0.1), VOLUME);
        wait(0.1);
        playNote(311.127, (0.75 * beat_duration), VOLUME);
        playNote(466.164, (0.25 * beat_duration), VOLUME);

        // Second measure
        playNote(391.995, (beat_duration - 0.1), VOLUME);
        wait(0.1);
        playNote(311.127, (0.75 * beat_duration), VOLUME);
        playNote(466.164, (0.25 * beat_duration), VOLUME);
        playNote(391.995, ((2 * beat_duration) - 0.1), VOLUME);
        wait(0.1);

        // Third measure
        playNote(587.330, (beat_duration - 0.1), VOLUME);
        wait(0.1);
        playNote(587.330, (beat_duration - 0.1), VOLUME);
        wait(0.1);
        playNote(587.330, (beat_duration - 0.1), VOLUME);
        wait(0.1);
        playNote(622.254, (0.75 * beat_duration), VOLUME);
        playNote(466.164, (0.25 * beat_duration), VOLUME);

        // Fourth measure
        playNote(369.994, (beat_duration - 0.1), VOLUME);
        wait(0.1);
        playNote(311.127, (0.75 * beat_duration), VOLUME);
        playNote(466.164, (0.25 * beat_duration), VOLUME);
        playNote(391.995, ((2 * beat_duration) - 0.1), VOLUME);
        wait(0.1);
    }
}

Run

Compile the program and copy the downloaded file to the mbed. Connect a set of headphones or speakers to the audio jack. Press the mbed’s reset button, and you should hear a tune come out of your headphones or speakers!

If the volume is too low, adjust the VOLUME constant in the program (try 0.1 or 1).

mbed running PWM song with headphones

Concepts

Much like in our other PWM tutorial, we relied on pulse-width modulation to emulate an analog signal (sound, this time). We also connected a peripheral that allowed us to convert electrical signals into sound: a speaker (or headphones, but these are nothing more than tiny speakers that wrap around your head).

PWM for Sound

Much like in Part 2, we used a PWM to control the a signal. In this example, we adjusted the period of the PWM (the inverse of the frequency) to control the pitch of the musical note. We also adjusted the duty cycle of the PWM to control the volume of the note.

If you looked at the code, you’ll notice that there is also a “duration” parameter in the playNote function. This told the function how long to play the note. So, by setting various volumes, frequencies (pitch), and durations, we can play an entire song!

To read more about PWM, see this Wikipedia article.

Speakers

Speakers are fascinating pieces of technology, despite their seemingly simple function. An electromagnet moves an attached membrane, or cone, through a permanent magnet. An electrical current causes the electromagnet to move at varying rates, which moves the cone in a similar fashion. The cone forces air back and forth, which creates sound! At certain frequencies, these moving airwaves can be heard by our ears.

To learn more about how speakers work, see this article.

Going Further

Making sounds with PWM can be useful for adding feedback into your project. You could make chirps and buzzes to notify the user of important information. That, or you could just make an R2-D2 clone.

Beyond the Tutorial

  • Search for sheet music from your favorite song, and using a note/frequency chart, make the mbed play your song
  • Try using the digital-to-analog converter (DAC) pins to play songs instead of PWM (Hint: see Jim Hamblen’s example)
  • Can you make the DAC play a chord instead of a single note?

Digging Deeper

  • As it turns out, you can use a combination of DAC and PWM to make some interesting sounds. Read about their uses in synthesizers.
  • In order to get louder sounds, we need to amplify our signal. Read about how amplifiers work.
  • Headphones have a long and interesting history. Check it out here.

Experiment 10: Hardware Soundboard

In the final tutorial of our 10-part series, we will make a hardware soundboard using our mbed. We will store some .wav files on an SD card and play one whenever a button is pressed. You could use it to interject hilarious comments into any conversation!

mbed soundboard circuit

Suggested Reading

The Circuit

This circuit can be made with parts in the SparkFun mbed Starter Kit. Also, keep in mind that the LPC1768 box contains a USB mini-B cable for programming and power.

Parts List

Schematic

mbed soundboard wave player schematic

Click on schematic to view larger image.

Connections

Connect a digital-to-analog (DAC) pin of the mbed (pin 18, in this case) to a 330 Ω resistor and connect that resistor to the base of an NPN transistor (2N3904). Connect the emitter of the transistor to ground and the collector to the negative (-) side of the speaker. The positive side of the speaker should be attached to +5V (the VU pin on the mbed). Note that the +/- markings can be found on the underside of the speaker (there are no wires on the speaker like in the Fritzing diagram).

To hook up the buttons, connect one side of each pushbutton to ground and the other to pins 11, 12, 13, and 14 of the mbed.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction. Polarized components are highlighted with a yellow warning triangle in the table below.

Fritzing Diagram

mbed .wav player Fritzing

Hookup Table

Place the LPC1768 in the first breadboard with pin VOUT in position i1 and pin 20 in position b20.

Connect the rest of the components as follows:

ComponentBreadboard 1Breadboard 2
MicroSD Transflash Breakout*h24 (CS)h25 (DI)h26 (VCC)h27 (SCK)h28 (GND)h29 (DO)
c27 (E)c28 (B)c29 (C)
330 Resistorb24b28
Pushbuttond2d4g2g4
Pushbuttond7d9g7g9
Pushbuttond12d14g12g14
Pushbuttond17d19g17g19
Speakerf25 (+)e30 (-)
Jumper Wirej1g26
Jumper Wirea1( - )
Jumper Wirea5g25
Jumper Wirea6g29
Jumper Wirea7g27
Jumper Wirea8g24
Jumper Wireg28( - )
Jumper Wirea18a24
Jumper Wirea27( - )
Jumper Wirea29a30
Jumper Wirej2j25
Jumper Wirea11j2
Jumper Wire( - )j4
Jumper Wirea12j7
Jumper Wire( - )j9
Jumper Wirea13j12
Jumper Wire( - )j14
Jumper Wirea14j17
Jumper Wire( - )j19

* Pins not listed are not used.


Tips

Transistor

Make sure you are using the 2N3904 transistor and not the temperature sensor! Note that the flat edge of the transistor is facing down in the Fritzing diagram.

Speaker

Notice that the speaker has the positive (+) and negative (-) pins labeled on the underside. The speaker will fit directly on the breadboard, as the Fritzing diagram has been modified to show where the speaker should be plugged in (otherwise it would cover up the rest of the components in the picture!).

Place the positive (+) terminal of the speaker into hole f25 of the breadboard and the negative (-) terminal into hole e30. The speaker will be angled across the breadboard, but it will leave enough room for wires to be plugged into j25 and a30.

pcb speaker pin labels

The Code

For our soundboard, we need to read files from an SD card, which means using the SDFileSystem again. Additionally, we want to add another library that allows us to play .wav files.

Libraries

Navigate to the mbed.org, login, and navigate to your Compiler.

Create a new program with the “Blinky LED Hello World” template. Name it something like “soundboard.”

Navigate to the following pages and import each library into your “soundboard” program.

The libraries should appear in your soundboard project.

mbed soundboard libraries

Program

Click on “main.cpp” in your project, remove the template code, and copy in the following code.

language:c
// Soundboard that plays 1 of 4 .wav files stored on the SD card based on 1 of
// 4 buttons pressed

#include "mbed.h"
#include "wave_player.h"
#include "SDFileSystem.h"

// .wav files to play
char *filenames[4] = {  "/sd/good_morning.wav", \"/sd/questions.wav", \"/sd/lack_discipline.wav", \"/sd/stop_whining.wav"};

// Define buttons
DigitalIn button_1(p11);
DigitalIn button_2(p12);
DigitalIn button_3(p13);
DigitalIn button_4(p14);

// USB serial (tx, rx)
Serial pc(USBTX, USBRX);

// SD card
SDFileSystem sd(p5, p6, p7, p8, "sd");

// Audio out (DAC)
AnalogOut       DACout(p18);
wave_player     waver(&DACout);

// Play a .wav file
int playSound(int file_num) {

    FILE *file;

    // Open sound file for reading
    file = fopen(filenames[file_num], "r");
    if ( file == NULL ) {
        error("ERROR: Could not open file for reading!\n");
        return -1;
    }

    // Play the sound file
    pc.printf("Playing sound clip %i\r\n", (file_num + 1));
    waver.play(file);

    // Reset to beginning of file and close it
    fseek(file, 0, SEEK_SET);
    fclose(file);

    return 0;
}

int main() {

    // Use internal pull-up resistors
    button_1.mode(PullUp);
    button_2.mode(PullUp);
    button_3.mode(PullUp);
    button_4.mode(PullUp);

    pc.printf("\r\nHardware Soundboard\r\n");

    while(1) {

        // Figure out which button was pressed and play that file
        if ( button_1 == 0 ) {
            playSound(0);
        }
        if ( button_2 == 0 ) {
            playSound(1);
        }
        if ( button_3 == 0 ) {
            playSound(2);
        }
        if ( button_4 == 0 ) {
            playSound(3);
        }

        // Wait 10ms before sampling the buttons again
        wait(0.01);
    }
}

Run

Insert the micro SD card into the USB to micro SD card adapter and insert the USB adapter into your computer. Copy the following .wav files to the SD’s root directory:

Wave files on SD card

Remove the SD card from your computer and plug it into the breakout board on the soundboard project.

Compile the program and copy the downloaded file to the mbed. Press the mbed’s reset button to start running the program. Press one of the 4 buttons to hear a sound clip!

mbed running hardware soundboard

Concepts

This project was larger than the others before it. There are a number of things going on, but most of them we covered in previous tutorials.

Amplifier

In addition to adding a speaker to play sounds, we created a very simple amplifier to increase the signal strength (and the volume). We used an NPN transistor (specifically, a 2N3904) that converts a small current through its base into a larger current through its collector. If we tried to power the speaker directly from the mbed’s pin, we would likely draw enough power to hurt the processor. Audio amplifiers can be quite complex. Read more about them here.

Internal Pull-ups

When we used buttons in previous tutorials, we used external pull-up resistors on the buttons to prevent a floating pin. In order to save board space for this project, we used mbed’s internal pull-ups. These are resistors internal to the mbed processor and can be enabled for each of the pins with the following line of code:

pin_name.mode(PullUp);

Going Further

In this demo, we combined many concepts to create a fun project. We made a simple amplifier to play sounds and relied on the wave_player library to read .wav files. Adding sound to a project can add a layer of interactivity and bring it to life.

Beyond the Tutorial

  • Download or create your own .wav files and play them using our soundboard. Note: you might have to use an editing program like Audacity to convert sound clips into .wav files if they do not play on the mbed.
  • Add lights! Program some LEDs to flash whenever a clip is being played.
  • You might need some extra components not found in the kit, but can you get a sound recorder to work on the mbed? (Hint: see the Simple Wave Recorder & Player library)

Digging Deeper

The End!

This demo finishes up our 10-part series on the mbed. We covered a number of topics that are considered important to embedded systems: buttons, LEDs, GPIO, ADC, DAC, interrupts, SPI, I2C, UART, etc. You had the opportunity to search for libraries on mbed.org, import them into your program, and run some basic firmware on the LPC1768. By now, you have had a good exposure to the building blocks of embedded programming on the mbed and should be ready to tackle your first project.

Make something cool! Take a picture of it and tag @sparkfun or @mbedmicro on Twitter. Or, post your project to the mbed.org Cookbook.


learn.sparkfun.com |CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

Hacking the MiP - Proto Back

$
0
0

Hacking the MiP - Proto Back a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t335

Overview

alt text

MiP Robotics Platform

The MiP Robotic Platform is the first self-balancing robot that you get to control and with which you can play games. The MiP can drive, dance, plays games, battle with other MiPs, respond to simple hand motions and can be remotely controlled by a compatible iOS or Android device. But did you know you can hack it?

alt text

Hacking Port Exposed!

The hacking port breaks out the following signals: * GND - A ground connection to the battery on the MiP * RX - A 3.3v signal level UART receive pin * TX - A 3.3v signal level UART transmit pin * 6v (Battery) - Raw battery power

Required Materials

There are a few components that you will need in order to exploit that port.

Once you have all the parts you need, let’s get started!

Attaching the Proto Back

Step 1. Remove Battery Pack

You want to make sure the MiP is powered off and the batteries are removed before we start hacking away.

alt text

Battery Pack Screw Locations

alt text

Battery Pack removed

Step 2. Drill and Remove Wheel Screws

Fortunately/un-fortunately the manufacturer glued the screw caps on the wheels. This means they won’t fall out, but this means they won’t fall out. Take your favorite drilling device and carefully create a hole in the wheel. This will expose enough of the screw head to get a phillips head screw driver in. I found that a 3/16" drill bit works great. I have also used a Dremel rotary tool to grind out the plug. NOTE: Remember to drill both sides

alt text

Drilling for Wheel Screws

Step 3. Remove Wheels

Usind a small phillips screwdriver, remove both wheels. If the holes you drilled were small enough, the screws will stay in the wheels.

Step 4. Remove the 8 body screws.

Remove the 8 body screws that hold the two halves of the MiP together. (be sure not to lose the screws so you can put it back together). NOTE: The wheels should be removed, I forgot to take them off for the photo

alt text

Body Screw Locations

Step 5. Remove Electrical Connections

There are three cables to remove. They are all different enough that it shoudl be obvious where each is replaced. Here is a quick overview of what each cable is for.

alt text

Connections of a MiP

Step 6. Cut Back Shell in Half

With a small saw or rotary tool cut the battery section from the back shell. The small “belt” of the MiP makes a great cut guide.

alt text

MiP Cut Line

alt text

“Don’t worry I have a degree in rocket surgery”

Step 7. Solder the Connector to the Proto-Back

Solder the 4-pin connector to the back of the Proto-Back. The front side has a Sparkfun and OSHW logo. THe backside does not. NOTE: Pay close attention to the orientation of the connector. There is a small groove located on the bottom of the connector, this groove should be pointed towards the inside of the board as shown below.

alt text

4-pin Connector Location

Step 8. Re-assemble MiP

First re-attach the lower portion of the MiP back shell. Be sure to replace the connectors to enable the power switch and the speaker. Connect the Expansion Cable to the MiP and the Proto-Back. Then using the 4 screws left over from the back shell, carefully install the new proto-back. Re-install the wheels and you are ready to go!

alt text

Components before assembly

alt text

Completed assembly without wheels

Powering the MiP

You may have noticed that there are no batteries on the MiP now. You will need to devise a power strategy to continue on. Here are some tips:

  • You can use the power switch by plugging power into the power connector shown in step 5.

    • The MiP has been tested with a 2 cell Lithium polymer pack. (7.4v)
    • Carefully note the polarity of the connector. Our Lipo packs are reverse polarity to the connector on the MiP battery pack
    • You can remove the wire harnes from the battery pack and continue to utilize the PTC fuse. This is also handy to re-use the power connector required.
  • You can power the MiP directly from the 6V and GND pins exposed on the breakout board.

    • Allows the Mip to be externally turned on/off.
    • Provides power to other devices that may not require the MiP to be active. Example: Booting a RasPi, BeagleBone, Edison, or other single board computer.

Good luck and happy hacking!

alt text

“Beagle MiP” BeagleBoard using a webcamera to track objects

Resources and Going Further

Now that you are ready to hack you may be interested in some of these other tutorials:


learn.sparkfun.com |CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

Hacking the MiP - Proto Pack

$
0
0

Hacking the MiP - Proto Pack a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t285

Overview

alt text

MiP Robotics Platform

The MiP Robotic Platform is the first self-balancing robot that you get to control and with which you can play games. The MiP can drive, dance, plays games, battle with other MiPs, respond to simple hand motions and can be remotely controlled by a compatible iOS or Android device. But did you know you can hack it?

alt text

Hacking Port Exposed!

The hacking port breaks out the following signals: * GND - A ground connection to the battery on the MiP * RX - A 3.3v signal level UART receive pin * TX - A 3.3v signal level UART transmit pin * 6v (Battery) - Raw battery power

Required Materials

There are a few components that you will need in order to exploit that port.

Once you have all the parts you need, let’s get started!

Attaching the Proto Pack

Step 1. Remove Battery Pack

You want to make sure the MiP is powered off and the batteries are removed before we start hacking away.

alt text

Battery Pack Screw Locations

alt text

Battery Pack removed

Step 2. Drill and Remove Wheel Screws

Fortunately/unfortunately the manufacturer glued the screw caps on the wheels. Good for consumers, ad for hacking. Take your favorite drilling device, and carefully create a hole in the wheel. This will expose enough of the screw head to get a phillips head screw driver to the screw head. I found that a 3/16" drill bit works great. I have also used a Dremel rotary tool to grind out the plug. NOTE: Remember to drill both sides.

alt text

Drilling for Wheel Screws

Step 3. Remove Wheels

Using a small phillips screwdriver, remove both wheels. If the holes you drilled were small enough, the screws will stay in the wheels.

Step 4. Remove the Eight (8) Body Screws.

Remove the 8 body screws that hold the two halves of the MiP together (be sure not to lose the screws so you can put it back together). NOTE: The wheels should already be removed, disregard them in this photo.

alt text

Body Screw Locations

Step 5. Remove Electrical Connections

There are three cables to remove. They are all different enough that it shoudl be obvious where each is replaced. Here is a quick overview of what each cable is for.

alt text

Connections of a MiP

Step 6. Make a hole for the hacking cable

Here is where you will need a rotary tool or some skill with a drill. You need to create a hole in the back to allow the hacking cable to pass through the shell. This doesn’t have to look pretty, it will be covered up later.

alt text

Make a hole that looks kinda like that, “just kinda funny lookin' ”

alt text

“Steady now, easy does it”

Step 7. Solder the Connector to the Proto-Pack

Solder the 4-pin connector to the back of the Proto-Pack. The front side has a Sparkfun and OSHW logo. The backside does not. NOTE: Pay close attention to the orientation of the connector. There is a small groove located on the bottom of the connector, this groove should be pointed towards the outside of the board as shown below.

alt text

Step 8. Remove the Battery Pack Plate

Remove the three screws that hold the back plate on. It’s not necessary to keep these screws.

alt text

Remove Screws to Make Room for Proto-Pack

Step 9. Assembling the Battery Holder

Using the 4-40 screws and nuts, re-assemble the Battery Holder by replacing the back plate with the Proto-Pack. Make sure the 4-pin connector is facing towards the Battery socket.

alt text

Assembled Battery Holder

Step 10. Re-assemble the MiP

Before re-placing the back shell, plug in the Expansion Cable. Thread the Expansion Cable through the hole you created in Step 5. Replace the 8 screws that were removed in Step 4. Replace the two wheels.

alt text

Expansion Cable Exposed

Step 11. Did you forget the Arms?

I managed to re-assemble my MiP with out arms… It happens.

alt text

No Arms…

alt text

Where did I put them?!

Step 12. Final Assembly

First make sure the Expansion Cable is exposed. Then plug this into the assembled battery holder. Once the connection is made, simply replace the battery holder and use the three M3 x 12mm screws to complete assembly. NOTE: Don’t forget to install the 4xAAA batteries

alt text

Final Assembly Components

alt text

Inserting the Expansion Cable

Step 13. You’re Done!

Admire your fine craftsmanship and start hacking!

alt text

Installed Proto Pack

Resources and Going Further

Now that you are ready to hack you may be interested in some of these other tutorials:


learn.sparkfun.com |CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

Viewing all 1123 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>