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

Soil Moisture-Sensing Solar Light

$
0
0

Soil Moisture-Sensing Solar Light a learn.sparkfun.com tutorial

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

Getting started

soil moisture sensing pathway light

In this tutorial, we are going to take a simple solar powered pathway light from a department store and rewire it to be a soil moisture sensor.

For this tutorial, I purchased a $2 solar pathway light from Mcguckins Hardware, but most any standard solar pathway light should do the trick.As far as the circuitry goes, most path lights use a very specialized chip, for which a datasheet can be difficult to find. The chip in my path light was an XY8018 which was set up with an inductor, the solar panel, an LED and a nickel-cadmium rechargeable battery. It seems others have had the same issue identifying the IC. While it’s always wise to know what you’re working with, this project is easy to accomplish without that information.

Materials Used:

Tools Used:

Other Materials You Could Use:

Suggested Reading

Circuitry

original solar light schematic

Schematic of the original solar light circuit.

The pathway light chip (the XY8018 here), in its original circuit is meant to turn on an LED when the solar panel is not receiving light, acting like a short circuit (or “high”), and turn off the LED and have the solar panel charge the battery when the solar panel is receiving light (or “low”). Using this information about how the chip functions we can rewire our probes to the chip to be the dictating factor to whether the LED is on or not.

Altered schematic with soil moisture detection probes

To set up a circuit that will turn the LED on when the soil is dry, we can wire one probe to pin 3 of the chip, where the solar panel was hooked up, and the other to ground, which will allow the LED to turn on when there is a high resistance between ground and pin 3 (when there is less water between the probes). The LED will turn off when there is more water between the probes and the resistance decreases between pin 3 and ground, pulling it low.

Probes

For my probes, I choose to use a small perf board, with all of its holes routed together, on both sides. I chose it because it was what I had laying around and it had a large conducting surface area. I cut it in half to make the two probes. The two halves where then hot glued to the end of the pathway light. Last, wires where piped through the shaft to be soldered to the probes from the main circuit.

soil moisture detecting probes

The probes could be made of many other things as well. Galvanized nails, a PCB board with copper tape on them, two steal rods, and other like things would also work fine as probes. Some things you should consider when choosing your probes is how moist your soil will be and if corrosion is going to become a large factor. If so, you might want to go with a metal that is less likely to corrode, such as galvanized steel. Also, you can encase your probes in a gypsum plaster to help prevent corrosion and keep your probes at a set distance.

Rewiring

The good news is that this IC works as is, even with our modification, so it requires no reprogramming whatsoever. That is also the bad news, since you cannot change the threshold at which the LED will illuminate. To change the threshold, you can move your probes closer together or further away. The closer they are, they better they will be at sensing small amounts of water, so the LED will only turn on when the soil is very very dry. The further apart the probes are, the more water that is needed to turn off the LED. Play around with your soil type, and what levels you would like your LED to turn on and off, and decide from there the spacing and possibly what type of probe you would like to use.

The only other thing I wanted this circuit to do was to always have the solar panel charging the battery. To accomplish that, wire the solar panel in parallel with the battery by soldering the solar panel wire that was attached to pin 3 to the ground side of the battery. This makes the final circuit look like this:

alt text

Final hacked soil sensor circuit.

Putting it all together

The insides of the hacked soil sensor

The insides of the hacked soil sensor.

I kept the same PCB found in the pathway light and rewired the solar panel directly to the board. I added some wires straight from the PCB to lead down to my circuit board probes that I hot glued to the pathway light stand. This worked for me, but you could certainly use a new board in the pathway light to make soldering the parts together easier, though space is a constraint.

There are many other things you could add to this simple circuit if you like. The main constraint is due to the fact that it’s running off of a solar panel and battery, and it can not produce a whole lot of current. Keep that in mind if you decide to build your own version.

Resources and Going Further

There are countless solar pathway lights and a number of ways to hack them. We’d love to see what kind of solar hacks you can come up with.

Want more fun in the sun? Check out these other SparkFun products and tutorials.

  • The Botanicalls Kit allows your plants to tweet you when they’re getting too dry.
  • The Sunny Buddy Hookup Guide will teach you how to incorporate solar charging and power into your next electronics project.
  • Add soil moisture readings to your weather station using what you learned in this tutorial.

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


Soil moisture-sensing by hacking a solar light

$
0
0

Soil moisture-sensing by hacking a solar light a learn.sparkfun.com tutorial

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

Getting started

soil moisture sensing pathway light

In this tutorial, we are going to take a simple solar powered pathway light from a department store and rewire it to be a soil moisture sensor. The finished design will turn on an LED when the soil dries up.

For this tutorial, I purchased a $2 solar pathway light from McGuckins Hardware, but most any standard solar pathway light should do the trick. As far as the circuitry goes, most path lights use a very specialized chip, for which a datasheet can be difficult to find. The chip in my path light was an XY8018 which was set up with an inductor, the solar panel, an LED and a Nickel-Cadmium rechargeable battery. It seems others have had the same issue identifying the IC. While it’s always wise to know what you’re working with, this project is easy to accomplish without that information.

Materials Used:

Tools Used:

Other Materials You Could Use:

Suggested Reading

Circuitry

original solar light schematic

Schematic of the original solar light circuit.

The pathway light chip (the XY8018 here), in its original circuit is meant to turn on an LED when the solar panel is not receiving light, acting like a short circuit (or “high”), and turn off the LED and have the solar panel charge the battery when the solar panel is receiving light (or “low”). Using this information about how the chip functions we can rewire our probes to the chip to be the dictating factor to whether the LED is on or not.

Altered schematic with soil moisture detection probes

To set up a circuit that will turn the LED on when the soil is dry, we can wire one probe to pin 3 of the chip, where the solar panel was hooked up, and the other to ground, which will allow the LED to turn on when there is a high resistance between ground and pin 3 (when there is less water between the probes). The LED will turn off when there is more water between the probes and the resistance decreases between pin 3 and ground, pulling it low.

Probes

For my probes, I choose to use a small perf board, with all of its holes routed together, on both sides. I chose it because it was what I had laying around and it had a large conducting surface area. I cut it in half to make the two probes. The two halves where then hot glued to the end of the pathway light. Last, wires where piped through the shaft to be soldered to the probes from the main circuit.

soil moisture detecting probes

The probes could be made of many other things as well. Galvanized nails, a PCB board with copper tape on them, two steel rods, and other like things would also work fine as probes. Some things you should consider when choosing your probes is how moist your soil will be and if corrosion is going to become a large factor. If so, you might want to go with a metal that is less likely to corrode, such as galvanized steel. Also, you can encase your probes in a gypsum plaster to help prevent corrosion and keep your probes at a set distance.

Rewiring

The good news is that this IC works as is, even with our modification, so it requires no reprogramming whatsoever. That is also the bad news, since you cannot change the threshold at which the LED will illuminate. To change the threshold, you can move your probes closer together or further away. The closer they are, they better they will be at sensing small amounts of water, so the LED will only turn on when the soil is very very dry. The further apart the probes are, the more water that is needed to turn off the LED. Play around with your soil type, and what levels you would like your LED to turn on and off, and decide from there the spacing and possibly what type of probe you would like to use.

The only other thing I wanted this circuit to do was to always have the solar panel charging the battery. To accomplish that, wire the solar panel in parallel with the battery by soldering the solar panel wire that was attached to pin 3 to the ground side of the battery. This makes the final circuit look like this:

alt text

Final hacked soil sensor circuit.

Usually for a more complex circuit, or a different battery such as a Lithum-ion battery, you would not want to hook up the power source directly to charge the battery like this, since overcharging is an issue. Here that issue is small, and even if the battery was overcharge it shouldn’t explode or anything, just decrease the lifetime of the battery. So it’s not very good practice to wire the solar panel to the battery like this, but for our purposes here it works.

Putting it all together

The insides of the hacked soil sensor

The insides of the hacked soil sensor.

I kept the same PCB found in the pathway light and rewired the solar panel directly to the board. I added some wires straight from the PCB to lead down to my circuit board probes that I hot glued to the pathway light stand. This worked for me, but you could certainly use a new board in the pathway light to make soldering the parts together easier, though space is a constraint.

There are many other things you could add to this simple circuit if you like. The main constraint is due to the fact that it’s running off of a solar panel and battery, and it can not produce a whole lot of current. Keep that in mind if you decide to build your own version.

Resources and Going Further

There are countless solar pathway lights and a number of ways to hack them. We’d love to see what kind of solar hacks you can come up with.

Want more fun in the sun? Check out these other SparkFun products and tutorials.

  • The Botanicalls Kit allows your plants to tweet you when they’re getting too dry.
  • The Sunny Buddy Hookup Guide will teach you how to incorporate solar charging and power into your next electronics project.
  • Add soil moisture readings to your weather station using what you learned in this tutorial.

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

Hackers in Residence - The ElectricBone

$
0
0

Hackers in Residence - The ElectricBone a learn.sparkfun.com tutorial

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

Introduction

Before I begin, I’d like to thank SparkFun for having me here and all the nice people that made this Hacker-in-Residence such a great experience. In particular, I’d like to thank Toni Klopfenstein for being there all the time and getting everything I needed for the project. Also, many thanks to Byron Jacquot for all the advice, help and “crash course” on PureData; to Shawn Hymel for introducing me to the RaspberryPi; to Jiffer Harriman (CU) for helping me with PD logic; and of course to Evan Spitler, mech shop wizard, for patiently helping me build my crazy trombone.

The ElectricBone

My idea for this project was to use electronics to create a musical instrument that someone could play like a trombone but would produce synthetic sounds. Like any other brass instruments, a trombone is a long open pipe that is played by buzzing one’s lips inside it, through a mouthpiece. The instrument then resonates in response, amplifying and modifying the sound. The length of the pipe determines the pitches that can be produced. These are basically harmonic partials starting from a fundamental frequency for each pipe length. What makes the trombone unique among the other brass instruments is that it uses a slide to change the length of the pipe and reach all possible notes. Thus, in order to implement my “trombone interface”, I needed to keep track of two things: lip vibration and slide movement.

Covered in this Tutorial

In this tutorial we will go over:

  • What electronic hardware worked best for this application
  • How to replicate a trombone with mechanical parts
  • How to connect everything together with software and embedded firmware
  • How to put everything together in one complete package

Suggested Reading

If you plan on following along at home, make sure you are familiar with the following concepts before continuing.

Planning it Out

Measuring the slide positions was fairly straight forward. There are a number of distance sensing technologies available, and during these two weeks at SparkFun, I also learned of some possibilities I’d never heard about. To control the basic shape of the note, I needed to identify its beginning, its end, and its intensity curve, from the lip’s vibration. That part turned out pretty easy using the Sound Detector sensor.

Determining the pitch from that buzzing, however, was a much more challenging task. After considering many suggestions by the engineering folks here at SFE, it became clear that I would need some extra firepower. So on top of an Arduino to control the I/O, the project also included a Raspberry Pi to handle the heavy lifting of pitch detection. We began by modeling the problem in PureData on a regular computer. We created a bank of adjustable bandpass filters to identify the most likely harmonic candidate. The plan was to then install the software on the Pi, however, despite some very promising results with the PD filters, that portion of the project had to be postponed due to time constraints. Instead, I “cheated” by including a Softpot as a hand control for pitch. Also, in this first version, I made the instrument send MIDI commands to an external synthesizer, which in turn produces the actual sounds.

Pure Data diagram

Pure Data adjustable bandpass filters.

Electronics Assembly

The basic design of the ElectricBone is quite simple. A Redboard controls an ultrasonic distance sensor (HC-RS04), a Sound Detector and a Softpot. The distance sensor uses two digital pins on the microcontroller: one for triggering an ultrasonic pulse and one for receiving the echo. The Sound Detector has three output pins, of which I used two: gate and envelope. The gate pin connects to a digital pin on the Redboard and the envelope connects to an analog pin. The Softpot’s output goes on a second analog input. On top of this basic circuit, there are two additional components: a Serial Enabled LCD, using Softserial on a ordinary digital pin, and a MIDI connector attached to the built-in serial ports. Finally there is a button for switching output modes.

Fritzing Diagram

The Redboard listens to the gate pin from the Sound Detector to know when the player’s lips start to vibrate. If it gets a hit, it starts to track the slide position through the distance sensor and harmonic number with the Softpot, which is operated by the player’s left thumb. By combining the two pieces of information (slide position and harmonic), the Redboard can determine which note needs to be played, so it issues a “Note On” message to the MIDI port. After the note start, it begins to track the envelope pin in order to control the intensity of the note. When the gate pin reads low, the Redboard sends out a MIDI “Note Off”, and the sound is terminated.

Mechanical Assembly

The mechanical structure for the instrument uses a few different materials. The main handle and the slide stay are made of wood. As is the plate for attaching the control box. The slide itself employs two different layers: an inner slide made of brass pipe (9/16") and a piece of PVC pipe (½") as the outer slide. Besides these, there are two acrylic plates carved with a laser cutter: one serves as a mounting rack for the ultrasonic sensor and the other as the deflector. All the pieces are assembled with screws or pressure.

alt text

alt text

The inner slide is attached to the main handle and the outer one to the other handle, both firmly placed into tight holes on the wood. The acrilic plates for the distance sensor go on top of each of these handles. This allows a slide action which is very similar to what a player would get with an actual trombone, plus it keeps the distance sensor at a constant straight angle with the bouncing plate, helping avoid false readings. Besides the slide attachment point, another hole on the other side of the main handle receives the mouthpiece. A third, lateral hole is used to attach the Sound Sensor in the same area, in order to catch the lips' vibration.

alt text

alt text

Enclosure

The brains of the project go into a Flanged Red Enclosure. The Redboard and LCD are mounted on the enclosure’s lid, leaving lots of room for the future installation of the Raspberry Pi and sound shield, for audio processing. A few openings on the right side of the box expose the MIDI connector and the USB and power connectors from the Redboard. On the other side the box receives all the wires from the sensors.

SparkFun Red enclosure

In general, when mounting a project like this in place, I prefer not to use breadboards, but rather plug the pins directly into the Arduino. However, since every component in this project requires power and ground, I needed somewhere to plug all these pins. The solution was to strip the power rails off a small breadboard and stick them to the box’s lid. This left me with lots of power/ground attaching points, without wasting much space. Another trick helped to keep the wire mess to a minimum. All the wires were color-coded and grouped together with heat shrink tubing.

Insides of the enclosure

And here is the finished product…

alt text

Firmware

The ElectricBone sketch, found here, defines three output modes, which can be toggled by the small button installed on the control box. Of these three modes, only the first one, MIDI Mode, is currently implemented. After a few lines of debouncing code for the mode button, the sketch switches on the selected mode to decide how to produce sounds.

In order to make the Arduino code more manageable, I split it into a few independent blocks which went inside separate functions. This way it is possible to visualize the entire algorithm at once just by glancing at the main loop.

The first of these functions, gateStatus(), returns the current status of the gate pin. If the pin just turned HIGH after being LOW, gateStatus() returns GATE_START. If the pin just turned LOW after being HIGH, the function returns GATE_END. While between a START and an END, gateSatus() will return GATE_ON. When there is no gate activity, the function returns GATE_OFF. Switching on the output of this function consitutes the basic skeleton for the ElectricBone algorithm.

From there, all we have to do is call the other functions to retrieve the current state of the sensors: trackSlide() returns the slide position in cm; slidePosition() calculates the position number for the value received from trackSlide(); harmonic() gets a harmonic number from the current Softpot input; pitchNumber() picks a MIDI note number based on the slide position and harmonic number. Once we have that information we send a message to the MIDI port using sendMIDI(). When gateStatus reports a GATE_END, the code sends Note Off to MIDI.

Resources and Going Further

This first experiment with trombone simulation was certainly not comprehensive, but served as proof of concept for the project. Obviously, the implementation, even at this early stage calls for many improvements, on which I will work from now on, as time allows. To start with, the sensitivity of the Sound Detector needs to be adjusted to work better with the mouthpiece buzzing. I also need to figure out a meaningful way to associate the envelope information with standard MIDI events, in order to use traditional synthesizers for output. Another improvement on output would be to implement trombone glissandi with pitchbend messages. Then, of course, there is the pitch detection algorithm, which will allow the player to control sound entirely from blowing/buzzing into it. This will involve perfecting the Puredata code, making it work on the Pi, and connecting all that with the Arduino-controlled sensors. Hopefully, with lots of work (and some luck), this prototype will become an actual, expressive musical instrument in the near future… and I can’t wait to start making music with it!

alt text

Carlos and part of the SFE Engineering Team

For more music related fun, check out these other SparkFun tutorials:


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

Transistors

$
0
0

Transistors a learn.sparkfun.com tutorial

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

Introduction

Transistors make our electronics world go ‘round. They’re critical as a control source in just about every modern circuit. Sometimes you see them, but more-often-than-not they’re hidden deep within the die of an integrated circuit. In this tutorial we’ll introduce you to the basics of the most common transistor around: the bi-polar junction transistor (BJT).

Introduction image

In small, discrete quantities, transistors can be used to create simple electronic switches, digital logic, and signal amplifying circuits. In quantities of thousands, millions, and even billions, transistors are interconnected and embedded into tiny chips to create computer memories, microprocessors, and other complex ICs.

Covered In This Tutorial

After reading through this tutorial, we want you to have a broad understanding of how transistors work. We won’t dig too deeply into semiconductor physics or equivalent models, but we’ll get deep enough into the subject that you’ll understand how a transistor can be used as either a switch or amplifier.

This tutorial is split into a series of sections, covering:

There are two types of basic transistor out there: bi-polar junction (BJT) and metal-oxide field-effect (MOSFET). In this tutorial we’ll focus on the BJT, because it’s slightly easier to understand. Digging even deeper into transistor types, there are actually two versions of the BJT: NPN and PNP. We’ll turn our focus even sharper by limiting our early discussion to the NPN. By narrowing our focus down – getting a solid understanding of the NPN – it’ll be easier to understand the PNP (or MOSFETS, even) by comparing how it differs from the NPN.

Suggested Reading

Before digging into this tutorial, we’d highly recommend giving these tutorials a look-through:

  • Voltage, Current, Resistance, and Ohm’s Law– An introduction to the fundamentals of electronics.
  • Electricity Basics– We’ll talk a bit about electricity as the flow of electrons. Find out how those electrons flow in this tutorial.
  • Electric Power– One of the transistors main applications is amplifying – increasing the power of a signal. Increasing power means we can increase either current or voltage, find out why in this tutorial.
  • Diodes– A transistor is a semiconductor device, just like a diode. In a way, it’s what you’d get if you stacked two diodes together, and tied their anodes together. Understanding how a diode works will go a long way towards uncovering the operation of a transistor.

Symbols, Pins, and Construction

Transistors are fundamentally three-terminal devices. On a bi-polar junction transistor (BJT), those pins are labeled collector (C), base (B), and emitter (E). The circuit symbols for both the NPN and PNP BJT are below:

NPN and PNP symbols

The only difference between an NPN and PNP is the direction of the arrow on the emitter. The arrow on an NPN points out, and on the PNP it points in. A useful mnemonic for remembering which is which is:

NPN: Not Pointing iN

Backwards logic, but it works!

Transistor Construction

Transistors rely on semiconductors to work their magic. A semiconductor is a material that’s not quite a pure conductor (like copper wire) but also not an insulator (like air). The conductivity of a semiconductor – how easily it allows electrons to flow – depends on variables like temperature or the presence of more or less electrons. Let’s look briefly under the hood of a transistor. Don’t worry, we won’t dig too deeply into quantum physics.

A Transistor as Two Diodes

Transistors are kind of like an extension of another semiconductor component: diodes. In a way transistors are just two diodes with their cathodes (or anodes) tied together:

Transistors as two diodes

The diode connecting base to emitter is the important one here; it matches the direction of the arrow on the schematic symbol, and shows you which way current is intended to flow through the transistor.

The diode representation is a good place to start, but it’s far from accurate. Don’t base your understanding of a transistor’s operation on that model (and definitely don’t try to replicate it on a breadboard, it won’t work). There’s a whole lot of weird quantum physics level stuff controlling the interactions between the three terminals.

(This model is useful if you need to test a transistor. Using the diode (or resistance) test function on a multimeter, you can measure across the BE and BC terminals to check for the presence of those “diodes”.)

Transistor Structure and Operation

Transistors are built by stacking three different layers of semiconductor material together. Some of those layers have extra electrons added to them (a process called “doping”), and others have electrons removed (doped with “holes” – the absence of electrons). A semiconductor material with extra electrons is called an n-type (n for negative because electrons have a negative charge) and a material with electrons removed is called a p-type (for positive). Transistors are created by either stacking an n on top of a p on top of an n, or p over n over p.

Simplified NPN construction

Simplified diagram of the structure of an NPN. Notice the origin of any acronyms?

With some hand waving, we can say electrons can easily flow from n regions to p regions, as long as they have a little force (voltage) to push them. But flowing from a p region to an n region is really hard (requires a lot of voltage). But the special thing about a transistor – the part that makes our two-diode model obsolete – is the fact that electrons can easily flow from the p-type base to the n-type collector as long as the base-emitter junction is forward biased (meaning the base is at a higher voltage than the emitter).

Active transistor current flow

The NPN transistor is designed to pass electrons from the emitter to the collector (so conventional current flows from collector to emitter). The emitter “emits” electrons into the base, which controls the number of electrons the emitter emits. Most of the electrons emitted are “collected” by the collector, which sends them along to the next part of the circuit.

A PNP works in a same but opposite fashion. The base still controls current flow, but that current flows in the opposite direction – from emitter to collector. Instead of electrons, the emitter emits “holes” (a conceptual absence of electrons) which are collected by the collector.


The transistor is kind of like an electron valve. The base pin is like a handle you might adjust to allow more or less electrons to flow from emitter to collector. Let’s investigate this analogy further…

Extending the Water Analogy

If you’ve been reading a lot of electricity concept tutorials lately, you’re probably used to wateranalogies. We say that current is analogous to the flow rate of water, voltage is the pressure pushing that water through a pipe, and resistance is the width of the pipe.

water analogies for current, voltage, and resistance

Unsurprisingly, the water analogy can be extended to transistors as well: a transistor is like a water valve– a mechanism we can use to control the flow rate.

There are three states we can use a valve in, each of which has a different effect on the flow rate in a system.

1) On – Short Circuit

A valve can be completely opened, allowing water to flow freely– passing through as if the valve wasn’t even present.

Valve open, water flowing, short circuit

Likewise, under the right circumstances, a transistor can look like a short circuit between the collector and emitter pins. Current is free to flow through the collector, and out the emitter.

2) Off – Open Circuit

When it’s closed, a valve can completely stop the flow of water.

valve closed, water stopped, open circuit

In the same way, a transistor can be used to create an open circuit between the collector and emitter pins.

3) Linear Flow Control

With some precise tuning, a valve can be adjusted to finely control the flow rate to some point between fully open and closed.

Valve half-open, water flow rate controlled

A transistor can do the same thing – linearly controlling the current through a circuit at some point between fully off (an open circuit) and fully on (a short circuit).

From our water analogy, the width of a pipe is similar to the resistance in a circuit. If a valve can finely adjust the width of a pipe, then a transistor can finely adjust the resistance between collector and emitter. So, in a way, a transistor is like a variable, adjustable resistor.

Amplifying Power

There’s another analogy we can wrench into this. Imagine if, with the slight turn of a valve, you could control the flow rate of the Hoover Dam’s flow gates. The measly amount of force you might put into twisting that knob has the potential to create a force thousands of times stronger. We’re stretching the analogy to its limits, but this idea carries over to transistors too. Transistors are special because they can amplify electrical signals, turning a low-power signal into a similar signal of much higher power.


Kind of. There’s a lot more to it, but that’s a good place to start! Check out the next section for a more detailed explanation of the operation of a transistor.

Operation Modes

Unlike resistors, which enforce a linear relationship between voltage and current, transistors are non-linear devices. They have four distinct modes of operation, which describe the current flowing through them. (When we talk about current flow through a transistor, we usually mean current flowing from collector to emitter of an NPN.)

The four transistor operation modes are:

  • Saturation– The transistor acts like a short circuit. Current freely flows from collector to emitter.
  • Cut-off– The transistor acts like an open circuit. No current flows from collector to emitter.
  • Active– The current from collector to emitter is proportional to the current flowing into the base.
  • Reverse-Active– Like active mode, the current is proportional to the base current, but it flows in reverse. Current flows from emitter to current (not, exactly, the purpose transistors were designed for).

To determine which mode a transistor is in, we need to look at the voltages on each of the three pins, and how they relate to each other. The voltages from base to emitter (VBE), and the from base to collector (VBC) set the transistor’s mode:

Mode Quadrants

The simplified quadrant graph above shows how positive and negative voltages at those terminals affect the mode. In reality it’s a bit more complicated than that.

Let’s look at all four transistor modes individually; we’ll investigate how to put the device into that mode, and what effect it has on current flow.

Note: The majority of this page focuses on NPN transistors. To understand how a PNP transistor works, simply flip the polarity or > and < signs.

Saturation Mode

Saturation is the on mode of a transistor. A transistor in saturation mode acts like a short circuit between collector and emitter.

Saturation mode model

In saturation mode both of the “diodes” in the transistor are forward biased. That means VBE must be greater than 0, and so must VBC. In other words, VB must be higher than both VE and VC.

Saturation mode voltage relations

Because the junction from base to emitter looks just like a diode, in reality, VBE must be greater than a threshold voltage to enter saturation. There are many abbreviations for this voltage drop – Vth, Vγ, and Vd are a few – and the actual value varies between transistors (and even further by temperature). For a lot of transistors (at room temperature) we can estimate this drop to be about 0.6V.

Another reality bummer: there won’t be perfect conduction between emitter and collector. A small voltage drop will form between those nodes. Transistor datasheets will define this voltage as CE saturation voltage VCE(sat)– a voltage from collector to emitter required for saturation. This value is usually around 0.05-0.2V. This value means that VC must be slightly greater than VE (but both still less than VB) to get the transistor in saturation mode.

Cutoff Mode

Cutoff mode is the opposite of saturation. A transistor in cutoff mode is off– there is no collector current, and therefore no emitter current. It almost looks like an open circuit.

Cutoff mode model

To get a transistor into cutoff mode, the base voltage must be less than both the emitter and collector voltages. VBC and VBE must both be negative.

Cutoff mode voltage relations

In reality, VBE can be anywhere between 0V and Vth (~0.6V) to achieve cutoff mode.

Active Mode

To operate in active mode, a transistor’s VBE must be greater than zero and VBC must be negative. Thus, the base voltage must be less than the collector, but greater than the emitter. That also means the collector must be greater than the emitter.

V_{C} > V_{B} > V_{E}

In reality, we need a non-zero forward voltage drop (abbreviated either Vth, Vγ, or Vd) from base to emitter (VBE) to “turn on” the transistor. Usually this voltage is usually around 0.6V.

Amplifying in Active Mode

Active mode is the most powerful mode of the transistor because it turns the device into an amplifier. Current going into the base pin amplifies current going into the collector and out the emitter.

Our shorthand notation for the gain (amplification factor) of a transistor is β (you may also see it as βF, or hFE). β linearly relates the collector current (IC) to the base current (IB):

I_{C} = \beta I_{B}

The actual value of β varies by transistor. It’s usually around 100, but can range from 50 to 200…even 2000, depending on which transistor you’re using and how much current is running through it. If your transistor had a β of 100, for example, that’d mean an input current of 1mA into the base could produce 100mA current through the collector.

Active mode model

Active mode model. VBE = Vth, and IC = βIB.

What about the emitter current, IE? In active mode, the collector and base currents go into the device, and the IE comes out. To relate the emitter current to collector current, we have another constant value: α. α is the common-base current gain, it relates those currents as such:

I_{C}= \alpha I_{E}

α is usually very close to, but less than, 1. That means IC is very close to, but less than IE in active mode.

You can use β to calculate α, or vice-versa:

\beta=\frac{\alpha}{(1-\alpha), alpha=\frac{\beta}{\beta+1}

If β is 100, for example, that means α is 0.99. So, if IC is 100mA, for example, then IE is 101mA.

Reverse Active

Just as saturation is the opposite of cutoff, reverse active mode is the opposite of active mode. A transistor in reverse active mode conducts, even amplifies, but current flows in the opposite direction, from emitter to collector. The downside to reverse active mode is the β (βR in this case) is much smaller.

To put a transistor in reverse active mode, the emitter voltage must be greater than the base, which must be greater than the collector (VBE<0 and VBC>0).

V_{C} < V_{B} < V_{E}

Reverse active mode isn’t usually a state in which you want to drive a transistor. It’s good to know it’s there, but it’s rarely designed into an application.

Relating to the PNP

After everything we’ve talked about on this page, we’ve still only covered half of the BJT spectrum. What about PNP transistors? PNP’s work a lot like the NPN’s – they have the same four modes – but everything is turned around. To find out which mode a PNP transistor is in, reverse all of the < and > signs.

For example, to put a PNP into saturation VC and VE must be higher than VB. You pull the base low to turn the PNP on, and make it higher than the collector and emitter to turn it off. And, to put a PNP into active mode, VE must be at a higher voltage than VB, which must be higher than VC.

In summary:

Voltage relationsNPN ModePNP Mode
VE< VB< VCActiveReverse
VE< VB> VCSaturationCutoff
VE> VB< VCCutoffSaturation
VE> VB> VCReverseActive

Another opposing characteristic of the NPNs and PNPs is the direction of current flow. In active and saturation modes, current in a PNP flows from emitter to collector. This means the emitter must generally be at a higher voltage than the collector.


If you’re burnt out on conceptual stuff, take a trip to the next section. The best way to learn how a transistor works is to examine it in real-life circuits. Let’s look at some applications!

Applications I: Switches

One of the most fundamental applications of a transistor is using it to control the flow of power to another part of the circuit – using it as an electric switch. Driving it in either cutoff or saturation mode, the transistor can create the binary on/off effect of a switch.

Transistor switches are critical circuit-building blocks; they’re used to make logic gates, which go on to create microcontrollers, microprocessors, and other integrated circuits. Below are a few example circuits.

Transistor Switch

Let’s look at the most fundamental transistor-switch circuit: an NPN switch. Here we use an NPN to control a high-power LED:

NPN switch to control an LED

Our control input flows into the base, the output is tied to the collector, and the emitter is kept at a fixed voltage.

While a normal switch would require an actuator to be physically flipped, this switch is controlled by the voltage at the base pin. A microcontroller I/O pin, like those on an Arduino, can be programmed to go high or low to turn the LED on or off.

When the voltage at the base is greater than 0.6V (or whatever your transistor’s Vth might be), the transistor starts saturating and looks like a short circuit between collector and emitter. When the voltage at the base is less than 0.6V the transistor is in cutoff mode – no current flows because it looks like an open circuit between C and E.

The circuit above is called a low-side switch, because the switch – our transistor – is on the low (ground) side of the circuit. Alternatively, we can use a PNP transistor to create a high-side switch:

PNP switch example

Similar to the NPN circuit, the base is our input, and the emitter is tied to a constant voltage. This time however, the emitter is tied high, and the load is connected to the transistor on the ground side.

This circuit works just as well as the NPN-based switch, but there’s one huge difference: to turn the load “on” the base must be low. This can cause complications, especially if the load’s high voltage (VCC in this picture) is higher than our control input’s high voltage. For example, this circuit wouldn’t work if you were trying to use a 5V-operating Arduino to switch on a 12V motor. In that case it’d be impossible to turn the switch off because VB would always be less than VE.

Base Resistors!

You’ll notice that each of those circuits uses a series resistor between the control input and the base of the transistor. Don’t forget to add this resistor! A transistor without a resistor on the base is like an LED with no current-limiting resistor.

Recall that, in a way, a transistor is just a pair of interconnected diodes. We’re forward-biasing the base-emitter diode to turn the load on. The diode only needs 0.6V to turn on, more voltage than that means more current. Some transistors may only be rated for a maximum of 10-100mA of current to flow through them. If you supply a current over the maximum rating, the transistor might blow up.

The series resistor between our control source and the base limits current into the base. The base-emitter node can get its happy voltage drop of 0.6V, and the resistor can drop the remaining voltage. The value of the resistor, and voltage across it, will set the current.

Switching an LED with a transistor

The resistor needs to be large enough to effectively limit the current, but small enough to feed the base enough current. 1mA to 10mA will usually be enough, but check your transistor’s datasheet to make sure.

Digital Logic

Transistors can be combined to create all our fundamental logic gates: AND, OR, and NOT.

(Note: These days MOSFETS are more likely to be used to create logic gates than BJTs. MOSFETs are more power-efficient, which makes them the better choice.)

Inverter

Here’s a transistor circuit that implements an inverter, or NOT gate:

BJT inverter circuit

An inverter built out of transistors.

Here a high voltage into the base will turn the transistor on, which will effectively connect the collector to the emitter. Since the emitter is connected directly to ground, the collector will be as well (though it will be slightly higher, somewhere around VCE(sat) ~ 0.05-0.2V). If the input is low, on the other hand, the transistor looks like an open circuit, and the output is pulled up to VCC

(This is actually a fundamental transistor configuration called common emitter. More on that later.)

AND Gate

Here are a pair of transistors used to create a 2-input AND gate:

BJT AND circuit

2-input AND gate built out of transistors.

If either transistor is turned off, then the output at the second transistor’s collector will be pulled low. If both transistors are “on” (bases both high), then the output of the circuit is also high.

OR Gate

And, finally, here’s a 2-input OR gate:

BJT OR circuit

2-input OR gate built out of transistors.

In this circuit, if either (or both) A or B are high, that respective transistor will turn on, and pull the output high. If both transistors are off, then the output is pulled low through the resistor.

H-Bridge

An H-bridge is a transistor-based circuit capable of driving motors both clockwise and counter-clockwise. It’s an incredibly popular circuit – the driving force behind countless robots that must be able to move both forward and backward.

Fundamentally, an H-bridge is a combination of four transistors with two inputs lines and two outputs:

alt text

Can you guess why it’s called an H bridge?

(Note: there’s usually quite a bit more to a well-designed H-bridge including flyback diodes, base resistors and Schmidt triggers.)

If both inputs are the same voltage, the outputs to the motor will be the same voltage, and the motor won’t be able to spin. But if the two inputs are opposite, the motor will spin in one direction or the other.

The H-bridge has a truth table that looks a little like this:

Input AInput BOutput AOutput BMotor Direction
0011Stopped (braking)
0110Clockwise
1001Counter-clockwise
1100Stopped (braking)

Oscillators

An oscillator is a circuit that produces a periodic signal that swings between a high and low voltage. Oscillators are used in all sorts of circuits: from simply blinking an LED to the producing a clock signal to drive a microcontroller. There are lots of ways to create an oscillator circuit including quartz crystals, op amps, and, of course, transistors.

Here’s an example oscillating circuit, which we call an astable multivibrator. By using feedback we can use a pair of transistors to create two complementing, oscillating signals.

Astable multivibrator

Aside from the two transistors, the capacitors are the real key to this circuit. The caps alternatively charge and discharge, which causes the two transistors to alternatively turn on and off.

Analyzing this circuit’s operation is an excellent study in the operation of both caps and transistors. To begin, assume C1 is fully charged (storing a voltage of about VCC), C2 is discharged, Q1 is on, and Q2 is off. Here’s what happens after that:

  • If Q1 is on, then C1’s left plate (on the schematic) is connected to about 0V. This will allow C1 to discharge through Q1’s collector.
  • While C1 is discharging, C2 quickly charges through the lower value resistor – R4.
  • Once C1 fully discharges, its right plate will be pulled up to about 0.6V, which will turn on Q2.
  • At this point we’ve swapped states: C1 is discharged, C2 is charged, Q1 is off, and Q2 is on. Now we do the same dance the other way.
  • Q2 being on allows C2 to discharge through Q2’s collector.
  • While Q1 is off, C1 can charge, relatively quickly through R1.
  • Once C2 fully discharges, Q1 will be turn back on and we’re back in the state we started in.

It can be hard to wrap your head around. You can find another excellent demo of this circuit here.

By picking specific values for C1, C2, R2, and R3 (and keeping R1 and R4 relatively low), we can set the speed of our multivibrator circuit:

alt text

So, with the values for caps and resistors set to 10µF and 47kΩ respectively, our oscillator frequency is about 1.5 Hz. That means each LED will blink about 1.5 times per second.


As you can probably already see, there are tons of circuits out there that make use of transistors. But we’ve barely scratched the surface. These examples mostly show how the transistor can be used in saturation and cut-off modes as a switch, but what about amplification? Time for more examples!

Applications II: Amplifiers

Some of the most powerful transistor applications involve amplification: turning a low power signal into one of higher power. Amplifiers can increase the voltage of a signal, taking something from the µV range and converting it to a more useful mV or V level. Or they can amplify current, useful for turning the µA of current produced by a photodiode into a current of much higher magnitude. There are even amplifiers that take a current in, and produce a higher voltage, or vice-versa (called transresistance and transconductance respectively).

Transistors are a key component to many amplifying circuits. There are a seemingly infinite variety of transistor amplifiers out there, but fortunately a lot of them are based on some of these more primitive circuits. Remember these circuits, and, hopefully, with a bit of pattern-matching, you can make sense of more complex amplifiers.

Common Configurations

Three of the most fundamental transistor amplifiers are: common emitter, common collector and common base. In each of the three configurations one of the three nodes is permanently tied to a common voltage (usually ground), and the other two nodes are either an input or output of the amplifier.

Common Emitter

Common emitter is one of the more popular transistor arrangements. In this circuit the emitter is tied to a voltage common to both the base and emitter (usually ground). The base becomes the signal input, and the collector becomes the output.

Common emitter model

The common emitter circuit is popular because it’s well-suited for voltage amplification, especially at low frequencies. They’re great for amplifying audio signals, for example. If you have a small 1.5V peak-to-peak input signal, you could amplify that to a much higher voltage using a slightly more complicated circuit, like:

Common emitter speaker amp

One quirk of the common emitter, though, is that it inverts the input signal (compare it to the inverter from the last page!). An input signal would be 180° out of phase with the output.

Common Collector (Emitter Follower)

If we tie the collector pin to a common voltage, use the base as an input, and the emitter as an output, we have a common collector. This configuration is also known as an emitter follower.

Common collector model

The common collector doesn’t do any voltage amplification (in fact, the voltage out will be 0.6V lower than the voltage in). For that reason, this circuit is sometimes called a voltage follower.

This circuit does have great potential as a current amplifier. In addition to that, the high current gain combined with near unity voltage gain makes this circuit a great voltage buffer. A voltage buffer prevents a load circuit from undesirably interfering with the circuit driving it.

For example, if you wanted to deliver 1V to a load, you could go the easy way and use a voltage divider, or you could use an emitter follower.

Common collector 1V out

As the load gets larger (which, conversely, means the resistance is lower) the output of the voltage divider circuit drops. But the voltage output of the emitter follower remains steady, regardless of what the load is. Bigger loads can’t “load down” an emitter follower, like they can circuits with larger output impedances.

Common Base

We’ll talk about common base to provide some closure to this section, but this is the least popular of the three fundamental configurations. In a common base amplifier, the emitter is an input and the collector an output. The base is common to both.

Common base model

Common base is like the anti-emitter-follower. It’s a decent voltage amplifier, and current in is about equal to current out (actually current in is slightly greater than current out).

The common base circuit works best as a current buffer. It can take an input current at a low input impedance, and deliver nearly that same current to a higher impedance output.

In Summary

These three amplifier configurations are at the heart of many more complicated transistor amplifiers. They each have applications where they shine, whether they’re amplifying current, voltage, or buffering.

Common EmitterCommon CollectorCommon Base
Voltage GainMediumLowHigh
Current GainMediumHighLow
Input ImpedanceMediumHighLow
Output ImpedanceMediumLowHigh

Multistage Amplifiers

We could go on and on about the great variety of transistor amplifiers out there. Here are a few quick examples to show off what happens when you combine the single-stage amplifiers above:

Darlington

The Darlington amplifier runs one common collector into another to create a high current gain amplifier.

Darlington pair

Voltage out is about the same as voltage in (minus about 1.2V-1.4V), but the current gain is the product of two transistor gains. That’s 2β, upwards of 1000!

The Darlington pair is a great tool if you need to drive a large load with a very small input current.

Differential Amplifier

A differential amplifier subtracts two input signals and amplifies that difference. It’s a critical part of feedback circuits, where the input is compared against the output, to produce a future output.

Here’s the foundation of the differential amp:

Differential amplifier -- long tailed pair

This circuit is also called a long tailed pair. It’s a pair of common-emitter circuits that are compared against each other to produce a differential output. Two inputs are applied to the bases of the transistors; the output is a differential voltage across the two collectors.

Push-Pull Amplifier

A push-pull amplifier is a useful “final stage” in many multi-stage amplifiers. It’s an energy efficient power amplifier, often used to drive loudspeakers.

The fundamental push-pull amp uses an NPN and PNP transistor, both configured as common collectors:

Push-pull amplifier

The push-pull amp doesn’t really amplify voltage (voltage out will be slightly less than that in), but it does amplify current. It’s especially useful in bi-polar circuits (those with positive and negative supplies), because it can both “push” current into the load from the positive supply, and “pull” current out and sink it into the negative supply.

If you have a bi-polar supply (or even if you don’t), the push-pull is a great final stage to an amplifier, acting as a buffer for the load.

Putting Them Together (An Operational Amplifier)

Let’s look at a classic example of a multi-stage transistor circuit: an Op Amp. Being able to recognize common transistor circuits, and understanding their purpose can get you a long way! Here is the circuit inside an LM3558, a really simple op amp:

LM358 circuit

The internals of an LM358 operational amplifier. Recognize some amplifiers?

There’s certainly more complexity here than you may be prepared to digest, however you might see some familiar topologies:

  • Q1, Q2, Q3, and Q4 form the input stage. Looks a lot like an common collector (Q1 and Q4) into a differential amplifier, right? It just looks upside down, because it’s using PNP’s. These transistors help to form the input differential stage of the amplifier.
  • Q11 and Q12 are part of the second stage. Q11 is a common collector and Q12 is a common emitter. This pair of transistors will buffer the signal from Q3’s collector, and provide a high gain as the signal goes to the final stage.
  • Q6 and Q13 are part of the final stage, and they should look familiar as well (especially if you ignore RSC) – it’s a push-pull! This stage buffers the output, allowing it to drive larger loads.
  • There are a variety of other common configurations in there that we haven’t talked about. Q8 and Q9 are configured as a current mirror, which simply copies the amount of current through one transistor into the other.

After this crash course in transistors, we wouldn’t expect you to understand what’s going on in this circuit, but if you can begin to identify common transistor circuits you’re on the right track!

Resources and Going Further

If you’re looking to get deeper into transistors, here are some resources we’d recommend:

  • Getting Started in Electronics by Forrest Mims– Mims is a master of explaining electronics in an easy-to-understand highly applicable manner. Definitely check this book out if you want a more in-depth introduction to transistors.
  • LTSpice and Falstad Circuit– These are free software tools you can use to simulate circuits. Digitally experimenting with circuits is a great way to learn. You get all of the experimentation, without the pain of breadboarding or fear of blowing stuff up. Try putting together some of the stuff we’ve talked about!
  • 2N3904 Datasheet– Another way to learn about transistors is to dig into their datasheet. The 2N3904 is a really common transistor that we use all the time (and the 2N3906 is its PNP sibling). Check out the datasheet, see if you recognize any familiar characteristics.

On top of that, our very own Director of Engineering, Pete, has produced a series of According to Pete videos with a focus on transistors and transistor amplifiers. Definitely check out his Diodes and Transistors video:

Then you can move on to: Transistor Biasing Configurations Part 1 and Part 2, and finally Current Mirrors. Great stuff!

Going Further

Or, if you’re itching to learn more about electronics in general, check out some of these SparkFun tutorials:

  • Integrated Circuits– What do you get when you combine thousands of transistors and stuff them in a black box? An IC!
  • Shift Registers– Shift registers are one of the most common integrated circuits around. Learn how you can use a transistor to blink dozens of LEDs with just a few inputs.
  • Mini FET Shield Hookup Guide– This is a really simple Arduino shield which uses 8 MOSFETs to control 8 high-current outputs. This is a good, real-life example of using a transistor as a switch.
  • Designing PCBs with EAGLE– Take your new transistor skills to the next level. Design them into a PCB! This tutorial explains how to use a freely available software (Eagle) to design PCBs.
  • How to Solder– If you design a PCB, though, you’ll need to know how to solder too. Learn how to through-hole solder in this tutorial.

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

Pocket AVR Programmer Hookup Guide

$
0
0

Pocket AVR Programmer Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Do you need more control over your AVRs? Whether it’s an ATmega328, ATmega32U4, ATtiny85, ATmega128RFA1, if it’s an AVR there’s a good chance the AVR Pocket Programmer can program it.

Pocket programmer angled

There are many reasons for programming your AVR via an in-system programmer (ISP). If your AVR doesn’t have a bootloader on it, it’s probably the only way to load code. Or maybe you want to overwrite the bootloader to squeeze out some extra flash space. Or maybe you want to poke at the fuse bits, to change the brown-out voltage. Or maybe you just want a faster and more reliable code upload.

Covered In This Tutorial

In this tutorial we will introduce you to all of the important aspects of the AVR Pocket Programmer. It’s split into a series of sections, which cover:

  • Board Overview– A look at the hardware components that make up the AVR Pocket Programmer.
  • Installing Drivers– How to install the AVR Pocket Programmers on a Windows machine (Mac and Linux users can skip this page).
  • Programming via Arduino– How to use the ubiquitous “easy-mode” AVR IDE to upload sketches via the AVR Pocket Programmer.
  • Using AVRDUDE– A more advanced, command-line-based approach to using the AVR Pocket Programmer.

Required Materials

Most importantly, to follow along with this tutorial, you will need an AVR Pocket Programmer and an AVR to program. On top of that, a mini-B USB cable is required to connect the Programmer to your computer.

Programming action shot

That microcontroller-to-be-programmed can be any AVR with 64K or less of flash. The ATmega328 on an Arduino Uno or RedBoard works perfectly, but the ATmega2560 of an Arduino Mega does not.

Beyond that, you may need something to interface the Programmer to your AVR. Here are some useful accessories, which might make the job easier:

  • Straight Male Headers– If you have an AVR on a development board – like an Arduino Pro– the 2x3 (or 2x5) ISP header may not be populated. You can use straight male headers (also available in a long-pinned version) to make a temporary contact between ISP cable and your dev board. There is also a 2x3 pin version.
  • ISP Pogo Adapter– Like the headers, this ISP adapter is designed to provide a temporary electrical connection between adapter and AVR. This is a great, more reliable alternative to the headers.
  • AVR Programming Adapter– If you AVR is living on a breadboard, you probably don’t have an interface to the standard 2x3 ISP pinout. This simple breakout board makes interfacing the programmer with your breadboarded circuit possible.

Suggested Reading

Whether you’re a beginner or experienced electronics enthusiast, the Pocket Programmer should be easy to get up-and-running. If you’ve programmed an Arduino before, you’ll be well-prepared for the next step. Here are some tutorials we’d recommend reading before continuing on with this one:

  • What is an Arduino?– If you’re unfamiliar with AVRs, check out this tutorial to learn about the most popular one of the lot.
  • Installing Arduino– Arduino isn’t required to use the Programmer, but it can make things easier, especially if you still want to program your AVR using the Arduino libraries.
  • Serial Peripheral Interface (SPI)– The Pocket Programmer uses an SPI interface to send data to and from the AVR. Click this tutorial to learn the meanings behind “MOSI”, “MISO”, and “SCK”.

Board Overview

Before we get to using the AVR Pocket Programmer, let’s quickly overview what components fill the board out:

Annotated AVR Pocket Programmer

  • USB Connector– This is your data and power input to the Programmer. A mini-B USB cable plugs in here and connects your computer to the Programmer.
  • 2x5 ISP Header– This shrouded header mates with the included Programming Cable, and allows you to send the programming signals out to your AVR. It’s polarized to make sure you can’t plug anything in backwards.
  • Power Target Switch– Unlike a lot of ISP’s out there, the AVR Pocket Programmer can deliver power to the AVR-to-be-programmed. Flick this switch to the “Power Target” side, to send 5V to the AVR. More on this below.
  • ATtiny2313– This is the chip that works the programming magic. It converts between USB and SPI to turn commands from your computer into words and instructions to load into your AVR-to-be-programmed. Unless you want to customize the Tiny ISP firmware, you can leave this chip alone.
    • The unpopulated ISP header, above the ATtiny2313, is broken out in case that chip needs to be programmed. It’s mostly used in production by those who program the programmers.
  • 74AC125 Buffer– This chip helps to add some protection to the programmer by buffering the data-line outputs. Another IC to mostly ignore.

The board also includes a variety of LEDs to indicate power, status, and data transfers.

AVR ISP Pinouts

AVRs are programmed through an SPI interface. There are six unique signals required for communication between ISP and AVR: VCC, GND, Reset, MOSI, MISO, and SCK.

To route those signals between devices, there are two standardized connectors – one 6-pin, 2x3 connector and another 10-pin, 2x5:

top avr isp pinouts

AVR ISP pinouts – top view.

The AVR Pocket Programmer includes an on-board 2x5 connector, and the included AVR Programming Cable terminates with both 2x5 and 2x3 connectors.

Power Target Switch

If you’re working with an AVR on a breadboard or a prototype, power may be hard to come by. The AVR Pocket Programmer allows you to route 5V out to your AVR. It can deliver upwards of 500mA before tripping the onboard PTC.

A closer look at the power-select switch

If the switch is in the Power Target position, it will route 5V out to your AVR. Otherwise, if the switch is pointing towards No Power, no signal will be connected to the 5V pin on the ISP connector.

Be careful using this feature! It will output 5V and only 5V! If you’re working with a 3.3V or 1.8V system, make sure this switch is in the No Power position.

Installing Drivers

Driver installation is required on Windows machines only. If you’re using Mac or Linux, feel free to click over to the next section. Otherwise, follow along below as we overview the installation process.

There are two sets of instruction for driver installation on this page. The first is the easiest, quickest method, and should work for most everyone. The second installation process is only required if the first one fails – it takes a more manual approach to the driver installation.

Install the Drivers Automatically with Zadig

To begin, plug the AVR Pocket Programmer into your computer. Upon initially connecting the board, Windows will try to automatically install the drivers. Some computers may be lucky, but most will turn up with a message notifying you that the driver install failed.

Click the link below to download the drivers:

Download the Zadig USBtiny Drivers

Use your favorite unzipper to extract the ZIP file. Don’t forget where you put the extracted folder!

After you’ve plugged the AVR Pocket Programmer into your computer and your machine has run through the process of checking for and failing to install drivers, proceed to the “zadig_v2.0.1.160” folder you just unzipped. Then Run zadig.exe.

Zadig is a wonderful tool that can install the drivers on just about any Windows platform out there. Upon opening the program, you should be greeted with a window like this:

Zadig screenshot

There are a few options to verify before installing the driver:

  • Select the device– The top dropbox controls which device you want to install the driver for. Hopefully you only have one option here, something like “Unknown Device #1”. If you have more than one option, check your device manager to see if you can make sense of which is which (plugging and unplugging a device usually helps).
  • Select the driver– Click the arrows in this box until you happen upon libusb-win32 (vx.x.x.x), that’s the driver we want to install.

After verifying those two selections, click “Install Driver”. The installation process can take a few minutes, but after you’ve watched the scroll bar zoom by countless times, you should be greeted with a “The driver was installed successfully” message.

If you were successful, close out of the Zadig program and proceed to the next section!

If Zadig didn’t work for you, check out the instructions below for help manually installing the drivers.


Manually Installing the libUSB Drivers

If, for some reason, Zadig didn’t work for you. Read the instructions below to manually install the drivers.

Note: If you are using a Windows 8 machine, before you can install the drivers you’ll need to disable driver signature enforcement. Follow along with our tutorial to turn that overzealous safety guard off for a minute.

Click the link below to download the drivers:

Download the USBtiny Drivers

Use your favorite unzipper to extract the ZIP file. Don’t forget where you put the extracted folder!

After you’ve plugged in the Programmer, and Windows has failed to install the driver. Follow these steps to install the driver:

  1. Open the Device Manager– There are a few routes to open up the device manager.
    • You can go to the Control Panel, then click Hardware and Sound, then click Device Manager.
      Opening device manager

    • Or, simply open the run tool (press Windows Key + R), and run devmgmt.msc.
  2. In the Device Manager, you should see an “Unknown device” listed under the “Other devices” tree. Right click “Unkown Device” and select Update driver software….
    Update driver software

  3. Click Browse my computer for driver software in the “Update Diver Software - Unknown Device” window that pops up.
    Browse for drivers

  4. Click “Browse…” and navigate to the “../usbtinyisp_libusb-win32_1.2.1.0” folder you just downloaded. Then click Next.
    Point to drivers

  5. Windows will begin installing the driver, and then immediately notify you that the driver isn’t signed. Click Install this driver software anyway option, to proceed with the installation.
    Driver signature check

  6. After a few moments, the driver should successfully install. You’ll be prompted with a “Windows has susccessfully updated your driver software” window. Close that, and you’ll see a “USBtiny” entry populated in the Device Manager, under the “LibUSB-Win32 Devices” tree.

Drivers verified in device manager

Congratulations! Proceed over to the next section, and we’ll start using the Programmer!


Breathe easy now! Once you’ve installed the USBTinyProgrammer drivers on your computer, you shouldn’t ever have to do it again. Now it’s time to program something!

Programming via Arduino

Arduino has a built-in tool that allows you to upload your sketch via a programmer instead of the serial bootloader. If you’re just taking your first steps toward ISP-ing your Arduino-compatible AVR, this is a good place to start.

Connect the Programmer

First, let’s connect the programmer to our Arduino. Most Arduinos break out the standardized 2x3 ISP header towards the edge of the board. Plug the 2x5-connector end of included programming cable into your AVR Pocket Programmer, then connect the other, 2x3 end into your Arduino.

Pay attention to the notch when connecting

Note the notch on the connector facing the same direction as pin 1 (marked with a small white line here) on the 2x3 Arduino connector.

When connecting the programming cable to you Arduino, make sure you match up the polarity! The cable has a “notch” on one side of the plastic housing. This should point towards pin 1 of the Arduino’s ISP header. Pin 1 is usually indicated by a stripe next to the hole or pin.

If your Arduino doesn’t have the ISP pins populated, check out the bottom section of this page for some tips and tricks we’ve used through the years.

Powering Target

While connecting your programmer, double-check to make sure the “Power Target” switch is in the correct position. The programmer can power your Arduino alone! If you want it to handle that task, slide it over to the Power Target position.

Powering the Arduino via Programmer

The “Power Target” feature is especially useful if you only have one USB slot/cable available.

Unplug your Arduino from USB if you’re going to power it via the Programmer – you don’t want to create any ugly reverse current flows through your power sources.

Programming via Arduino

Now that the programmer is connected to your Arduino, open up the IDE. Then open an example sketch like Blink (File > Examples > 1.Basics > Blink).

Before uploading, we need to tell Arduino which programmer we’re using. Go up to Tools>Programmer and select USBtinyISP.

Selecting the programmer

Also make sure you’ve set the “Board” option correctly! The serial port selection isn’t required for uploading the sketch, but is still necessary if you’re doing anything with the serial monitor.

To upload the sketch using the programmer you selected, go to File>Upload Using Programmer. If you’ll be doing this a lot, get used to pressing CTRL+SHIFT+U (COMMAND+SHIFT+U on Mac).

Upload using programmer

The Arduino will run through its normal process of compiling. After the sketch compiles, the Programmer will start lighting up blue everywhere – the “D+” and “D-” LEDs will light up, and so will the “Stat2” LED. When the “Stat2” LED turns off, the upload will be finished. Check the status area of your Arduino IDE to verify that the sketch is “Done uploading.”

If you’ve uploaded a sketch via the programmer, you’ve also wiped off the bootloader. If you ever want to put the serial bootloader back on your Arduino, check out the next section.

Programming a Bootloader

The Arduino IDE also has a feature built-in to allow you to (re-)upload a bootloader to the AVR. Here’s how:

Make sure you’ve set the Board option correctly – among other things, that will set which bootloader you’ll be uploading. Then, simply navigate up to Tools>Burn Bootloader at the very bottom of the menu.

Burn bootloader

This process may take a minute-or-so. Not only will the bootloader be written into the flash of your AVR, the fuse bits (setting the clock speed, bootloader space, etc), and lock bits (barring the bootloader from overwriting itself) will also be (re)set.

The bootloader upload process is complete when the “Burning bootloader to I/O board (this may take a minute)…” message turns to “Done burning bootloader”. It really does take a while – it’s not lying when it says it “may take a minute.”

Pogo Pins or the Angled Header Press

Most Arduino boards should have male pins populated on this 2x3 connector. If your board doesn’t have pins shooting out of those holes, there are a few options.

You can solder a couple strips of 3 straight male headers in there, to get the best, most reliable connection. But if you want to avoid soldering, you can use those same headers (long headers work better for this), plugging the long end into the programming cable and pushing the short end into the empty holes, while angling them to make contact on all six pins.

Angled header press

Another solder-less option is to use the ISP Pogo Adapter, which will afford you a more reliable electrical connection.

Using the pogo pin adapter

Both of these methods can be tricky – you have to hold those pins steady while the code uploads to your Arduino – but they’re a good solderless, temporary option.

Using AVRDUDE

If you’re looking for more control over your AVR Pocket Programmer – and the AVR it’s connected to – follow along below. We’ll demonstrate how to use AVRDUDE, an open-source command line wonder-utility for reading, writing and manipulating AVRs.

If you have Arduino, then you already have AVRDUDE installed – it’s the tool Arduino uses under the hood to upload sketches. If you need to install AVRDUDE separately, check out the download documentation.

Sanity Check – Device Signature Verification

AVRDUDE is a command-line tool, so, in order to use it, you’ll need to open up the “Command Prompt” (Windows) or “Terminal” (Mac/Linux).

To make sure AVRDUDE is working, and your AVR Pocket Programmer is connected correctly, it’s good to do a little sanity check first. Type this into your command prompt:

avrdude -c usbtiny -p atmega328p

(Note: This is all assuming you have an ATmega328P connected at the other end of your programmer. If you have a different type of microcontroller, you’ll need to formulate a slightly different command, check the Specify AVR Device section below.)

If everything is connected correctly, you should get a response like this:

Device signature check response

This basic command defines the programmer type you’re using and the AVR it’s talking to. AVRDUDE will attempt to read the Device Signature from your AVR, which is different for each AVR type out there. Every ATmega328P should have a device signature of 0x1E950F.

Flash Programming

Now that you’ve verified that everything is in working order, you can do all sorts of memory reading and writing with AVRDUDE. The main piece of memory you probably want to write is flash – the non-volatile memory where the programs are stored.

This command will perform a basic write to flash (using this HEX file as an example):

avrdude -c usbtiny -p atmega328p -U flash:w:blink.hex

Writing to flash will take a little longer than reading the signature bits. You’ll see a text status bar scroll by as the device is read, written to, and verified.

Flash write example

The -U option command handles all of the memory reads and writes. We tell it we want to work with flash memory, do a write with w, and then tell it the location of the hex file we want to write.

Flash Reading

The -U command can also be used to read the memory contents of an AVR. A command like below, for example, will read the contents of your AVR and store them into a file called “mystery.hex”.

avrdude -c usbtiny -p atmega328p -U flash:r:mystery.hex:r

This is incredibly useful if you want to copy the contents of one Arduino to another. Or maybe you’re a masochist, and you want to try reverse-engineering the mystery code in an AVR.

Useful Options

Here are just a few last AVRDUDE tips and tricks before we turn you loose on the AVR world.

Specify AVR Device

Two options required for using AVRDUDE are the programmer type and AVR device specification. The programmer definition, assuming you’re using the AVR Pocket Programmer, will be -c usbtiny. If you need to use a different programmer check out this page and CTRL+F to “-c programmer-id”.

The AVR device type is defined with the -p option. We’ve shown a few examples with the ATmega328P, but what if you’re using an ATtiny85? In that case, you’ll want to put -p t85 instead. Check out the top of this page for an exhaustive list of compatible AVR device types.

Verbose Output

Adding one, or more -v’s to your AVRDUDE command will enable various levels of verbosity to the action. This is handy if you need a summary of your configuration options, or an in-depth view into what data is being sent to your AVR.


There’s plenty more where that came from. Check out the AVRDUDE Option Documentation for the entire list of commands.

Resources & Going Further

Here are some more AVR Pocket Programmer related resources, should you need them:

Going Further

We’ve got plenty more tutorials where that came from. If you’re looking for more stuff to learn, or are looking for some project inspiration, check out these tutorials!


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

Pushing Data to Data.SparkFun.com

$
0
0

Pushing Data to Data.SparkFun.com a learn.sparkfun.com tutorial

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

Introduction

SparkFun’s Data.SparkFun.com service allows you to easily push your data to the “cloud.” Whether you’re posting weather readings, office environment conditions, or anything else, it can come in handy to have a central, online location to store those sensor readings. By sending a simple HTTP request to the Data.SparkFun.com server, your project data is stored and displayed in a simple database where it can be retrieved or reviewed at your leisure.

SCreenshot of the stream

Any electronics project that can be Internet-connected should be able to post data to the SparkFun data service. Luckily, these days – with Internet-of-Things applications taking off – there is no shortage of hardware gateways to the web. Basic Arduino’s can rely on shields for WiFi or Ethernet access, while many advanced development platforms already have WiFi or Ethernet built-in.

alt text

An assortment of shields and development boards that can be used as your hardware’s Internet gateway for Data.SparkFun.com.

This tutorial is a grab bag of example sketches and scripts that show how you can publish anything to our data service using most of today’s popular hardware platforms. Each example has a section dedicated to the example hookup, code and setup:

  • Arduino & Ethernet Shield– The Ethernet Shield has been one of the Arduino’s longest lasting Network portals around. If you don’t mind a few wires hanging out of your project, this shield is one of the most reliable options around. This example also works with the PoEthernet Shield, or really any shield that uses the Ethernet library.
  • Arduino & CC3000 Shield– The CC300 WiFi Shield is one of our newest offerings to the WiFi Shield market. Because it’s relatively low-cost and reliable, it’s a great choice if you’re short on RJ-45 ports or Cat5 cable.
  • Arduino & WiFly Shield– The WiFly Shield is another long-surviving shield that makes connecting your ‘duino to WiFi easy. Not as cheap as the CC3000, but a good option if you’ve already got a Shield lying around.
  • Arduino Yun– Internet-of-things applications like this are what the Arduino Yun was made for. With built in Ethernet, WiFi, and even Linux, not much stands in the way of your data on its way to the web.
  • Raspberry Pi (using Python)– With a full Linux kernel at its fingertips, the Raspberry Pi should have no problems posting an HTTP request. In this example we’ll use Python, which allows us to toggle I/O at the same time.
  • Electric Imp– A prerequisite to using the Electric Imp is that it must be Internet-connected to download code. With its ability to work with web “agents”, the it’s easy to get the imp posting HTTP requests.

Each section of the tutorial will demonstrate an example sketch for a particular piece, or combination of hardware. But before clicking over to the platform you plan on using, check out the What is Phant? first. That’s where we’ll demonstrate how to create a data stream and how to use it.

What is Phant?

The software that powers Data.SparkFun.com is called Phant, short for the animal that never forgets. The project is maintained by folks at SparkFun, and it’s fully open-source – you can download the code, modify it, and even stick it on a server of your own.

Phant logo

Each Phant data stream gets two unique keys – one public and another private. The public key is visible to everyone who visits your data stream because it’s part of the URL. The stream we’ll be using in this tutorial, for example, has a public key of “6JZbNolApzF4om2l9yYK”, and the URL is https://data.sparkfun.com/streams/6JZbNolApzF4om2l9yYK.

The private key is required to post any data to your stream. This unique hash isn’t publicly visible, and it should only be known by you or anyone else allowed to post to your stream.

Finally, each stream contains one or more field names– the “labels” for your data values. In our example, we have three fields named “light”, “switch”, and “name.” Data of nearly any form can be stored in those fields – integers, strings, floats, you name it.

Once you have all three of those ingredients, plus data to assign to each field, you can construct either an HTTP GET or POST, and send it to data server. For example, to post data to our example stream using an HTTP GET, a request like this can be sent:

https://data.sparkfun.com/input/6JZbNolApzF4om2l9yYK?private_key=Ww0vPW1yrkUNDqWPV9jE&light=2501&switch=1&name=tutorial

Go ahead an click that, or copy/paste it into your web browser. Then visit the stream, where your data will be instantly viewable.

Stream screenshot

So, to post data to the stream using Arduino’s, Pi’s, Imp’s or other hardware, all it takes is constructing a HTTP request like above – basically a lot of string concatenations – and sending it to the server. That’s the common theme we’ll be following throughout the next few examples.

To learn about deletion, clearing, and outputting data from your stream check out the Phant documentation section.

Create a Data Stream

You can learn a lot about Phant by just jumping in and creating a stream. To create a data stream, head over to data.sparkfun.com, and click “CREATE”.

On the next page, fill in the blanks with your feed’s title and description. Then take extra care to fill in the Fields textbox. This comma-separated list of words defines how you interact with the data stream to post a list of unique values. Make your fields as descriptive and short as you can. I used “light”, “switch”, and “name” to describe the readings.

Creating a stream

Once you’ve figured all of that out, click “Create!”. After which, you’ll be led to the stream’s key page.

Stream key page

Copy down all of the information on this page! Better yet, take advantage of the “Email a Copy” section at the bottom to get a more permanent copy of the keys.


Now that you have the stream set up, click around this tutorial to find the hardware set up that suits you. Time to post some data!

Arduino & Ethernet Shield

The real sticking point with using Arduinos in Internet applications like this is finding a bridge between the lowly 8-bit microcontroller and the web. WiFi or Ethernet-enabling shields or breakout boards are usually the best option for that. If you don’t mind being tied down by wires, Ethernet can be the faster, more reliable option of the two. The Ethernet Shield, and its variations like the PoEthernet Shield, equip your Arduino with all it needs to access a network and post data to a server over Ethernet.

Ethernet Shield Example hookup

Arduino Example Circuit

We’ll use this circuit for all four of the Arduino examples. A simple selection of digital and analog sensors are used to demonstrate the abilities of the Data.SparkFun.com service.

Ethernet example hookup

The output of a photocell (voltage divided with a 10kΩ resistor) connects to A0. A momentary push-button is connected to D3 on one end and ground on the other. And a SPDT switch can connect D5 to ground or let it float.

Ethernet Example Code

Here’s an example sketch that posts data to Data.SparkFun.com using the Ethernet Shield. Copy and paste from below or click here to download the sketch.

language:c
/*****************************************************************
Phant_Ethernet.ino
Post data to SparkFun's data stream server system (phant) using
an Arduino and an Ethernet Shield.
Jim Lindblom @ SparkFun Electronics
Original Creation Date: July 3, 2014

This sketch uses an Arduino Uno to POST sensor readings to
SparkFun's data logging streams (http://data.sparkfun.com). A post
will be initiated whenever pin 3 is connected to ground.

Before uploading this sketch, there are a number of global vars
that need adjusting:
1. Ethernet Stuff: Fill in your desired MAC and a static IP, even
   if you're planning on having DCHP fill your IP in for you.
   The static IP is only used as a fallback, if DHCP doesn't work.
2. Phant Stuff: Fill in your data stream's public, private, and
data keys before uploading!

Hardware Hookup:
  * These components are connected to the Arduino's I/O pins:
    * D3 - Active-low momentary button (pulled high internally)
    * A0 - Photoresistor (which is combined with a 10k resistor
           to form a voltage divider output to the Arduino).
    * D5 - SPDT switch to select either 5V or 0V to this pin.
  * A CC3000 Shield sitting comfortable on top of your Arduino.

Development environment specifics:
    IDE: Arduino 1.0.5
    Hardware Platform: RedBoard & PoEthernet Shield

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!

Much of this code is largely based on David Mellis' WebClient
example in the Ethernet library.

Distributed as-is; no warranty is given.
*****************************************************************/
#include <SPI.h> // Required to use Ethernet
#include <Ethernet.h> // The Ethernet library includes the client
#include <Progmem.h> // Allows us to sacrifice flash for DRAM

///////////////////////
// Ethernet Settings //
///////////////////////
// Enter a MAC address for your controller below.
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(54,86,132,254);  // numeric IP for data.sparkfun.com
char server[] = "data.sparkfun.com";    // name address for data.sparkFun (using DNS)
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192,168,0,177);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

/////////////////
// Phant Stuff //
/////////////////
const String publicKey = "6JZbNolApzF4om2l9yYK";
const String privateKey = "Ww0vPW1yrkUNDqWPV9jE";
const byte NUM_FIELDS = 3;
const String fieldNames[NUM_FIELDS] = {"light", "switch", "name"};
String fieldData[NUM_FIELDS];

//////////////////////
// Input Pins, Misc //
//////////////////////
const int triggerPin = 3;
const int lightPin = A0;
const int switchPin = 5;
String name = "Ether-anon";
boolean newName = true;

void setup()
{
  Serial.begin(115200);

  // Setup Input Pins:
  pinMode(triggerPin, INPUT_PULLUP);
  pinMode(switchPin, INPUT_PULLUP);
  pinMode(lightPin, INPUT_PULLUP);

  // Set Up Ethernet:
  setupEthernet();

  Serial.println(F("=========== Ready to Stream ==========="));
  Serial.println(F("Press the button (D3) to send an update"));
  Serial.println(F("Type your name (no spaces!), followed by '!' to update name"));
}

void loop()
{
  // If the trigger pin (3) goes low, send the data.
  if (!digitalRead(triggerPin))
  {
    // Gather data:
    fieldData[0] = String(analogRead(lightPin));
    fieldData[1] = String(digitalRead(switchPin));
    fieldData[2] = name;

    Serial.println("Posting!");
    postData(); // the postData() function does all the work,
                // check it out below.

    delay(1000);
  }

  // Check for a new name input:
  if (Serial.available())
  {
    char c = Serial.read();
    if (c == '!')
    {
      newName = true;
      Serial.print("Your name is ");
      Serial.println(name);
    }
    else if (newName)
    {
      newName = false;
      name = "";
      name += c;
    }
    else
    {
      name += c;
    }
  }
}

void postData()
{
  // Make a TCP connection to remote host
  if (client.connect(server, 80))
  {
    // Post the data! Request should look a little something like:
    // GET /input/publicKey?private_key=privateKey&light=1024&switch=0&name=Jim HTTP/1.1\n
    // Host: data.sparkfun.com\n
    // Connection: close\n
    // \n
    client.print("GET /input/");
    client.print(publicKey);
    client.print("?private_key=");
    client.print(privateKey);
    for (int i=0; i<NUM_FIELDS; i++)
    {
      client.print("&");
      client.print(fieldNames[i]);
      client.print("=");
      client.print(fieldData[i]);
    }
    client.println(" HTTP/1.1");
    client.print("Host: ");
    client.println(server);
    client.println("Connection: close");
    client.println();
  }
  else
  {
    Serial.println(F("Connection failed"));
  }

  // Check for a response from the server, and route it
  // out the serial port.
  while (client.connected())
  {
    if ( client.available() )
    {
      char c = client.read();
      Serial.print(c);
    }
  }
  Serial.println();
  client.stop();
}

void setupEthernet()
{
  Serial.println("Setting up Ethernet...");
  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println(F("Failed to configure Ethernet using DHCP"));
    // no point in carrying on, so do nothing forevermore:
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
  // give the Ethernet shield a second to initialize:
  delay(1000);
}

No library additions are required, since the Ethernet library used here is included with Arduino.

Unmodified, this example sketch should post to our example stream whenever you press the button connected to D3.

Modifying Ethernet and Phant Settings

Before uploading the sketch there are a few global variables you’ll need to adjust. First off, depending on your network, you may need to adjust some Ethernet-specific values. These are listed under the “Ethernet Settings” heading:

language:c
///////////////////////
// Ethernet Settings //
///////////////////////
// Enter a MAC address for your controller below.
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(54,86,132,254);  // numeric IP for data.sparkfun.com
char server[] = "data.sparkfun.com";    // name address for data.sparkFun (using DNS)
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192,168,0,177);

The mac array – a list of six HEX bytes – can be changed to any value you require. Newer Ethernet shields may even have MAC address printed on them. Just make sure your MAC address is unique!

Unless your using something else, leave the server variable set to "data.sparkfun.com". Customize your IP address to match compatible values on your network – this only becomes necessary if DHCP fails; the static IP is a fallback plan.

Next, you’ll want to modify your data stream keys and fields. Those in the example sketch should work, feel free to post to our example stream, at least temporarily. To set it to your data stream, adjust the variables under the “Phant Stuff” heading:

language:c
/////////////////
// Phant Stuff //
/////////////////
const String publicKey = "6JZbNolApzF4om2l9yYK";
const String privateKey = "Ww0vPW1yrkUNDqWPV9jE";
const byte NUM_FIELDS = 3;
const String fieldNames[NUM_FIELDS] = {"light", "switch", "name"};
String fieldData[NUM_FIELDS];

The publicKey and privateKey variables will be given to you when you create your stream. You can also adjust the number of data fields and their names here as well. The values in the fieldNames string array should match exactly what you typed when you created the stream.

Running the Sketch

After you’ve fixed the WiFi and datastream settings, upload the sketch. Then open the Serial Monitor and set the baud rate to 115200 bps. Some debug messages will flow by at the start. Once you see your IP address printed, your Arduino is connected and you’re ready to post some data.

CC3000 serial monitor

One of the fields in this example pushes a name to the server. If you want to update the name value, type in your name into the Serial Monitor and terminate it with a ‘!’.

To push your data to the server, simply press the button tied to D3 (or just short that pin to ground). A few serial lines will quickly be printed. Check to make sure HTTP/1.1 200 OK is somewhere among those lines – that means the server accepted your request.

Going Further

To further customize the sketch, you’ll want to mess around with the “gathering data” stage. In this example, a trio of lines load data into the fieldData array, converting each into a string beforehand. Those values from fieldData are later used in the postData() function when the HTTP GET string is formulated.

Most of the importatnt stuff happens in the postData() function. Here you’ll find an example for creating an HTTP GET, and routing it out to the server. Check out the comments for a line-by-line dissection of the code.

Arduino & CC3000 Shield

The CC3000 WiFi Shield (or, alternatively, the CC3000 Breakout) is a relatively low-cost WiFi solution for the Arduino. This is a fully-functional wireless networking shield which gives any Arduino-compatible board an easy route to WiFi and the Internet.

Arduino equipped with a CC3000 Shield

If you haven’t already, check out the CC3000 Hookup Guide, which will show you how to install the shield and get started using the library.

Arduino Example Circuit

We’ll use the same, exact circuit as that in the Arduino & Ethernet Shield example.

CC3000 example circuit

The output of a photocell (voltage divided with a 10kΩ resistor) connects to A0. A momentary push-button is connected to D3 on one end and ground on the other. And a SPDT switch can connect D5 to ground or let it float.

CC3000 Shield Example Code

Before running the sketch, you’ll need to download and install the CC3000 Arduino Library. You can grab it from our GitHub Repository or download it directly by clicking here. Check out our CC3000 Library Installation Guide for help installing the library.

Click here to download the example sketch, or, if you’d rather just copy/paste, here it is:

language:c
/*****************************************************************
Phant_CC3000.ino
Post data to SparkFun's data stream server system (phant) using
an Arduino and the CC3000 Shield.
Jim Lindblom @ SparkFun Electronics
Original Creation Date: July 3, 2014

This sketch uses an Arduino Uno to POST sensor readings to
SparkFun's data logging streams (http://data.sparkfun.com). A post
will be initiated whenever pin 3 is connected to ground.

Before uploading this sketch, there are a number of global vars
that need adjusting:
1. WiFi Stuff: Fill in your SSID, WiFi Passkey, and encryption
   setting using three variables available.
2. Phant Stuff: Fill in your data stream's public, private, and
data keys before uploading!

This sketch requires that you install this library:
* SFE_CC3000: https://github.com/sparkfun/SFE_CC3000_Library

Hardware Hookup:
  * These components are connected to the Arduino's I/O pins:
    * D3 - Active-low momentary button (pulled high internally)
    * A0 - Photoresistor (which is combined with a 10k resistor
           to form a voltage divider output to the Arduino).
    * D5 - SPST switch to select either 5V or 0V to this pin.
  * A CC3000 Shield sitting comfortable on top of your Arduino.

Development environment specifics:
    IDE: Arduino 1.0.5
    Hardware Platform: RedBoard & CC3000 Shield (v10)

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!

Much of this code is largely based on Shawn Hymel's WebClient
example in the SFE_CC3000 library.

Distributed as-is; no warranty is given.
*****************************************************************/
// SPI and the pair of SFE_CC3000 include statements are required
// for using the CC300 shield as a client device.
#include <SPI.h>
#include <SFE_CC3000.h>
#include <SFE_CC3000_Client.h>
// Progmem allows us to store big strings in flash using F().
// We'll sacrifice some flash for extra DRAM space.
#include <Progmem.h>

////////////////////////////////////
// CC3000 Shield Pins & Variables //
////////////////////////////////////
// Don't change these unless you're using a breakout board.
#define CC3000_INT      2   // Needs to be an interrupt pin (D2/D3)
#define CC3000_EN       7   // Can be any digital pin
#define CC3000_CS       10  // Preferred is pin 10 on Uno
#define IP_ADDR_LEN     4   // Length of IP address in bytes

////////////////////
// WiFi Constants //
////////////////////
char ap_ssid[] = "NETWORK_ID";                // SSID of network
char ap_password[] = "NETWORK_PASS";        // Password of network
unsigned int ap_security = WLAN_SEC_UNSEC; // Security of network
// ap_security can be any of: WLAN_SEC_UNSEC, WLAN_SEC_WEP,
//  WLAN_SEC_WPA, or WLAN_SEC_WPA2
unsigned int timeout = 30000;             // Milliseconds
char server[] = "data.sparkfun.com";      // Remote host site

// Initialize the CC3000 objects (shield and client):
SFE_CC3000 wifi = SFE_CC3000(CC3000_INT, CC3000_EN, CC3000_CS);
SFE_CC3000_Client client = SFE_CC3000_Client(wifi);

/////////////////
// Phant Stuff //
/////////////////
const String publicKey = "6JZbNolApzF4om2l9yYK";
const String privateKey = "Ww0vPW1yrkUNDqWPV9jE";
const byte NUM_FIELDS = 3;
const String fieldNames[NUM_FIELDS] = {"light", "switch", "name"};
String fieldData[NUM_FIELDS];

//////////////////////
// Input Pins, Misc //
//////////////////////
const int triggerPin = 3;
const int lightPin = A0;
const int switchPin = 5;
String name = "Anonymouse";
boolean newName = true;

void setup()
{
  Serial.begin(115200);

  // Setup Input Pins:
  pinMode(triggerPin, INPUT_PULLUP);
  pinMode(switchPin, INPUT_PULLUP);
  pinMode(lightPin, INPUT_PULLUP);

  // Set Up WiFi:
  setupWiFi();

  Serial.println(F("=========== Ready to Stream ==========="));
  Serial.println(F("Press the button (D3) to send an update"));
  Serial.println(F("Type your name, followed by '!' to update name"));
}

void loop()
{
  // If the trigger pin (3) goes low, send the data.
  if (!digitalRead(triggerPin))
  {
    // Gather data:
    fieldData[0] = String(analogRead(lightPin));
    fieldData[1] = String(digitalRead(switchPin));
    fieldData[2] = name;

    // Post data:
    Serial.println("Posting!");
    postData(); // the postData() function does all the work,
                // check it out below.
    delay(1000);
  }

  // Check for a new name input:
  if (Serial.available())
  {
    char c = Serial.read();
    if (c == '!')
    {
      newName = true;
      Serial.print("Your name is ");
      Serial.println(name);
    }
    else if (newName)
    {
      newName = false;
      name = "";
      name += c;
    }
    else
    {
      name += c;
    }
  }
}

void postData()
{

  // Make a TCP connection to remote host
  if ( !client.connect(server, 80) )
  {
    // Error: 4 - Could not make a TCP connection
    Serial.println(F("Error: 4"));
  }

  // Post the data! Request should look a little something like:
  // GET /input/publicKey?private_key=privateKey&light=1024&switch=0&time=5201 HTTP/1.1\n
  // Host: data.sparkfun.com\n
  // Connection: close\n
  // \n
  client.print("GET /input/");
  client.print(publicKey);
  client.print("?private_key=");
  client.print(privateKey);
  for (int i=0; i<NUM_FIELDS; i++)
  {
    client.print("&");
    client.print(fieldNames[i]);
    client.print("=");
    client.print(fieldData[i]);
  }
  client.println(" HTTP/1.1");
  client.print("Host: ");
  client.println(server);
  client.println("Connection: close");
  client.println();

  while (client.connected())
  {
    if ( client.available() )
    {
      char c = client.read();
      Serial.print(c);
    }
  }
  Serial.println();
}

void setupWiFi()
{
  ConnectionInfo connection_info;
  int i;

  // Initialize CC3000 (configure SPI communications)
  if ( wifi.init() )
  {
    Serial.println(F("CC3000 Ready!"));
  }
  else
  {
    // Error: 0 - Something went wrong during CC3000 init!
    Serial.println(F("Error: 0"));
  }

  // Connect using DHCP
  Serial.print(F("Connecting to: "));
  Serial.println(ap_ssid);
  if(!wifi.connect(ap_ssid, ap_security, ap_password, timeout))
  {
    // Error: 1 - Could not connect to AP
    Serial.println(F("Error: 1"));
  }

  // Gather connection details and print IP address
  if ( !wifi.getConnectionInfo(connection_info) )
  {
    // Error: 2 - Could not obtain connection details
    Serial.println(F("Error: 2"));
  }
  else
  {
    Serial.print(F("My IP: "));
    for (i = 0; i < IP_ADDR_LEN; i++)
    {
      Serial.print(connection_info.ip_address[i]);
      if ( i < IP_ADDR_LEN - 1 )
      {
        Serial.print(".");
      }
    }
    Serial.println();
  }
}

Before uploading the sketch there are a few global variables you’ll need to adjust. Check out the section below. Most importantly, you need to alter some constants to connect to your WiFI network. The relevant section is under the “WiFi Constants” heading:

language:c
////////////////////
// WiFi Constants //
////////////////////
char ap_ssid[] = "NETWORK_ID";                // SSID of network
char ap_password[] = "NETWORK_PASS";        // Password of network
unsigned int ap_security = WLAN_SEC_UNSEC; // Security of network
// ap_security can be any of: WLAN_SEC_UNSEC, WLAN_SEC_WEP,
//  WLAN_SEC_WPA, or WLAN_SEC_WPA2
unsigned int timeout = 30000;             // Milliseconds
char server[] = "data.sparkfun.com";      // Remote host site

The ap_ssid and ap_password strings should be adjusted to match your WiFi network. If your network is open (no passkey), that second variable should be blank (ap_password[] = "";). Also make sure to adjust the ap_security variable to match the security of your network. See the comments for possible values.

With those correctly set, you can run the sketch. This example sketch should post to our example stream whenever you press the button connected to D3.

Modifying Data.SparkFun.com Settings

Next, you’ll want to modify your data stream keys and fields. Those in the example sketch should work, feel free to post to our example stream, at least temporarily. To set it to your data stream, adjust the variables under the “Phant Stuff” heading:

language:c
/////////////////
// Phant Stuff //
/////////////////
const String publicKey = "6JZbNolApzF4om2l9yYK";
const String privateKey = "Ww0vPW1yrkUNDqWPV9jE";
const byte NUM_FIELDS = 3;
const String fieldNames[NUM_FIELDS] = {"light", "switch", "name"};
String fieldData[NUM_FIELDS];

The publicKey and privateKey variables will be given to you when you create your stream. You can also adjust the number of data fields and their names here as well. The values in the fieldNames string array should match exactly what you typed when you created the stream.

Running the Sketch

After you’ve fixed the WiFi and datastream settings, upload the sketch. Then open the Serial Monitor and set the baud rate to 115200 bps. Some debug messages will flow by at the start. Once you see your IP address printed, your Arduino is connected and you’re ready to post some data.

CC3000 serial monitor

One of the fields in this example pushes a name to the server. If you want to update the name value, type in your name into the Serial Monitor and terminate it with a ‘!’.

To push your data to the server, simply press the button tied to D3 (or just short that pin to ground). A few serial lines will quickly be printed. Check to make sure HTTP/1.1 200 OK is somewhere among those lines – that means the server accepted your request.

Going Further

To further customize the sketch, you’ll want to mess around with the “gathering data” stage. In this example, a trio of lines load data into the fieldData array, converting each into a string beforehand. Those values from fieldData are later used in the postData() function when the HTTP GET string is formulated.

Most of the importatnt stuff happens in the postData() function. Here you’ll find an example for creating an HTTP GET, and routing it out to the server. Check out the comments for a line-by-line dissection of the code.

Arduino & WiFly Shield

The WiFly Shield is another easy solution for wirelessly connecting your Arduino to the Internet.

the WiFly shield

Check out our WiFly Shield Hookup Guide, if you haven’t already, for help setting up and testing out your WiFly Shield.

Arduino Example Circuit

We’ll use the same, exact circuit as that in the previous Arduino examples.

CC3000 example circuit

The output of a photocell (voltage divided with a 10kΩ resistor) connects to A0. A momentary push-button is connected to D3 on one end and ground on the other. And a SPDT switch can connect D5 to ground or let it float.

WiFly Example Sketch

This example sketch requires the WiFly Shield library. You can download it from the GitHub repository. Follow the instructions in our How to Install an Arduino Library for help installing the library.

Once you’ve installed the library, click here to download the example sketch, or copy/paste from below:

language:c
/*****************************************************************
Phant_WiFly.ino
Post data to SparkFun's data stream server system (phant) using
an Arduino and the WiFly Shield.
Jim Lindblom @ SparkFun Electronics
Original Creation Date: July 7, 2014

This sketch uses an Arduino Uno to POST sensor readings to
SparkFun's data logging streams (http://data.sparkfun.com). A post
will be initiated whenever pin 3 is connected to ground.

Before uploading this sketch, there are a number of global vars
that need adjusting:
1. WiFi Stuff: Fill in your SSID, WiFi Passkey, and encryption
   setting using three variables available.
2. Phant Stuff: Fill in your data stream's public, private, and
data keys before uploading!

This sketch requires that you install this library:
* WiFly_Shield: https://github.com/sparkfun/WiFly-Shield/tree/master/Libraries

Hardware Hookup:
  * These components are connected to the Arduino's I/O pins:
    * D3 - Active-low momentary button (pulled high internally)
    * A0 - Photoresistor (which is combined with a 10k resistor
           to form a voltage divider output to the Arduino).
    * D5 - SPST switch to select either 5V or 0V to this pin.
  * A WiFly Shield sitting comfortable on top of your Arduino.

Development environment specifics:
    IDE: Arduino 1.0.5
    Hardware Platform: RedBoard & WiFly Shield

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 the WiFly library and the SPI library to support it:
#include <SPI.h>
#include <WiFly.h>
// Progmem allows us to store big strings in flash using F().
// We'll sacrifice some flash for extra DRAM space.
#include <Progmem.h>

////////////////////
// WiFi Constants //
////////////////////
char ssid[] = "SSID"; // SSID of the WiFi network
char passphrase[] = "SSID_PASSPHRASE"; // Password (if applicable)
// Security of your network. Set to true if your network uses WPA,
// otherwise (if it's open) set it to false:
boolean wpaEnabled = true;

/////////////////
// Phant Stuff //
/////////////////
const String publicKey = "6JZbNolApzF4om2l9yYK";
const String privateKey = "Ww0vPW1yrkUNDqWPV9jE";
char server[] = "data.sparkfun.com"; // Remote host site
const byte NUM_FIELDS = 3;
const String fieldNames[NUM_FIELDS] = {"light", "switch", "name"};
String fieldData[NUM_FIELDS];

//////////////////////
// Input Pins, Misc //
//////////////////////
const int triggerPin = 3;
const int lightPin = A0;
const int switchPin = 5;
String name = "WiFlyShield"; // Your/Arduino's name (no spaces)
boolean newName = true;

void setup()
{
  Serial.begin(115200);

  // Setup Input Pins:
  pinMode(triggerPin, INPUT_PULLUP);
  pinMode(switchPin, INPUT_PULLUP);
  pinMode(lightPin, INPUT_PULLUP);

  // Set up WiFi:
  setupWiFi();

  Serial.println(F("=========== Ready to Stream ==========="));
  Serial.println(F("Press the button (D3) to send an update"));
  Serial.println(F("Type your name (no spaces!), followed by '!' to update name"));
}

void loop()
{
  // If the trigger pin (3) goes low, send the data.
  if (!digitalRead(triggerPin))
  {
    // Gather data:
    fieldData[0] = String(analogRead(lightPin));
    fieldData[1] = String(digitalRead(switchPin));
    fieldData[2] = name;

    // Post data:
    Serial.println(F("Posting!"));
    postData(); // the postData() function does all the work,
                // check it out below.
    delay(1000);
  }

  // Check for a new name input:
  if (Serial.available())
  {
    char c = Serial.read();
    if (c == '!')
    {
      newName = true;
      Serial.print(F("Your name is "));
      Serial.println(name);
    }
    else if (newName)
    {
      newName = false;
      name = "";
      name += c;
    }
    else
    {
      name += c;
    }
  }
}

void postData()
{
  WiFlyClient client(server, 80);

  if (client.connect())
  {
    Serial.println(F("Connected"));

    // Post the data! Request should look a little something like:
    // GET /input/publicKey?private_key=privateKey&light=1024&switch=0&time=5201 HTTP/1.1\n
    // Host: data.sparkfun.com\n
    // Connection: close\n
    // \n
    client.print("GET /input/");
    client.print(publicKey);
    client.print("?private_key=");
    client.print(privateKey);
    for (int i=0; i<NUM_FIELDS; i++)
    {
      client.print("&");
      client.print(fieldNames[i]);
      client.print("=");
      client.print(fieldData[i]);
    }
    client.println(" HTTP/1.1");
    client.print("Host: ");
    client.println(server);
    client.println("Connection: close");
    client.println();

    // While we're connected, print out anything the server sends:
    while (client.connected())
    {
      if (client.available())
      {
        char c = client.read();
        Serial.print(c);
      }
    }
    Serial.println();
  }
  else // If the connection failed, print a message:
  {
    Serial.println(F("Connection failed"));
  }

  // If we're disconnected, stop the client:
  if (!client.connected())
  {
    Serial.println(F("Disconnecting."));
    client.stop();
  }
}

void setupWiFi()
{
  Serial.println(F("Initializing WiFly"));
  WiFly.begin();

  Serial.print(F("Connecting to "));
  Serial.println(ssid);
  if (!WiFly.join(ssid, passphrase, wpaEnabled))
  {
    Serial.println(F("Association failed."));
    while (1)
      ;// Hang on failure.
  }

  // Print the IP address:
  Serial.print(F("IP: "));
  Serial.println(WiFly.ip());
}

Before uploading the sketch there are a few global variables you’ll need to adjust to configure it to your WiFi network. The relevant section is under the “WiFi Constants” heading:

language:c
////////////////////
// WiFi Constants //
////////////////////
char ssid[] = "SSID"; // SSID of the WiFi network
char passphrase[] = "SSID_PASSPHRASE"; // Password (if applicable)
// Security of your network. Set to true if your network uses WPA,
// otherwise (if it's open) set it to false:
boolean wpaEnabled = true;

The ssid and passphrase character arrays should be adjusted to match your WiFi network. If your network is open (no passkey), that second variable should be blank (passphrase[] = "";). Also make sure to adjust the wpaEnabled variable to match the security of your network. If it uses WPA, set that variable to true, otherwise (if it’s open) set it to false.

With those correctly set, you can run the sketch. This example sketch should post to our example stream whenever you press the button connected to D3.

Configuring Data.SparkFun.com Settings

To use your own data stream, you’ll want to modify the data stream keys and fields. To set it to a data stream of your own, adjust the variables under the “Phant Stuff” heading:

language:c
/////////////////
// Phant Stuff //
/////////////////
const String publicKey = "6JZbNolApzF4om2l9yYK";
const String privateKey = "Ww0vPW1yrkUNDqWPV9jE";
char server[] = "data.sparkfun.com"; // Remote host site
const byte NUM_FIELDS = 3;
const String fieldNames[NUM_FIELDS] = {"light", "switch", "name"};
String fieldData[NUM_FIELDS];

The publicKey and privateKey variables will be given to you when you create your stream. You can also adjust the number of data fields and their names here as well. The values in the fieldNames string array should match exactly what you typed when you created the stream.

Running the Sketch

After you’ve fixed the WiFi and datastream settings, upload the sketch. Then open the Serial Monitor and set the baud rate to 115200 bps. Some debug messages will flow by at the start. Once you see your IP address printed, your Arduino is connected and you’re ready to post some data.

WiFly serial monitor example

One of the fields in this example pushes a name to the server. If you want to update the name value, type in your name into the Serial Monitor and terminate it with a ‘!’.

To push your data to the server, simply press the button tied to D3 (or just short that pin to ground). A few serial lines will quickly be printed. Check to make sure HTTP/1.1 200 OK is somewhere among those lines – that means the server accepted your request.

Going Further

To further customize the sketch, you’ll want to mess around with the “gathering data” stage. In this example, a trio of lines load data into the fieldData array, converting each into a string beforehand. Those values from fieldData are later used in the postData() function when the HTTP GET string is formulated.

Most of the importatnt stuff happens in the postData() function. Here you’ll find an example for creating an HTTP GET, and routing it out to the server. Check out the comments for a line-by-line dissection of the code.

Arduino Yún

With its built-in WiFi and Ethernet, the Arduino Yun was made for internet-of-things applications like this.

Arduino Yun circuit

For help getting started with the Yun, check out Arduino’s Guide to the Arduino Yun. If you’re going to use the Yun over WiFi, definitely check out their section on configuring the WiFi.

Arduino Example Circuit

As with every other Arduino example in this tutorial, we’ll be using a simple circuit consisting of a photocell (voltage divided with a 10kΩ resistor) connecte to A0. A momentary push-button is connected to D3 on one end and ground on the other. And a SPDT switch can connect D5 to ground or let it float.

alt text

Pretend the RedBoard in the Fritzing diagram above is Arduino-blue, and you should be golden.

Yun Example Sketch

Make sure your Yun is connected to the Internet, before continuing on. If you have an Ethernet switch or router nearby, simply connect an Ethernet cable between the two. If you’re using your Yun through WiFi, follow these directions to connect your Yun to a WiFi network.

Here’s the code. Copy and paste from below, or click here to download it.

language:c
/*****************************************************************
Phant_Yun.ino
Post data to SparkFun's data stream server system (phant) using
an Arduino Yun
Jim Lindblom @ SparkFun Electronics
Original Creation Date: July 3, 2014

This sketch uses an Arduino Yun to POST sensor readings to
SparkFun's data logging streams (http://data.sparkfun.com). A post
will be initiated whenever pin 3 is connected to ground.

Make sure you fill in your data stream's public, private, and data
keys before uploading! These are in the global variable section.

Hardware Hookup:
  * These components are connected to the Arduino's I/O pins:
    * D3 - Active-low momentary button (pulled high internally)
    * A0 - Photoresistor (which is combined with a 10k resistor
           to form a voltage divider output to the Arduino).
    * D5 - SPST switch to select either 5V or 0V to this pin.
  * Your Yun should also, somehow, be connected to the Internet.
    You can use Ethernet, or the on-board WiFi module.

Development environment specifics:
    IDE: Arduino 1.5.6-r2
    Hardware Platform: Arduino Yun

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!

curl example from:
https://github.com/sparkfun/phant/blob/master/examples/sh/curl_post.sh

Distributed as-is; no warranty is given.
*****************************************************************/
// Process.h gives us access to the Process class, which can be
// used to construct Shell commands and read the response.
#include <Process.h>

/////////////////
// Phant Stuff //
/////////////////
// URL to phant server (only change if you're not using data.sparkfun
String phantURL = "http://data.sparkfun.com/input/";
// Public key (the one you see in the URL):
String publicKey = "6JZbNolApzF4om2l9yYK";
// Private key, which only someone posting to the stream knows
String privateKey = "Ww0vPW1yrkUNDqWPV9jE";
// How many data fields are in your stream?
const int NUM_FIELDS = 3;
// What are the names of your fields?
String fieldName[NUM_FIELDS] = {"light", "switch", "name"};
// We'll use this array later to store our field data
String fieldData[NUM_FIELDS];

////////////////
// Pin Inputs //
////////////////
const int triggerPin = 3;
const int lightPin = A0;
const int switchPin = 5;

String name = "Yun-anon";
boolean newName = true;

void setup()
{
  Bridge.begin();
  Serial.begin(115200);

  // Setup Input Pins:
  pinMode(triggerPin, INPUT_PULLUP);
  pinMode(switchPin, INPUT_PULLUP);
  pinMode(lightPin, INPUT_PULLUP);

  Serial.println("=========== Ready to Stream ===========");
  Serial.println("Press the button (D3) to send an update");
  Serial.println("Type your name, followed by '!' to update name");
}

void loop()
{
  // If the trigger pin (3) goes low, send the data.
  if (!digitalRead(triggerPin))
  {
    // Gather Data
    fieldData[0] = String(analogRead(lightPin));
    fieldData[1] = String(digitalRead(switchPin));
    fieldData[2] = name;

    // Post Data
    Serial.println("Posting Data!");
    postData(); // the postData() function does all the work,
                // see below.
    delay(1000);
  }

  // Check for a new name input:
  if (Serial.available())
  {
    char c = Serial.read();
    if (c == '!')
    {
      newName = true;
      Serial.print("Your name is ");
      Serial.println(name);
    }
    else if (newName)
    {
      newName = false;
      name = "";
      name += c;
    }
    else
    {
      name += c;
    }
  }
}

void postData()
{
  Process phant; // Used to send command to Shell, and view response
  String curlCmd; // Where we'll put our curl command
  String curlData[NUM_FIELDS]; // temp variables to store curl data

  // Construct curl data fields
  // Should look like: --data "fieldName=fieldData"
  for (int i=0; i<NUM_FIELDS; i++)
  {
    curlData[i] = "--data \"" + fieldName[i] + "=" + fieldData[i] + "\"";
  }

  // Construct the curl command:
  curlCmd = "curl ";
  curlCmd += "--header "; // Put our private key in the header.
  curlCmd += "\"Phant-Private-Key: "; // Tells our server the key is coming
  curlCmd += privateKey;
  curlCmd += "\""; // Enclose the entire header with quotes.
  for (int i=0; i<NUM_FIELDS; i++)
    curlCmd += curlData[i]; // Add our data fields to the command
  curlCmd += phantURL + publicKey; // Add the server URL, including public key

  // Send the curl command:
  Serial.print("Sending command: ");
  Serial.println(curlCmd); // Print command for debug
  phant.runShellCommand(curlCmd); // Send command through Shell

  // Read out the response:
  Serial.print("Response: ");
  // Use the phant process to read in any response from Linux:
  while (phant.available())
  {
    char c = phant.read();
    Serial.write(c);
  }
}

After uploading the sketch, open the Serial Monitor and set your baud rate to 115200 bps. Wait for the “Ready to Stream” message to appear, then press the button to send data. This example sketch should post to our example stream by default.

Yun serial monitor

You can update the name value that posts, by sending a series of characters followed by an exclamation mark (!).

Configuring to Use Your Data Stream

The section in the code under “Phant Stuff” is where you can alter variables and set the Yun to use a data stream of your own.

language:c
/////////////////
// Phant Stuff //
/////////////////
// URL to phant server (only change if you're not using data.sparkfun
String phantURL = "http://data.sparkfun.com/input/";
// Public key (the one you see in the URL):
String publicKey = "6JZbNolApzF4om2l9yYK";
// Private key, which only someone posting to the stream knows
String privateKey = "Ww0vPW1yrkUNDqWPV9jE";
// How many data fields are in your stream?
const int NUM_FIELDS = 3;
// What are the names of your fields?
String fieldName[NUM_FIELDS] = {"light", "switch", "name"};
// We'll use this array later to store our field data
String fieldData[NUM_FIELDS];

The publicKey and privateKey variables should be set to the respective keys your were supplied when creating your stream. Also make sure to set the NUM_FIELDS variable to the number of fields in your stream and update the fieldName array values accordingly.

Using the Sketch

In this example we use the Unix cURL command to transfer data to a server. The Yun’s Process class comes in handy for sending a shell command, and reading its response.

Most of the action happens in the void postData() function. That’s where we read the Arduino’s inputs and formulate a cURL command. The contents of the cURL command include the server URL, public and private keys, and our data keys and values. Check out the comments in that function for a line-by-line dissection.

Raspberry Pi (Python)

The multi-talented Raspberry Pi has no shortage of tools for posting data to web servers. You could use a shell script and cURL, similar to what we did on the Yun, but in this example we’ll use Python, which pairs nicely with the Pi’s RPi.GPIO module.

Raspberry Pi hookup

If you haven’t used Python on the Pi to read-and-write to I/O pins, check out our Raspberry gPIo tutorial. This tutorial leans on that to read the status of a couple input pins.

Example Circuit

Our simple example circuit changes a little bit in this case. The Pi doesn’t have analog inputs, so we can’t plug the photocell in, but we’ll still use a button and switch:

alt text

The button is connected to the Pi’s pin 22 (that’s the Broadcom chip pin), and the switch output is connected to pin 23.

If you have a Pi Wedge, it makes the job of wiring to the Pi much easier.

Example Script

Right-click and Save Link As to download the example python script, or copy and paste from below. We’ve named our file phant-raspi.py, if you’re making the file on your own. Place it in an easily-accesible directory on your Pi.

language:c
########################################################################
# phant-raspi.py
# Raspberry Pi Phant Example
# Jim Lindblom @ SparkFun Electronics
# July 7, 2014
#
# This example demonstrates how to post data to a phant server (e.g.
#   data.sparkfun.com) using python on a Raspberry Pi.
#   The RPi.GPIO module is used to enable I/O reading and writing.
#   Before running this script, make sure to update your public and
#   private keys (publicKey and privateKey vars).
#
# Development environment specifics:
#   Raspberry Pi rev 2
#
# 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.
########################################################################

import RPi.GPIO as GPIO  # RPi.GPIO used for GPIO reading/writing
import time              # time used for delays
import httplib, urllib   # http and url libs used for HTTP POSTs
import socket            # socket used to get host name/IP

#################
## Phant Stuff ##
#################
server = "data.sparkfun.com" # base URL of your feed
publicKey = "6JZbNolApzF4om2l9yYK" # public key, everyone can see this
privateKey = "Ww0vPW1yrkUNDqWPV9jE"  # private key, only you should know
fields = ["light", "switch", "name"] # Your feed's data fields

######################
## I/O Stuff & Misc ##
######################
buttonPin = 22 # Active-low button connected to Broadcom pin 22
switchPin = 23 # SPST switch connected to Broadcom pin 23
myname = socket.gethostname() # Send local host name as one data field

##############
## I/O Setup #
##############
GPIO.setmode(GPIO.BCM) # Broadcom pin-numbering scheme
GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Button pin set as input w/ pull-up
GPIO.setup(switchPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Switch set as input w/ pull-up

##########
## Loop ##
##########
print("Here we go! Press CTRL+C to exit")
try:
    # Loop until CTRL+C is pressed
    while 1:
        # If the button is pressed, we'll send our data. It's active-low
        # so we need to check if it's 0.
        if not (GPIO.input(buttonPin)):
            print("Sending an update!")
            # Our first job is to create the data set. Should turn into
            # something like "light=1234&switch=0&name=raspberrypi"
            data = {} # Create empty set, then fill in with our three fields:
            # Field 0, light, gets the local time:
            data[fields[0]] = time.strftime("%A %B %d, %Y %H:%M:%S %Z")
            # Field 1, switch, gets the switch status:
            data[fields[1]] = GPIO.input(switchPin)
            # Field 2, name, gets the pi's local name:
            data[fields[2]] = myname
            # Next, we need to encode that data into a url format:
            params = urllib.urlencode(data)

            # Now we need to set up our headers:
            headers = {} # start with an empty set
            # These are static, should be there every time:
            headers["Content-Type"] = "application/x-www-form-urlencoded"
            headers["Connection"] = "close"
            headers["Content-Length"] = len(params) # length of data
            headers["Phant-Private-Key"] = privateKey # private key header

            # Now we initiate a connection, and post the data
            c = httplib.HTTPConnection(server)
            # Here's the magic, our reqeust format is POST, we want
            # to send the data to data.sparkfun.com/input/PUBLIC_KEY.txt
            # and include both our data (params) and headers
            c.request("POST", "/input/" + publicKey + ".txt", params, headers)
            r = c.getresponse() # Get the server's response and print it
            print r.status, r.reason

            time.sleep(1) # delay for a second

except KeyboardInterrupt: # If CTRL+C is pressed, exit cleanly:
    GPIO.cleanup() # cleanup all GPIO

Now open up the terminal, and navigate to the directory where your script lives, and run it like this:

pi@raspberrypi ~/code/phant-pi $ sudo python phant-raspi.lpy

With the script running, when you connect the button pin (22) to ground it should send an update. A handful of messages will appear each time a message is sent. You want to see “200 OK” after the “Sending an Update!” message. That should indicate that the HTTP POST was succesfully sent.

To customize it to your own Phant stream, edit the public, private, and field keys in this section:

language:python
#################
## Phant Stuff ##
#################
server = "data.sparkfun.com" # base URL of your feed
publicKey = "6JZbNolApzF4om2l9yYK" # public key, everyone can see this
privateKey = "Ww0vPW1yrkUNDqWPV9jE"  # private key, only you should know
fields = ["light", "switch", "name"] # Your feed's data fields

You may also want to modify how the data for those fields is gathered. That happens near the very beginning of the lone if statement. Field 0 (“light”) contains the current time/date, field 1 (“switch”) contains the status of our switch, and field 2 (“name”) contains the localhost name of your Pi.

Electric Imp

The Electric Imp– a development platform centered around Internet-of-Things applications – is a perfect tool for sending data to a Phant stream. If you want to get code on the little SD-card sized module, it already has to be Internet connected. Plus the Imp API already has all of the HTTP-related features you need to send server requests.

Electric Imp hookup

If you’re unfamiliar with the Electric Imp, check out our Electric Imp Hookup Guide, which will guide you through the BlinkUp process and includes a few example programs to get you started.

The Imp Example Circuit

Here’s the example circuit for our Imp example:

Electric Imp example circuit

The output of a photocell (voltage divided with a 10kΩ resistor) connects to pin 5. A momentary push-button is connected to pin 2 on one end and ground on the other. And a SPDT switch can connect pin 7 to ground or let it float.

The Imp Example Code

As with most Electric Imp code examples, there are two halves to this puzzle: device code and agent code. Create a new model in your imp IDE– we called ours “Phant Imp” – and paste these two bits of code into their respective half.

Device Code

The Imp device itself is responsible for reading the button, switch, and light inputs, packaging them into a string and sending that off to the agent. Here’s the code:

language:JavaScript
/*****************************************************************
Phant Imp (Device)
Post data to SparkFun's data stream server system (phant) using
an Electric Imp
Jim Lindblom @ SparkFun Electronics
Original Creation Date: July 7, 2014

Description

Hardware Hookup:
  * These components are connected to the Arduino's I/O pins:
    * Pin 1 - Active-low momentary button (pulled high internally)
    * Pin 2 - Photoresistor (which is combined with a 10k resistor
           to form a voltage divider output to the Arduino).
    * Pin 5 - SPST switch to select either 5V or 0V to this pin.

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.
*****************************************************************/

/////////////////
// Phant Stuff //
/////////////////
const FIELD_COUNT = 3; // Number of fields in the stream
local fieldNames = ["light", "switch", "name"]; // Exact names of each field

/////////////////////
// Pin Definitions //
/////////////////////
buttonPin <- hardware.pin2;
lightPin <- hardware.pin5;
switchPin <- hardware.pin7;

// This name will be sent to the stream each update:
local impName = "Imp%20" + imp.getmacaddress();

////////////////////////////
// Button Press Interrupt //
////////////////////////////
// This function will be called each time the button (connected to pin 2) is
// pressed or released.
function sendData()
{
    // Only do this if the pin is low (pressed)
    if (buttonPin.read() == 0)
    {
        // Collect Data
        local lightValue = lightPin.read();
        local switchValue = switchPin.read();

        // Populate fieldData array with respective data values
        local fieldData = [lightValue, switchValue, impName];

        // Create a data string to send to the agent. Should be of the form:
        // "fieldName0=fieldData0&fieldName1=fieldData1&fieldName2=fieldData2"
        local data = "";
        for (local i=0; i<FIELD_COUNT; i++)
        {
            data += fieldNames[i] + "=" + fieldData[i];
            if (i < FIELD_COUNT - 1)
                data += "&";
        }
        server.log("Sending Data!");
        agent.send("postData", data);

        imp.sleep(1); // Wait for a second (lazy debounce, update rate control)
    }
}

///////////////
// Pin Setup //
///////////////
buttonPin.configure(DIGITAL_IN_PULLUP, sendData); // Button -- input w/ pull-up
lightPin.configure(ANALOG_IN); // Light sensor -- Analog input
switchPin.configure(DIGITAL_IN_PULLUP); // Switch -- Input w/ pull-up

server.log("Phant Imp has started"); // Hello, world.

The very first few lines of that code, under the “Phant Stuff” heading, determine the field names of your data steram. Make sure to set the FIELD_COUNT variable to the number of data fields in your stream, and stick the exact name of each field in the fieldNames array.

Agent Code

Paste this code into the left, agent half of your Imp IDE.

language:JavaScript
/*****************************************************************
Phant Imp (Agent)
Post data to SparkFun's data stream server system (phant) using
an Electric Imp
Jim Lindblom @ SparkFun Electronics
Original Creation Date: July 7, 2014

Description

Before uploading this sketch, there are a number of vars that need adjusting:
1. Phant Stuff: Fill in your data stream's public, private, and
data keys before uploading!

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.
*****************************************************************/

/////////////////
// Phant Stuff //
/////////////////
local publicKey = "6JZbNolApzF4om2l9yYK"; // Your Phant public key
local privateKey = "Ww0vPW1yrkUNDqWPV9jE"; // The Phant private key
local phantServer = "data.sparkfun.com"; // Your Phant server, base URL, no HTTP

/////////////////////
// postData Action //
/////////////////////
// When the agent receives a "postData" string from the device, use the
// dataString string to construct a HTTP POST, and send it to the server.
device.on("postData", function(dataString) {

    server.log("Sending " + dataString); // Print a debug message

    // Construct the base URL: https://data.sparkfun.com/input/PUBLIC_KEY:
    local phantURL = "https://" +  phantServer + "/input/" + publicKey;
    // Construct the headers: e.g. "Phant-Priave-Key: PRIVATE_KEY"
    local phantHeaders = {"Phant-Private-Key": privateKey, "connection": "close"};
    // Send the POST to phantURL, with phantHeaders, and dataString data.
    local request = http.post(phantURL, phantHeaders, dataString);

    // Get the response from the server, and send it out the debug window:
    local response = request.sendsync();
    server.log("Phant response: " + response.body);
});

The agent is responsible for receiving data from the Imp and sending it off to a server in the form of an HTTP POST. The public and private keys of your stream are stored in this half of the model. Update those, under the “Phant Stuff” heading, to the hashes in your stream.

In this example, the agent is totally ignorant of the data being passed to the stream. It’s relying on the device to construct that string exactly as the server wants to see it. That seemed to be the easiest way to handle this, as the device can only send a single string at a time to the agent.

With those two halves of code copied and pasted, upload them to your Imp. Then, whenever you press the button, it should post its data to our example stream. Update the variables under the “Phant Stuff” headings to configure it to your stream.

Resources & Going Further

Need more Phant documentation or examples? Check out these resources:

  • Phant Documentation Page– All of the in’s and out’s of Phant. This page shows how you can post to the server, read from the server, and even delete your stream.
  • Phant GitHub Repository– Want to use Phant on your server? Want to modify the code? It’s all hosted here on GitHub.
  • Phant Example Code– Example code covering perl, PHP, Ruby, and shell.
  • Phant Arduino Library– The Phant Arduino library makes creating HTTP GETs and POSTs super easy.

Going Further

Now that you’re posting data to the Internet, what project are you going to create to use the SparkFun data service? Need some inspiration? Check out these tutorials:

Weather Station image


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

How to Sell Your Widget on SparkFun

$
0
0

How to Sell Your Widget on SparkFun a learn.sparkfun.com tutorial

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

Choose Your Adventure

Have an awesome electronic widget that you want to get to market? Great! We are always listening for new ideas from our customers and the community. We get many inquires on this topic, so read this tutorial carefully to keep your product pitch from getting lost in the shuffle.


We’re lucky, here at SparkFun, to have an amazingly creative and talented group of customers. Not only can they identify gaps in the catalogs of electronics suppliers, they can create a gizmo that fills that hole. But, going beyond a prototype or even a limited-quantity production run, often the hardest task in getting your world-alterring product out there is producing, marketing, and/or selling it to the masses. That’s where we come into the picture.

(An older image of) the SparkFun Team

Over the years SparkFun has helped to bring dozens of unique widgets and useful electronic shortcuts – dreamt-up and designed by our customers – to the throngs of electronics hobbyists, artists and students. A few examples include:

We’ve gone through this process enough to know how to guide any product through it. The goal of this tutorial is to walk you through two of the most common routes previous collaborators have followed in getting their widgets sold on SparkFun. Which route you choose mostly depends on who is manufacturing your product. Time to choose your adventure:

Option 1: You Manufacture, SparkFun Buys and Resells

Have you already set up a manufacturing process for your design? Whether you’re cooking the boards in your basement reflow toaster, or working with an established assembly house, we’d be interested in reselling it. What really matters is that you have a solid, tested design, a manufacturing process set up for it, and a market starving to buy it.

Hundreds of products in the SparkFun catalog go through this process, including pcDuino3 and BITalino - BioMedical Development Kit. It’s the fastest route to our storefront, if that’s what interests you the most.

Check out this half of the tutorial to find out more about how to pitch your product.

Option 2: SparkFun Manufactures, and Pays You a Royalty Per Sale

Have you prototyped your design, and proven that it works, but gotten stuck trying to produce and sell it? Well it just so happens that we have pick-and-place machines, reflow ovens, and a all-star production team that can help with manufacturing. Plus, our engineers can help polish the design along the way.

The best part about this option is you still get paid. Instead of buying the products up-front, we pay you a percentage-based royalty per product sold.

We do have limited production and design resources, so there’s no guarantee that we can take your product on. But if it’s unique enough, and fits within our manufacturing abilities, we’re certainly interested in working with you to help productize your widget.

Products like the MaKey MaKey, WAV Trigger, and EasyDriver have all gone through this process, and are now some of the highest-selling, most important products in our catalog. Check out this section of the tutorial to learn more about how to pitch your design.


So, it all begins by figuring out who’s producing the widget. Read on to learn more about each option.

Option 1: You Manufacture, SparkFun Resells

This option is great for those who already have the resources to support manufacturing. In this relationship, SparkFun assumes the responsibilities of storefront management, inventory storage, shipping, and customer service. You, on the other hand, deal with manufacturing and assume all the risks inherent to that. This allows you to have more control over your product (revisions, pricing, documentation, etc).

A great example of this relationship in action is the pcDuino.

pcDuino 3

The pcDuino is designed and manufactured by our friends at LinkSprite. They support a community, publish the documentation, and handle all manufacturing, but aren’t as interested in hosting a storefront. So we resell it! As a bonus, the end-customer can save on shipping (or get it for free) when resistors, batteries, switches, and other components are inevitably added to the order.

Division of Responsibilities

Here’s an overview of who does what in this relationship:

Venn diagram of responsibilities

SparkFun’s Responsibilities

To help store, sell, ship, and market your product, we have a great group of talented employees canvassing a wide variety of skills. Here are the roles we’ll take sole ownership of in the relationship:

  • Purchasing Your Product– To begin, our purchasers can work with you to work out prices, payment methods, and inbound shipping requirements. We’ll need a decent distributor margin to give us room for our distributor and education pricing. We’ll work out those details in an email.
  • Storing Your Product– Once we bring the product in, we’ve got a warehouse equipped to store it until it sells.
  • Managing Storefront– We’ll post up a product page with all of the relevant descriptions and documentation-links to the product.
  • Shipping Your Product– Once the order comes in, we’ll grab it from the inventory shelves and ship it away.
  • Customer Service– If there are any problems before or after an order, our customer service team can help sort it out.
  • (First Level) Tech Support– Our crack technical support team can field initial tech questions (via email, chat, or phone calls), but we may have to refer the tough ones to you.

Your Responsibilities

  • Manufacturing– In this relationship, you’ll manage all of the part sourcing, manufacturing, and assembly responsibilities. That includes testing the product for complete functionality.
  • Keeping Supply Up with Demand– Some of the greatest products are sunk because they can’t stay in stock. We want to keep your product in stock as much as possible, so we’ll work with you ahead of time to understand the lead times of your product.
  • Documentation– Products that are well-supported, by datasheets, user’s manuals, and tutorials, really stick out to us. This is a load we’re willing to share (see below), but the most attractive products to us are those with the proper documentation to support them.
  • Replacements– No test procedure is perfect. Even the most battle-tested products may have a hidden flaw, and our customers will find it. If a defective product is discovered, we’ll lean on you to help replace it. (But the first defense is tech support. See below.)
  • Sticking Around– Whether your product needs future firmware updates or customer support, we need to be able to stay in contact with you for the long term.

Shared Responsibilities

This is still a team effort. You’ve got a product that you love and want to see in the hands of as many users as possible. And we want to help get the word out and move some product! Here are some duties we might share in our quest:

  • Marketing– We both want to see your product sell. We’ll pitch in on getting the word out, but we’ll need your help too.
  • Documentation/Tutorials– Generally we’re looking for products that are already well-supported through tutorials, datasheets, and user’s guides. We’re always excited about playing with new toys and documenting our experience, though – so we can help out with tutorials here and there.
  • Technical support– We can handle first level calls and emails. For the real brain-stumpers, we’ll refer customer questions to you, the all-knowing-product-creator.

Crowdfunded? Crowdfunding?

Many products in our catalog were born out of a crowdfunding website, like Kickstarter or Indiegogo. We’re happy to work with you, if your product is on this path, but there are a few caveats.

If you aim to approach us with a crowdfunded product, it’s best to do so after it’s been funded, or at least while it’s on a trajectory to be funded. But, most important of all, we need to know ahead of time how far out your product is from shipping. Obviously this is a sticking point for a lot of crowdfunded projects.

If your product failed to meet its crowdfunding goal, we might be able to work together to still make it a reality. Check out the next page to see how we can collaborate to produce your widget.

Option 2: SparkFun Manufactures, You Get a Royalty

This option is great for those looking to steer clear of the hassles of organizing manufacturing and generally running a business. We’ll keep in contact with you about further revisions or changes to your design, but we deal with the manufacturing risks. We buy the parts and the PCBs to build your widget. We monitor demand and order stock to meet it. Doing this we can often significantly reduce the cost of the BOM (bill of materials), and produce a reliable, steady supply of your widget.

An example of this relationship is the WAV Trigger. The hardware and firmware was spearheaded by Jamie Robertson with one of our engineers guiding the design to help leverage the SparkFun manufacturing process.

WAV trigger

We generally prefer Open Source Hardware designs for this relationship. Almost always those designs will be published under the creative commons license, so please take a look and decide if this is ideal for you.

Division of Responsibilities

Our load is much heavier in this relationship, but we still need some help from you. Here’s an example of what we’ll be doing, what we expect from you, and what duties we’ll share in:

SparkFun’s Responsibilities

  • Part Sourcing, Manufacturing, and Testing– We’ll handle everything that goes into manufacturing and assembling your product. From ordering PCBs, resistors, IC’s and other components, to stuffing the boards, and testing for complete functionality. These are company skills in which we place a lot of pride.
  • Managing the Storefront, and Shipping Orders– Just as any other product, your widget will get its own product page, and can be ordered via our online retail system.
  • Paying You a Percentage Royalty Per Product Sold– Before the product goes live, we’ll find an agreeable percentage royalty to pay you per product sold. Then sit back as we send you quarterly checks.
  • Customer Service and Technical Support– Our customer service team will tackle all of the customer’s order-specific questions. Our ace technical support crew will be trained up on your widget, and help answer any technical questions. Should it be necessary, we’ll handle replacements or returns.

Your Responsibilities

  • Initial Design (Prototype)– Come to us with as much information and tested hardware as you can. Usually we like to see at least an initial round of prototyped PCBs. We can work together from there to bring your product fully into the fold.
  • Keeping in Contact– We expect your product to be around for a while, and as long as it’s around we need you to be there too. For the product’s lifetime, we’ll need you to stay in contact for any questions or revisions that might come up.

Shared Responsibilities

  • Designing for (SparkFun) Manufacturing– More on this in the next section. We’ll assign one of our talented engineers to help create a SparkFun manufacturing-friendly design based as closely-as-possible on your original design.
  • Documentation– At the bare minimum we’ll want to release a hookup guide alongside your product. We can work together to help make this happen. We’re happy to help publish and create more content as required.
  • Getting the Word Out– Our marketing team will help let the world know about your product. We hope you will too!

Collaborative Design Process

Since we’ll be the ones manufacturing the board, there are certain design-for-manufacturability adjustments we usually like to make in order to keep costs down and production times minimal. These changes include:

  • “Scrubbing” the Bill-of-Materials (BOM)– We’ll look for minor BOM adjustments that allow us to use parts we already have in production stock rather than sourcing a new component. For example, we may want to swap out your TC1185 voltage regulator with a nearly-compatible (already in house) MIC5205. Or (assuming it doesn’t break anything) try to use a 2.2kΩ resistor instead of the 2.1kΩ you’ve spec'ed out.
  • PCB Layout Adjustments– We’ll want to use part footprints from our EAGLE libraries, and we may want to tweak some component placements to give the pick-and-place machines some breathing room.
  • Test Procedure Considerations– Every one of our boards is tested for complete functionality, in one way or another. On some designs this means adding test points, on others it means working in some test code under the hood of your firmware.

To help implement these DFM adjustments, one of our talented engineers will be assigned to work with you on bringing it in house. No matter what, we’ll work and communicate with you along the way to make sure our changes don’t alter your vision of your product.

As a result of the “design scrub”, this option takes longer than the previously mentioned route. We’ll go through at least one prototype round of the design to iron out any production issues, and just make sure the thing works as intended. If you want to get a head start, and make things go a little more smoothly, try design your product to follow as many of our design rules as possible. Check out the next page for more details on that!

Designing for (SparkFun) Manfuacture

The schematic and PCB designs are the heart of most SparkFun products. Over the last 10+ years, we’ve designed hundreds of unique PCBs, and produced millions of widgets, so we know what adjustments to the design will make our production process flow as smoothly as possible.

Those adjustments have found their way into a loose set of rules that we know to follow, but you might not. Designing your product with these rules in mind will give you a head start, and it’ll also make your product pitch more attractive to us. The less work we have to put into scrubbing your design, the faster we can start building and shipping it!

  • Design your PCB in EAGLE– The collaborative process is easiest if we’re both speaking the same EDA language. There are dozens of design tools out there, but we’ve gotten really accustomed to EAGLE. If you’re not familiar with the software, consider checking out some of our tutorials for help getting started.
  • Use our EAGLE libraries– By using our set of EAGLE footprints and parts, you’re better assured that the parts in your design will also be on our inventory shelves. You’ll also be using the footprints that our quality-assurance team has painstakingly crafted to help optimize AOI and other testing.
    • Unless your part is a kit, aim to use as many surface-mount (SMD) parts as possible. Our production team is most efficient, when they’re letting the pick-and-place/reflow oven combo do most of the busy work.
    • For common passives (resistors, capacitors, etc.), try to us 0603 parts or bigger (0805, 1206, …).
    • If a part has multiple footprints, and you’re unsure of which one to use, consider checking the Eagle files of one of our live boards and comparing against that.

PCB Design Specifications

In as many designs as possible, we try to keep our board layouts within this set of specifications:

PCB minimum specs

  • Minimum trace width: 0.006" (6 mil)
  • Minimum trace clearance: 0.008" (8 mil)
  • Trace-to-board edge clearance: 0.008" (8 mil)
  • Minimum via drill diameter: 0.01" (10 mil)
  • Default board width: 1.6mm

EAGLE Design Rules

Further to those minimum specifications, here are some more EAGLE-specific design rules:

  • Board Frame
    • Create the board frame on a 0.1" grid. Make the lower left corner start at (0, 0).
    • Change the line width of the board frame to 0.008"
    • Board frame will be square unless called for by special requirements of the design.
  • Grid
    • All parts are placed on a 0.005" grid. If possible, use a .05" grid.
    • Make sure all 0.1" headers are lined up on a 0.1" grid. Keep it breadboard compatible!
  • Packages
    • Use 0603 packages for resistors and capacitors.
  • Traces
    • Use 10 mil (0.010") traces in general.
    • 8 mil traces can be used when necessary, 6 mil is absolute minimum.
    • Use thicker traces (as thick as possible) on power and charging traces.
    • Keep at least 8 mil of space between traces.
    • Route with straight lines and 45 degree corners only. No right angles in trace routing, but T-intersections are okay.
    • Route from pads. Avoid routing into the pads- this causes traces to be not centered on a pad. Traces should enter and exit center of pad at 90 degree angle.
  • Pours
    • Use ground pours on the top and bottom layers.
      • Change the “Isolate” setting on ground pours to 12 mil (0.012").
  • Vias
    • If something is soldered into a hole (header, connector, prototype vias, etc), use a via with a larger annular ring so that it is easier to solder. For normal prototyping vias, use 0.04" hole with a 0.074" diameter.
    • Set the default via size to 0.020."
    • 0.010" is the smallest allowed via size. Only change from the default if absolutely necessary.
    • Via size is defined by the “Drill” parameter in the DRC.
  • Misc
    • Add a version code on the bottom copper layer, and revise the version code on every revision!
    • Use the standardized I2C layout: GND, VCC, SDA, SCL.
    • The autorouter can only be used on prototypes. Hand routing and touch-up of the autorouter is expected for production boards.

Make sure to load the Sparkfun.dru for the DRC check. Pull the most up-to-date version of the Sparkfun.dru from GitHub. Don’t use the default settings!

PCB Aesthetics (Labeling)

When the bare PCB is your product, it doesn’t hurt to dress it up and make the board look nice and polished. Here are some EAGLE-specific design rules that we follow to make our boards look as good as possible.

  • Labels
    • Label the name of the board appropriately.
    • Label any LED with its purpose (power, status, D4, Lock, etc).
    • Label all connectors (Vin, Port1, Batt, 5-9V, etc).
    • Label pins where applicable (Tx, Rx, Power, +, Charger, etc).
    • Label switches and switch states (On/Off, USB, etc).
    • Label any extra information (ie. axes on gyros, accelerometers, etc).
    • Makes sure labels are on a straight line- add a line in the tDocu layer to make sure the labels line up.
    • Text should be 0.032" minimum and 15% ratio, vector font.
  • Logos
    • Every board should have the full SparkFun logo or at least the smaller SFE Flame. Add the LOGO-SFE part to the schematic. Make sure to put this part in the lower right hand corner of the schematic.
    • Every board should have the Open Source Hardware Logo unless otherwise specified. Look for OSHW-LOGO in the library and add it to the schematic. This should go in the lower right hand corner as well.
  • Misc
    • Components that are grouped together in the PCB layout will be grouped together in the schematic. Draw boxes to show functional groups.

Pitching Your Product

Pitching a product can be a daunting task. You need to demonstrate how awesome your product is in both technical and marketable aspects. Here you’ll find a rundown on what a we look for when evaluating potential new products.

  1. Introduce yourself and, if applicable, your company. Talk about your company, other products you’ve designed, your market, and your involvement in the industry. Provide any relevant links, such as your website and product page.
  2. Lay your product spiel on us. There should be a clear, compelling reason for why this product was created. Explain what it does, how it does it, and some of the major design decisions.
    • Include the basics: specifications, applications, pricing, design files, and bill of materials if applicable.
    • A working prototype or product also really helps a pitch. It shows commitment via invested time and effort expended on working out the kinks. Additionally, it makes your product more enticing, since it represents significantly less risk.
    • Be careful of a common pitfall here! Too many features will drive up price, size, and complexity. There is a sweet spot for all products with just the right number of features for the majority of users. When we design products, we aim to tailor it for the 90% use case. This keeps the ease of use and price down while still maintaining value.
  3. Compare and contrast your product with similar, competing products.
    • Explain what makes your product unique and innovative. Show that there is significant differentiation between it and everything else out there. We need to understand why your product adds value over our current offerings.
    • Point out what void or market demand is met.
  4. Another important aspect of a product is the market. Present your expectations of the market and competition. This doesn’t mean a ten page report, but do your homework. Estimate how popular your product will be. Use real numbers over vague qualifications, projected average sales per month is a good example.
    • Price is especially important! Compare the prices and features of your product versus its competition.
    • Know how saturated the market is as well. If a product fits into a niche, that can be especially helpful.

Email Us!

Here at SparkFun we strive to be the place to get hard-to-find and innovative electronics. Additionally, we try to carry the extra parts and tools required for you to complete you project. We are always looking to expand our catalog and love to hear what customers and the community have created.

If either of these options sound like the opportunity you are looking for please shoot us an email at spark@sparkfun.com.


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

ADXL337 and ADXL377 Accelerometer Hookup Guide

$
0
0

ADXL337 and ADXL377 Accelerometer Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The ADXL337 and the ADXL377 are both small, thin, low power, complete 3-axis accelerometers with signal conditioned analog voltage outputs.

Here are photographs of each accelerometer breakout board which we created to make these small chips easier to use:

The ADXL337 and ADXL377 Breakout Boards

The primary difference between the two is the range of acceleration they measure. The ADXL337 measures acceleration with a full-scale range of ±3 g while the ADXL377 has a full-scale range of ±200 g for measuring more extreme changes in motion, shock or vibration.

Covered in this Tutorial

In this tutorial, we will help you learn how to use these accelerometers so you can quickly and painlessly integrate them into your project[s]. Here is what we’ll cover:

  • Hardware Overview– An overview of the ADXL337/ADXL377 IC’s, and their respective breakout boards we designed to make them simple to use.
  • Example Hookup– How to connect the accelerometers to the ubiquitous Arduino so we can start writing code to work with them.
  • Example Code– We’ve written example sketches that demonstrate how to collect sensor data as well as make sense of it.

Required Materials

You may also need a breadboard, jumper wires, and straight male headers to follow the example setup, if you don’t already have these or another way of connecting the Arduino to the breakout board.

Suggested Reading

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

  • Accelerometer Basics– This is a great primer on accelerometers – how they work, and why they’re used.
  • Accelerometer Buying Guide– If you’re not sure which accelerometer is best for you, check out this guide.
  • Logic Levels– The ADXL337/ADXL377 are 3.3V devices, so your analog to digital (ADC) readings will vary depending on whether you’re using a 5V or 3.3V micro! Both will work, just be aware of how it affects the values the microcontroller reads.

Hardware Overview

The Breakout Boards for the ADXL337 and ADXL377 break out the all the pins you’ll need to get the necessary data from the accelerometers.

Top down view of ADXL337 and ADXL377 breakout boards

As you can see, each breakout has the same pins broken out. Here is some information about each pin:

Pin LabelPin FunctionInput/OutputNotes
3.3VPower SupplyInputCan be between 1.8 - 3.6V.
XX axis accelerationOutputAnalog output whose voltage correlates to acceleration measured on the X axis
YY axis accelerationOutputAnalog output whose voltage correlates to acceleration measured on the Y axis
ZZ axis accelerationOutputAnalog output whose voltage correlates to acceleration measured on the Z axis
STSelf TestInputUsed to verify sensor functionality
GNDGroundInput0V, common voltage to share with microcontroller circuit

Voltage Supply Requirements

The big alert here is that the ADXL337 and ADXL377 both have a maximum voltage of 3.6V– that range applies to both the power supply and the self test pin. You can use a 5V or 3.3V micro with these sensors as long as you power the board with 3.3V. Be aware though, that your analog to digital (ADC) readings will vary depending on whether you’re using a 5V or 3.3V micro! Both will work, just be aware of how it affects the numeric values the microcontroller reads.

Fortunately, you don’t need a lot of power to make the accelerometers work. In normal operating mode they typically draw about 300µA.

Extra Hardware Notes

If you are powering either the ADXL337 or ADXL377 with 3.3V, a voltage reading of 1.65V on the X pin will correspond to an acceleration reading of 0g for both chips. However, if the X pin reads 3.3V, on the ADXL337 this means a force of 3g is being applied on the x axis while the same reading on an ADXL377 would indicated a force of 200g. The usage of both chips is essentially the same, but interpreting the readings is different due to the scale that each chip measures.

The ADXL377 also has 4 mounting holes, as opposed to just two, to allow for a more secure physical connection to your project since it will likely be subjected to more extreme force.

Also, for both chips, 0.01µF capacitors are used on the X, Y, and Z outputs. This means the maximum rate you can collect acceleration data from the IC’s is 500Hz.

Example Hookup

Soldering

Before you can plug your accelerometer breakout board into a breadboard and connect it to anything, you’ll need to solder connectors or wires to the breakout pins. What you solder to the board depends on how you’re going to use it.

If you’re going to use the breakout board in a breadboard or similar 0.1"-spaced perfboard, we recommend soldering straight male headers into the pins (there are also long headers if you need).

If you’re going to mount the breakout into a tight enclosure, you may want to solder wires (stranded or solid-core) directly into the pins.

Simple Hookup

This example will use an Arduino Uno to collect and interpret the sensor data from the ADXL337 or ADXL377. Since the sensors' outputs are analog, all we need are three wires between the Arduino’s ‘Analog In’ pins and accelerometer (aside from power and ground). While the following hookup diagram shows the ADXL337, the header and connections to the Arduino are the same for both boards. Here’s the hookup:

Fritzing hookup for the ADXL337

We simply have to supply the accelerometer with power (3.3V and GND), then hookup the X, Y, and Z lines of the sensor to ADC pins (A0, A1, and A2 respectively in this case). The self test pin (ST) can be left disconnected or connected to ground under normal operation. If you want to use the self test to double check the functionality of the sensor, tie it to 3.3V. Check the datasheet for more info.

Example Code

Now that your accelerometer breakout is electrically connected to your Arduino, it’s time to dive into the code. The full example sketch can be found in the github repository for either the ADXL337 or the ADXL377. The code is the same with the exception of the value for the scale variable.

The first two lines of code in the sketch setup configuration variables.

language:c
int scale = 3;
boolean micro_is_5V = true;

The variable scale is set to the full scale of the accelerometer measured in g forces. It is set to 3 for the ADXL337 and set to 200 for the ADXL377, since the sensors measure a ±3g and ±200g range respectively. The variable micro_is_5V is set to true if using a 5V microcontroller such as the Arduino Uno, or false if using a 3.3V microcontroller. We want to know this because it affects the interpretation of the sensor data we will read later on.

Next we use the setup() function in initialize serial communication so that we can later print sensor data to the Serial Monitor.

language:c
void setup()
{
  // Initialize serial communication at 115200 baud
  Serial.begin(115200);
}

Using the loop() function, we collect the sensor data, scale it to the appropriate units measured in g forces, and print both the raw and scaled data to the Serial Monitor. First, let’s look at how we read the sensor data.

language:c
void loop()
{
  // Get raw accelerometer data for each axis
  int rawX = analogRead(A0);
  int rawY = analogRead(A1);
  int rawZ = analogRead(A2);

We use the analog inputs A0, A1, and A2 on the Arduino and a few analog reads to get a number between 0 and 1023 that corresponds to the voltage on those pins. Those voltages reflect the latest acceleration measurement from the sensor. As an example, if the ADXL337 is measuring 3.3V on the X pin, this means it is measuring +3g’s on the X axis. This in turn is measured by the microcontroller. If you’re using a 3.3V microcontroller, the analog read will return 1023 and store that value in the variable rawX. If you’re using a 5V microcontroller, the analog read will return 675 and store that value in that same variable instead. That’s why it’s important to set the variable micro_is_5V correctly so we know how to interpret these raw values.

Knowing the microcontroller’s voltage, will allow us to scale these integers into readable units measured in g forces correctly. Here’s how we scale these values into more meaningful units.

language:c
 float scaledX, scaledY, scaledZ; // Scaled values for each axis
  if (micro_is_5V) // microcontroller runs off 5V
  {
    scaledX = mapf(rawX, 0, 675, -scale, scale); // 3.3/5 * 1023 =~ 675
  }
  else // microcontroller runs off 3.3V
  {
    scaledX = mapf(rawX, 0, 1023, -scale, scale);
  }

We first declare the scaled variables as floats, since we want decimal places. We then check whether the microcontroller is running off of 5V or 3.3V with the boolean micro_is_5V. Based on that we scale the raw integer value of x, rawX, into a decimal value measured in g forces, called scaledX using a mapping function. We also do this for the Y and Z axis however I left those out above since they follow the exact same process. Remember that the 675 came from the fact that a 5V Arduino will measure 3.3V as 675, while a 3.3V Arduino will measure 3.3V as 1023.

The mapf() function exists in the sketch and works exactly the same as Arduino standard map() function, which you can reference here. The reason I didn’t use the standard map was because it deals with integers only, and, for our purposes, we need decimal places. Thus, I essentially rewrote the exact same function using floats instead.

After scaling, we print both the raw and scaled data to the Serial Monitor. You probably only care to view the scaled data unless your debugging, however I left both there so you can compare. Here’s how to print the raw and scaled data for each axis:

language:c
  // Print out raw X,Y,Z accelerometer readings
  Serial.print("X: "); Serial.println(rawX);

  // Print out scaled X,Y,Z accelerometer readings
  Serial.print("X: "); Serial.print(scaledX); Serial.println(" g");

This allows you to see the data in both forms. Afterward, we use a delay before making extra sensor reads.

language:c
delay(2000);

In the example sketch, we pause for 2 seconds (2000 milliseconds) since we are simply printing to the Serial Monitor for viewing and learning purposes. In your actual project, you can read the sensor at 500Hz at most, which means you want a minimum of 2 milliseconds in between sensor reads.

Then it’s back to the beginning of loop(). Hope this helps you collect and analyze accelerometer data in your own project.

Resources & Going Further

Thanks for reading! By now you’ve become familiar with both the hardware and software to use the ADXL337 and ADXL377 accelerometers. We’re excited to see what you build with these sensors. The following resources may be helpful for you when building your related projects:

Now go create something awesome with your accelerometer. Need some inspiration? Check out these other SparkFun tutorials:


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


AD8232 Heart Rate Monitor Hookup Guide

$
0
0

AD8232 Heart Rate Monitor Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The AD8232 is a neat little chip used to measure the electrical activity of the heart. This electrical activity can be charted as an ECG or Electrocardiogram. Electrocardiography is used to help diagnose various heart conditions. Now for the disclaimer:

This device is not intended to diagnose or treat any conditions.

AD8232

Covered in this Tutorial

In this tutorial, we will go over the basics for getting your AD8232 Heart Rate Monitor up and running. First, an overvew of the board and all its features will be presented. Then, we’ll show you how hook it up to your favorite microcontroller and how to create visual data using Processing.

Suggested Reading

If you are not familiar with any of the following concepts, you may want to review them before moving ahead.

Understanding the ECG

In general terms, lets look at what an ECG is representing and how we’re able to sense it. The ECG is separated into two basic Intervals, the PR Interval and the QT Interval, described below.

Note: All information comes from the Waves and Intervals section of the ECG Wikipedia page .

alt text

Credit Wikipedia.org

alt text

Diagram of the heart. Credit Wikipedia.org

PR Interval

The PR interval is the initial wave generated by an electrical impulse traveling from the right atrium to the left. The right atrium is the first chamber to see an electrical impulse. This electrical impulse causes the chambers to “depolarize”. This forces it to contract and drain deoxygenated blood from both the Superior and Inferior vena cava into the right ventricle. As the electrical impulse travels across the top of the heart it then triggers the left atrium to contract. The left atrium is responsible for receiving newly oxygenated blood from the lungs into the left ventricle via the left and right pulmonary veins. The pulmonary veins are red in the diagram because they are carrying oxygenated blood. They are still called veins because veins carry blood towards the heart. Science!

QT Interval

The QT Interval is where things get really interesting. The QRS is a complex process that generates the signature “beep” in cardiac monitors. During QRS both ventricles begin to pump. The right ventricle begins to pump deoxygenated blood into the lungs through the left and right pulmonary arteries. The pulmonary arteries are blue in the diagram because they are carrying deoxygenated blood. They are still called arteries because arteries carry blood away the heart. Science, Again! The left ventricle is also begining to pump freshly oxygenated blood through the aorta and into the rest of the body. After the initial contraction comes the ST segment. The ST segment is fairly quiet electrically as it is the time where the ventricals waiting to be “re-polarized”. Finally the T wave becomes present to actively “re-ploarize”, or relax the ventricles. This relaxation phase resets the ventricles to be filled again by the atriums.

alt text

Heartbeat with corresponding ECG Credit Wikipedia.org

Connecting the Hardware

In this guide, we’ll connect the AD8232 Breakout to an Arduino microcontroller. We will build a simple cardiac monitor that will allow you to measure the electrical activity of the heart in real time!

Materials required for this example


Pin Connections

The AD8232 Heart Rate Monitor breaks out nine connections from the IC. We traditionally call these connections “pins” because they come from the pins on the IC, but they are actually holes that you can solder wires or header pins to.

alt text

We’ll connect five of the nine pins on the board to your Arduino. The four pins you need are labeled GND, 3.3v, OUTPUT, LO-, and LO+.

Board Label Pin FunctionArduino Connection
GNDGroundGND
3.3v3.3v Power Supply3.3v
OUTPUTOutput SignalA0
LO-Leads-off Detect -11
LO+Leads-off Detect +10
SDNShutdownNot used

Connecting Headers to the Board

You can use any method you’d like to make your connections to the board. For this example, we’ll solder on a five-pin length of male-male header strip and use a breadboard and jumpers to make our connections.

alt text

Headers installed

Follow the diagram below, to make necessary connections. The SDN pin is not used in this demo. Connecting this pin to ground or “LOW” on a digital pin will power down the chip. This is useful for low power applications.

alt text

Connection Diagram

Now that the electronics are complete, let’s look at sensor pad placement. It is recommended to snap the sensor pads on the leads before application to the body. The closer to the heart the pads are, the better the measurement. The cables are color coded to help identify proper placement.

Cable Color Signal
BlackRA (Right Arm)
Bluecolor>LA (Left Arm)
Redcolor>RL (Right Leg)

alt text

Sensors connected to Heart Monitor

alt text

Typical Sensor Placements

Uploading the sketch and connecting with Processing

By this point, you should have the hardware connected and ready.

The example sketch can be found on github here You can cut and paste the code straight from github or clone the repository and open the file. For more on using the Sparkfun Github repositories, read this handy tutorial. If you’ve never worked with the Arduino IDE before, please see this tutorial.

alt text

Upload sketch to Arduino Pro-Mini

Now that you have a sketch running, Let’s get the processing sketch ready. The processing sketch will give you a visual output of what’s going on. The example processing sketch can be found here.

alt text

Run the Processing sketch

If the processing sketch does not work, you may need to modify the following line:

myPort = new Serial(this, Serial.list()[2], 9600);

You may need to change the paramter inside Serial.list()[N]. A List of available COM ports will appear in the lower portion of the sketch window. Remember that COM port selection begins at 0. Typically your Arduino will appear as the highest COM number if it is the only device connected to your computer.

alt text

The Arduino shows up as COM38. This is found in the Serial List at array element “2”.

If everything is working correctly, you should see a nice box pop up and start displaying the output signal.

alt text

“Normal” heart rate of an SFE engineer

If your subject decides to remove the sensors, the leads off detection will kick in and display a flat blue line.

alt text

“Flight, we just lost Lovell!”

Tips and Tricks

ECG’s are notoriously noisy. This is because you are measuring muscle activation. The further sensor pads are from the heart, the more muscle noise you will see. These are commonly referred to as “Motion Artifacts”. So here are some simple tips to improve the signal quality.

  • Keep sensor pads as close to the heart as you can.
  • Make sure the RA and LA sensor pads are on correct sides of the heart.
  • Try not to move too much while taking a measurement.
  • Try to use fresh pads for each measurement. The pads loose the ability to pass signals with multiple applications.
  • Prep and clean the area you plan to stick pads. This will help make a good connection (hair is not a good conductor).
  • You may have to adjust sensor placement for different individuals.

Resources and Going Further

Thanks for reading. For more resources on the AD8232 Heart Rate Monitor, check out the following links:

For more Electronics Fun, check out these other SparkFun tutorials:

More Biometric products offered by Sparkfun:


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

MS5803-14BA Pressure Sensor Hookup Guide

$
0
0

MS5803-14BA Pressure Sensor Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

 MS5803-14BA Breakout Board

The MS5803-14BA is a pressure sensor with an I2C (“Wire”) and SPI interface.

Pressure sensors measure the absolute pressure of the fluid around them. This includes air, water, and anything else that acts like a viscous fluid. Depending on how you interpret the data, you can determine altitude, water depth, or any other tasks that require an accurate pressure reading.

Covered in This Tutorial

We will show you how to connect this sensor to an Arduino microcontroller and use the included software library to get measurements out of the sensor. We’ll also show you how to interpret the readings showing changes in altitude and water depth.

Suggested Reading

This part is easy to use. But before you start, we recommend the following background knowledge:

Connecting the Hardware - I2C

In this example, we will communicate with the MS5803-14BA using the I2C interface.

Connection Names

The MS5803-14BA Breakout Board breaks out seven connections from the IC. We traditionally call these connections “pins” because they come from the pins on the IC, but they are actually holes that you can solder wires or header pins to.

alt text

We’ll connect four of the seven pins on the board to your Arduino. The four pins you need are labeled GND, VCC, SCL, and SDA.

Connecting Headers to the Board

You can use any method you like to make your connections to the board. For this example, we’ll solder on a seven-pin length of male-male header strip, and use male-female jumper wires to connect the MS5803-14BA to your Arduino.

Solder a 7-pin length of male-male header to the board. You can solder it to either side. The bottom is more useful for breadboards, and the top is more useful for jumper wires.

alt text

Connecting the Board to your Arduino

When you’re done soldering, connect the GND, 3.3v, SDA, and SCL pins to your Arduino. Different Arduino models use different pins for the I2C interface; use the following chart to determine where to plug everything in.

IMPORTANT: Connect the power pins (3.3v and GND) ONLY to a 3.3V supply. Larger voltages will permanently damage the part. Note that because I2C uses open drain drivers, it is safe to connect the I2C pins (DA and CL) to an I2C port on a 5V microprocessor.

MS5803-14BA labelPin functionArduino connection
GNDgroundGND
3.3v3.3V power supply3.3V
SDAI2C data Any pin labeled SDA, or:
Uno, Redboard, Pro / Pro MiniA4
Mega, Due20
Leonardo, Pro Micro2
SCLI2C clock Any pin labeled SCL, or:
Uno, Redboard, Pro / Pro MiniA5
Mega, Due21
Leonardo, Pro Micro3

alt text

Once you have the MS5803-14BA connected to your Arduino, we’re ready to play with the software.

Installing the Arduino Library

Libraries are collections of software functions geared towards a single purpose, such as communicating with a specific device. Arduino comes with a number of built-in libraries that help you do advanced tasks. We’ve written an Arduino library called SFE_MS5803_14BA_I2C that allows you to easily talk to the MS5803 sensor. This library is not included with the stock Arduino software, but don’t worry, installing new libraries is easy.

If you’d like to interface the MS5803 to a microcontroller other than an Arduino, the C++ source code in the library and the information in the datasheet may be helpful when writing your own code.

1. Install the Arduino IDE

If you don’t already have the Arduino IDE (Integrated Development Environment) installed, download the version for your system (Windows, Mac, Linux) from http://arduino.cc/en/Main/Software and install it following the instructions on that site.

If you need help installing the IDE, check out our tutorial.

2. Install the SFE_MS5803_14BA_I2C Library

User-installed libraries live in a “libraries” folder within your personal Arduino sketch folder. On Windows systems your personal sketch folder is located in “My Documents/Arduino”. On Mac computers, it’s “~/Documents/Arduino”. On Linux it is usually “~/Arduino/sketchbook”. Locate your personal Arduino sketch folder and open it so you can drag new files into it.

Now download the latest MS5803 software archive from this link: https://github.com/sparkfun/MS5803-14BA_Breakout/archive/master.zip. You can either save the file to your system and open it later, or open it directly.

(Note that you can find the .zip file for any Github repository by looking for the “Download ZIP” button on the main page:)

alt text

Open the .zip file you just downloaded. (On most systems you should be able to double-click it to show the included files.) Open the folder called “MS5803-14BA_Breakout-master”, then “Libraries”, then “Arduino”. You should now see a folder called “SFE_MS5803_14BA_I2C”. Drag the “SFE_MS5803_14BA_I2C” folder from the .zip folder into your personal Arduino sketch folder. If you get a warning that there is already a libraries folder there, that’s fine. It just means you’ve already installed some libraries, which is great! Just tell your system to go ahead and overwrite them, which sounds alarming but will only add the new library to the existing folder.

alt text

That’s it! Now restart the Arduino IDE and you should be ready to go.

If any of these instructions are unclear, you can find more detailed instructions in our installing an arduino library tutorial.

Running the Example sketches

Running the Example Sketch

The library you just installed includes an example sketch that show basic operation of the MS5803. This are designed to be a starting point for writing your own code.

After you install the library, run the Arduino IDE, and open the following menu item: File / Examples / SFE_MS5803_14BA / SFE_MS5803_14BA_I2C_demo.

(If you don’t see this menu item, you may not have installed the library correctly, or didn’t restart the Arduino IDE. Take another look at the library installation page to see if you missed any steps.)

alt text

When the example opens, upload it to your Arduino (remember to select the correct board type and serial port), and open the Serial Monitor to 9600 baud. You should see some diagnostic information (if it can’t find the device, double check your hardware connections) followed by measurement readings.

Alternative Arduino Interfaces

$
0
0

Alternative Arduino Interfaces a learn.sparkfun.com tutorial

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

Overviewing the Options

Arduino is awesome! It’s our go-to electronics education platform, and it’s our top choice for rapid prototyping, but it isn’t for everyone. Maybe it’s the cryptic language, or the Java-based IDE, or maybe it’s just the teal window border – regardless of your reasoning, if you’re trying to escape the Arduino IDE, here are a few alternatives we’d like to share.

The Arduino alternatives covered in this tutorial range from simple, introductory graphical programming to web-based Arduino interfaces for your web browser. Here’s a quick overview of each interface covered, we’ll go into further detail later on:

Codebender – “Cloud”-enabled, Browser-Based Arduino Programming

Codebender is an online development environment for Arduino. With Codebender, all of your code writing, testing, storing, sharing, even uploading occurs in the “cloud”, through your web browser.

Codebender example

With the help of a browser plugin (available for Chrome or Firefox), Codebender can even flash code straight to an Arduino connected to your computer. And, of course, the Serial Monitor is built-in as well for simple debugging.

Codebender is especially powerful if you want to socially code. It’s easy to share your code with others, or piggyback of Arduino sketches already written. There’s a great community springing up around it.

Check out the Codebender section of this tutorial for an introduction to the interface.

ArduBlock – A Visual Programming Arduino Extension

ArduBlock is a graphical programming add-on to the default Arduino IDE. Instead of memorizing cryptic functions, forgetting semicolons, and debugging code, ArduBlock allows you to build your Arduino program by dragging and dropping interlocking blocks.

ArduBlock example

ArduBlock is a perfect interface if you’re just getting into programming, electronics, or Arduino. Check out the ArduBlock section of this tutorial for an introduction and quick getting started guide.

Minibloq – Visual Programming Standalone Software

In the same vein as ArduBlock, Minibloq is a graphical programming environment where groups of blocks are stacked on top of each other to create your program. Unlike ArduBlock, however, Minibloq is a stand-alone program – no Arduino install required.

Minibloq example

One of Minibloq’s most powerful features is its real-time code generation – as you drag blocks into your program, the equivalent code is generated concurrently. This makes Minibloq an excellent tool for beginners to intermediate programmers.

Check out the Minibloq section of this tutorial for an introduction to the interface.

…and Beyond

Those are the alternatives we’ll be discussing in this tutorial, but there are many others worth checking out, including:

  • Scratch for Arduino– More visual programming! Scratch for Arduino (S4A) is a riff on the popular Scratch programming environment. If you’re an experienced Scratch user, this is most definitely worth checking out!
  • Modkit– After a successful Kickstarter campaign, Modkit is well on it’s way to producing another great visual alternative to Arduino. Check out their website and get a feel for their browser-based visual environment.
  • Arduino IDE for Atmel StudioAtmel Studio is an incredibly powerful tool for programming and debugging AVR chips like those on the Arduino. If you’re looking for a more advanced approach to Arduino, or Atmel chips in general, check out this extension to Atmel Studio.

alt text

This extension can be an extremely powerful tool – complete with breakpoint implementation and a host of features you may be used to from more advanced IDE’s.

CodeBender

Codebender takes the Arduino IDE to the “cloud”. Using Codebender, you can write, compile, and run your code all through a web browser.

alt text

Codebender has all of the features you’d find in normal, “offline” Arduino, and even some that are unique to the web-based IDE. It’s an awesome tool if you’re into sharing your code, contributing to others, or just discovering what other Arduino users are up to.

Setting up Codebender is super quick-and-easy: visit the website, create an account, install the plugin, and start coding/uploading! There’s no waiting for 100MB+ downloads, or installing any software, just pure cloud-based, hardware-programming fun.

Social Coding

Since Codebender is cloud-based, it lends well to “social coding”. They’ve got an amazing system geared around DIT (do it together), making it easy to share code and piggyback off of others.

Every sketch you write can easily be embedded into another webpage, so your friends and readers can easily peek through your code. With the right browsers (Chrome or Firefox) and plugins installed, they can even upload it to their Arduino directly from your web page. Try it out!

Useful Features

At this point, Codebender can match the Arduino IDE feature-for-feature – you can upload code, interact with the serial monitor, and even upload via an AVR programmer. Plus, there are all sorts of features unique to the web-based IDE.

You can easily upload your own library; that is, if you can’t find the one you need among the hundreds of libraries that they already host.

alt text

If you’re stuck debugging your code, they’ve beefed up the error output window to make missing semicolons or typos all the more apparent.

alt text

Codebender just keeps getting more-and-more awesome. They’ve got a great team continuously adding new features. Plus it’s open-source, so you can contribute or make your own fork.


Whether you’re an experienced user, or an Arduino newbie, we really encourage you to check Codebender out. Head over to their home page, create an account, install the plugin, connect your Arduino, and start code bending!

ArduBlock

ArduBlock is a programming environment designed to make “physical computing with Arduino as easy as drag-and-drop.” Instead of writing code, worrying about syntax, and (mis)placing semicolons, ArduBlock allows you to visually program with an snapped-together list of code blocks.

alt text

ArduBlock builds on the simplicity of Arduino, and creates a perfect beginner gateway to physical computing. Instead of tearing your hair out debugging, you can spend your time creating!

Installing ArduBlock

ArduBlock is something of an “add-on” to Arduino, so it requires that you have the Arduino IDE installed. The benefit of that, though, is – because Arduino is multi-platform – ArduBlock works on Windows, Mac, or Linux. Plus, having Arduino already present makes the transition from visual programming to text programming easier, when the inevitability approaches.

Installing ArduBlock can be a little tricky – there’s no installer, just a Java file that needs to be stored in a very specific location. Follow the steps below to install it:

  1. Download and Install Arduino (if you haven’t already) – Ardublock is an extension of the default Arduino IDE, so you’ll need to have Arduino installed on your computer to run it. Check out our Installing Arduino IDE tutorial for help with that.
  2. Download ArduBlock– Click the link to the left, or head over to the ArduBlock Sourceforge page to find the latest and greatest version.
  3. Identify your Arduino Sketchbook location– This is a folder on your computer where your sketches and libraries are saved by default. To find your sketchbook location, run Arduino, and open Preferences by going to File > Preferences. The contents of the top text box defines your sketchbook location. Memorize that location and close Arduino.

  4. Create [sketchbook]/tools/ArduBlockTool/tool/– The Ardublock file you downloaded earlier needs to live in a very specific location within your Arduino sketchbook. Navigate to your sketchbook, then create a nest of three directories: tools>ArduBlockTool>tool (watch out, each folder is case sensitive).
  5. Paste “ardublock-xxxxxxxx.jar” Into /tool/– Paste the Ardublock file you downloaded – a JAR (Java ARchive) file – into the last folder in the nest you created.


  6. Start Arduino– Or restart it if it was open.
  7. Select the Board and Serial Port– Just as you would if you were using Arduino, make your board and serial port selections from the “Tools” menu.
  8. Open ArduBlock– Run ArduBlock by clicking Tools>ArduBlock. If you don’t see an entry for ArduBlock here, double-check to make sure your directories are all correctly typed and cased.


ArduBlock works hand-in-hand with the Arduino IDE – it relies on the IDE being open in the background, so don’t close the Arduino window!

Using ArduBlock

The ArduBlock window is split into two halves. On the left there are “bins”, which store every possible block you can add to your sketch. The blank, gray slate to the right of that is where you “draw” your sketch. To add a block to your sketch, simply drag it from the bin into the blank, gray area.

To begin, every ArduBlock sketch requires a Program block, which you can find in the “Control” bin. The Program block defines the setup and loop functions that every Arduino program requires.

Ardublock program location

From there, you can drag more Blocks over, snapping them into either the loop or setup sections. Here, try making a blink program. The set digital pin blocks, which effect a digital output (analogous to Arduino’s digitalWrite function), are found under the “Pins” bin. The delay milliseconds block, found under “Control”, is analogous to a delay Arduino function.

Ardublock blink program

Then click Upload to Arduino to send your drawing off to your Arduino board. You can ALT+TAB back over to the Arduino window to check your code upload status.

Upload program

After you’ve successfully uploaded your first sketch, continue to play around and explore the contents of the other bins!

ArduBlock Tips & Tricks

You can clone blocks, or groups of blocks, by right clicking and selecting “Clone”. Everything from the block you right-clicked to the bottom of that “group” will be copied and pasted into the top-left corner of the window. This is a huge timesaver for bigger drawings.

alt text

You can temporarily remove code from your sketch by dragging it out of the entirety of the “Program” block. Anything not connected to the main Program block will be ignored when your code is compiled. This is a great debugging tool – you can remove a block of code from program execution, while not actually deleting it, much like commenting out code.

alt text

Finally, if you peek back over at the Arduino window, after you’ve uploaded an ArduBlock drawing, you may notice something different. To create your code, the ArduBlock program simply parses your blocks and spits the equivalent Arduino code over into the Arduino window.

alt text

This becomes a great learning tool if you’re interested in transitioning from graphical programming to text.

ArduBlock Resources

Minibloq

Minibloq is a visually-driven programming environment for Arduino and other physical computing devices. Instead of tearing your hair out over syntax, variable types, compilation errors, and the other annoyances of code, Minibloq allows you to construct your program using a series of graphic blocks.

alt text

Beyond the gentle, visual introduction to programming, one of Minibloq’s coolest features is its real-time code generator. As you add blocks to the Minibloq drawing, an equivalent line of code will be generated in the next window over. This is an excellent tool if you’re looking to make the leap from graphic programming languages to text.

Minibloq has a major focus on robotics. It includes support for popular robotics platforms, like Multiplo and our RedBot Kit.

Getting Started with Minibloq

Head over to the Minibloq download page to grab the latest version. Be aware that, for now at least, Minibloq is (mostly) only Windows compatible.

By default the interface is split into three columns – hardware view, Minibloq editor, and code editor. On the main toolbar up top, you can choose which columns you want to display or hide.

alt text

The hardware section allows you to pick your Arduino-compatible board among options including RedBoard, Arduino Uno, Arduino Leonardo, RedBot Kit, and others.

The middle, Minibloq editor window is where you’ll spend most of your program-building time. This view works hand-in-hand with the detatched “Actions” window, where you click buttons to add blocks to your program.

Finally, there’s the “Generated code” view on the right, which is the most powerful learning feature of Minibloq. It’s a huge aide in easing the transition from visual programming to “coding” programing.

Creating a Minibloq drawing takes some time to get used to. Try creating a blink program to get a feel for it:

alt text

Then check out some of the included examples by going to File>Examples. Among the many example sketches are a collection of SparkFun Inventor’s Kit and RedBot Kit specific programs. Check ‘em out!

Minibloq Resources


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

Digital Sandbox Experiment Guide

$
0
0

Digital Sandbox Experiment Guide a learn.sparkfun.com tutorial

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

Welcome to the Digital Sandbox!

The Digital Sandbox is a learning platform that engages both the software and hardware worlds. It’s powered by a microcontroller that can interact with real-world inputs – like light or temperature sensors – while at the same time controlling LEDs, motors, and other outputs. The Digital Sandbox is equipped with everything, on board, that you will need to complete 13 experiments including controlling an LED, measuring how loud things are, detecting the temperature is, and more. Think of this as a SparkFun Inventor’s Kit all in one board!

DS Cover Graphic

This tutorial walks you through a series of experiments that demonstrate how to program the Digital Sandbox using ArduBlock a graphical programming language for Arduino.

If you’re interested in programming your Sandbox using the regular Arduino programming language, check out our parallel tutorial: the Digital Sandbox Arduino Companion.

Experiment List (Table of Contents):

  1. Setup, Loop, and Blink
  2. Exploring Blink
  3. Multi-Blink
  4. Dimming (the Hard Way)
  5. Dimming (the Easy Way)
  6. Color Mixing
  7. Number Storage with Variables
  8. If This Then That
  9. The Reaction Tester
  10. Serial Calculator
  11. Do the Analog Slide
  12. Automatic Night Light
  13. Thermal Alert!
  14. Sound Detecting
  15. Opto-Theremin (Addon)
  16. Serial Motoring (Addon)
  17. Servo Sweeper (Addon)

Please note that experiments 14, 15, and 16 require the Digital Sandbox Add-On, which can be purchased separately.

What is the Digital Sandbox?

The Digital Sandbox is a learning platform that engages both the software and hardware worlds. It’s powered by a microcontroller that can interact with real-world inputs – like light or temperature sensors – while at the same time controlling LEDs, motors, and other outputs.

By interfacing the Sandbox to your PC or Mac via a USB cable, the Sandbox can be programmed using the popular Arduino programming environment. To further simplify the learning experience, we’ve designed the Sandbox and this guide around using a simple, “blocky”, programming addon to Arduino – Ardublock.

The Anatomy of the Digital Sandbox

The Digital Sandbox includes a variety of on-board inputs and outputs that are commonly encountered in the world of electronics. Here is an overview of what’s included on the board:

Annotated image of the Digital Sandbox

  1. USB Mini-B Connector– Used to connect to a computer.
  2. JST Right-Angle Connector– Used to supply power to the board.
  3. Slide Switch for Charging– Used to charge a lithium polymer battery that is plugged into the two-pin JST connector, while the Digital Sandbox is connected to a computer and the slide switch is in the “ON” position.
  4. Reset Button– This is a way to manually reset your Digital Sandbox, which will restart your code from the beginning.
  5. Slide Switch (Pin 2)– On or off slide switch.
  6. LEDs (Pins 4-8)– Use one or all of the LEDs (light-emitting diodes) to light up your project!
  7. LED (Pin 13)– Incorporate this into your sketch to show whether your program is running properly.
  8. Temperature Sensor (Pin A0)– Measures ambient temperature.
  9. Light Sensor (Pin A1)– Measures the amount of light hitting the sensor.
  10. RGB LED (Pins 9-11)– RGB (red/green/blue) LEDs have three different color-emitting diodes that can be combined to create many colors.
  11. Slide Potentiometer (Pin A3)– Change the values by sliding it back and forth.
  12. Microphone (Pin A2)– Measures how loud something is.
  13. Push Button (Pin 12)– A button is a digital input. It can be either “on” or “off.”
  14. Add-on Header (Pin 3)– Three-pin header for add-ons. Example add-ons are servos, motors and buzzers.

Digital Sandbox Baseplate Setup

Secure the Digital Sandbox board to the baseplate with the included Phillips-head screws.

baseplate assembly

Finger-tighten the screws for easy removal later.

Setting up Arduino and ArduBlock

This page will help you wrangle the computer end of the Digital Sandbox. That process includes downloading and installing the software, installing drivers on you computer, and setting up the Arduino environment to work with your Sandbox. Follow along, and you’ll be blinking LEDs in no time!

Download Arduino, ArduBlock, and the Examples

First things first, you’ll need to download some software. There are two options here: if you already have Arduino installed, follow the directions for installing the Digital Sandbox Arduino addon. If you don’t have Arduino, follow the directions immediately below.

Don’t Have Arduino?

We’ve packaged up a custom version of the Arduino software (version 1.0.5), which includes ArduBlock and the Sandbox examples used throughout this guide. Click one of the links below to download the software, make sure you grab the version that matches your system:

The Arduino software comes packaged in an archived, .ZIP format. Once you’ve downloaded the ZIP file, you’ll need to extract it. Both Windows (use the built-in extract wizard) and Mac (double-click to open) machines should have built-in tools for unzipping.

Mac users can simply run the Arduino application from the extracted folder, or move it into a preferred directory (e.g. Applications) and then run it. Also move the Digital Sandbox Examples folder to your preferred location.

alt text

Windows users can move the Arduino folder to a preferred location. The Sandbox examples are included as well, in a folder named “Digital Sandbox Examples.”

Once you’ve installed Arduino, continue on below with installing the Sandbox drivers.

Already Have Arduino?

If you already have Arduino installed, you can save some bandwidth and just download the Sandbox addon, which includes ArduBlock, the Digital Sandbox hardware definitions, and the example files. Click the link below to download the Arduino addon folder:

Download the Sandbox Arduino Addon

All of the addon items are archived in a ZIP folder. To install the addon extract the ZIP file into your computer’s Arduino sketchbook directory. This is a folder on your computer where your sketches and libraries are saved by default. To find your sketchbook location, run Arduino, and open Preferences by going to File > Preferences. The contents of the top text box defines your sketchbook location. Memorize that location and close Arduino.

Arduino sketchbook location

Then extract the contents of the Sandbox_Addons.zip file into that location.

alt text

Install Drivers

Once you have downloaded and extracted the Arduino software connect the Digital Sandbox to your computer.

Sandbox connected to computer

Once the board is connected, you will need to install drivers. Please go to www.sparkfun.com/ftdi for instructions specific to your operating system.

Open Arduino and ArduBlock

ArduBlock is an add-on that exists inside the Arduino software. To run it, first open the Arduino program. Windows users should run Arduino.exe; Mac users can run the Arduino application.

alt text

Let’s do some preparation before opening ArduBlock. First, go to the Tools menu, hover over Board and select Digital Sandbox.

Tools > Board > Digital Sandbox

Next, go back to the Tools menu, hover over Serial Port and select the serial port number that matches your Sandbox board.

Windows serial port selection

  • Windows users: This is likely to be COM2 or higher (COM1 is usually reserved for hardware serial ports). To find out, you can disconnect your Sandbox and re-open the menu; the entry that disappears should be the Sandbox. Reconnect the board and select that serial port.
  • Mac users: On the Mac, this should be something with “/dev/tty.usbmodem” or “/dev/tty.usbserial” in it.

Finally, to open ArduBlock, go to Tools and select ArduBlock.

Tools > ArduBlock

What opens next is the ArduBlock interface. Make sure the Arduino window remains running in the background. If you close that, ArduBlock will close as well.

Example of ArduBlock interface

Note: If you don’t see ArduBlock under the Tools menu, you may need to manually install it. Please visit this tutorial for help adding ArduBlock to a previous Arduino installation.

When faced with a new platform, a coder’s first task is to write a “Hello, world” program. Usually a “Hello, world” program actually prints those comforting words on a screen. The Digital Sandbox doesn’t give us a screen to print words on, but we do have LEDs! Wonderful, blinky, bright, shiny LEDs. Instead of printing words, let’s blink an LED to say “Hello, world.”

Background Information

This experiment introduces the general concept of physical programming. Changes you make in your program actually affect what’s happening on the Digital Sandbox board.

This drawing also serves to introduce a couple of the most fundamental Arduino programming concepts: setup and loop.

Active Parts

Experiment 0 active parts

Code Components

This code drawing requires two blocks (well, sort of three):

alt text

  • Program: This block is required for every single ArduBlock drawing ever! You can only have one per drawing. Program always has two slots for blocks – one named “setup” and another named “loop.” Find this block under the Control bin.
  • Blink: Find this block under the Pins bin. This block “blinks” a pin on the Digital Sandbox. The Blink block actually gives you two blocks for the price of one! It also includes a pink block with the number 13 inside it. Leave that block alone for now, we’ll discover its use in later experiments.

Do This

With this pair of blocks, there are only two functional drawings we can create. You can either stick the Blink block under the setup section of program, or under the loop section.

alt text

Try sticking the Blink block under setup, then click Upload to Arduino.

Upload to Arduino

Keep your eyes glued to the Digital Sandbox as the code uploads. You’ll see the red and green RX and TX LEDs blink like crazy as code is sent from computer to Sandbox. Pay extra close attention to what happens after the red and green LEDs do their dance. Do you notice anything?

Now move the Blink block from setupto loop, and do the Upload to Arduino jig again. Notice anything different?


Every Arduino program requires two functions always be present: setup and loop. From the names of these functions, it should be pretty clear what their job is.

Setup runs once, at the very beginning of the program. Its purpose is usually to set the platform up for the rest of its lifecycle (until the Sandbox is reset, or loses power). As we continue on with these experiments, you’ll have a greater understanding of what kind of things need to be set up in advance.

If setup sets the Sandbox up, Loop must…loop. Code in this block will execute sequentially and endlessly. Once we get to the bottom of loop, we jump right back up to the top and do it all over again. This looping will continue until you either reset or remove power.

Further Explorations

  • What happens when you press the reset button?
  • What happens if there’s nothing in either setup or loop (move the Blink block out)?
  • What happens if you add a second Blink block to the drawing? Regardless of where you put it, can you discern which of your Blink blocks is being executed?
  • What do you think the 13 inside the Blink block is for?

Now, we didn’t exactly cheat in experiment zero, but the Blink block was a bit of a shortcut. What if you wanted to speed up the blinking? Or change how long it’s on versus how long it’s off? Or even blink something other than that wimpy little yellow LED?

Background Information

This experiment digs into the anatomy of the Blink block. We can customize an LED blink with a combination of two blocks – Set Digital Pin and Delay Milliseconds.

This experiment introduces the concept of digital output. We call the Sandbox’s LEDs “outputs,” because it’s an effect that the board produces.

The term “digital” means that the output can only take one of two states: ON or OFF. We may also refer to those two opposing states as HIGH/LOW or 1/0. When an output connected to an LED is HIGH, the LED turns on. When the output is LOW, the LED turns off.

Active Parts

alt text

Code Components

Here is the set of blocks we’ll use to create this drawing:

alt text

Aside from the Program block (which you should include in every drawing), there are two new blocks to be added:

  • Set Digital Pin: This block sets an output to either HIGH or LOW, so it can be used to turn the LED on or off. Find this block under the Pins bin. When you drag this block over, it includes a pair of pink blocks containing “13” and “HIGH.” Let’s only concern ourselves with the bottom pink block for now.
    • HIGH/LOW block: If you mouse over this block, a drop-down arrow will appear. Click the arrow and you can change the value of the block to either “HIGH” or “LOW.” This determines which of the two states you’re setting the digital output to.
  • Delay Milliseconds: The Digital Sandbox runs code so fast that sometimes we need to slow it down with a delay. This block will halt the Sandbox from doing anything for a specified number of milliseconds. There are 1000 milliseconds (ms) in a second, so delaying for 1000ms will stop for one second. Find this block under the Control bin.

Do This

Organize and snap together the Set Digital Pin and Delay Milliseconds blocks so they alternate – teal, yellow, teal, yellow. Then put the group of four blocks in the loop section of the Program block. Then Upload the code.

You should see a very familiar sight. But this time you have control over the blink rate! Adjust the value in the Delay Milliseconds block(s). What happens if you make the delays shorter? What happens if the two delays are not for the same amount of time?

The Digital Sandbox operates at 8MHz – there’s a clock in there that ticks eight million times per second. That means it can run millions of lines of code per second. Without any delays in the program, the digital output would flick on and off so fast you wouldn’t be able to tell if it’s actually on or off.

Further Explorations

  • How short can you make the delays and still notice a blink? Ten milliseconds? One millisecond?
  • What happens if you take the Delay Milliseconds block out of the program?
  • While digging around for the Delay Milliseconds block, you may have discovered a Delay Microseconds block as well. What happens if you swap that in?

Large arrays of LEDs are often used to create massive outdoor signs and animations because they’re both bright and efficient. While we don’t have the millions of LED pixels that a display in Times Square might have, we can still create some fun patterns with the Digital Sandbox.

Background Information

In this experiment we explore the subject of pins– the manipulators of the Sandbox. Each LED (as well as the other inputs and outputs on the Digital Sandbox) is connected to a specific pin on the Sandbox’s microcontroller.

Pins are all uniquely numbered, and each input or output component on the Sandbox is labeled with the pin number it’s connected to – that’s the D2, D4, D11, A1, etc. lettering next to each LED, switch and sensor.

Every pin can be separately controlled; for instance pin 4 can be set HIGH at the same time pin 5 is set LOW. Some pins (as we’ll later discover) have special powers, but every pin is at least able to accomplish digital input and output.

Active Parts

alt text

Code Components

Whoa! Block explosion! This experiment calls for sixteen total blocks:

alt text

Instead of introducing a new block, we’ll be adjusting the value of Set Digital Pin’s top pin - the pin number. This value specifies which of the Sandbox’s pins we’ll be toggling.

Do This

In our unfinished example, the blocks are all arranged in groups of three. Each group begins by setting a pin HIGH, then delays for a second and sets it back to LOW. Notice that each group of three toggles a different pin, ranging from pin 4 to pin 8. Stack the groups-of-three on top of each other in the loop, then upload and enjoy the exciting animation.

If the LED slide is too slow for you, try adjusting the delays to make it faster, or perhaps you want to change the pins to adjust the order of the blinks.

Further Explorations

  • Try adding more blocks to create slicker patterns. Can you make a Larson scanner (ask an old person about Cylons or Knight Rider)? A chaser? Flip from odds to evens?
  • Try turning on more than one LED at a time. Turn them all on (and shield your eyes)!

3: Dimming (the Hard Way)

Yikes! Those white LEDs are blindingly bright! Is there any way to dim them? (Unless one of your hobbies is staring into the sun, we recommend putting a piece of paper over the LEDs in this experiment…or wear sunglasses.)

Background Information

Remember that the Digital Sandbox is fast. It can flick an LED on and off millions of times per second. What if we blinked the LED super fast, but also make it so the length of time the LED is off is more than the length of time it’s on? This is called pulse-width modulation (PWM), a tool with a variety of applications, including dimming the LEDs.

In this experiment we’ll explore PWM the hard way, by coding it in manually.

Active Parts

alt text

Code Components

We’ll use a similar set of blocks:

alt text

Take note of how long each delay is, and which pins are on/off in each group.

Do This

Stack the two group of threes on top of each other, in the loop section, and Upload.

After uploading, take a close look at the LEDs connected to pins 5 and 6. Can you spot a difference between the two? The D6 LED should look dimmer in comparison to D5. That’s because D6 is set to be low 90% of the time, and on only 10%. It’s blinking on and off so fast that you can’t notice. But what the blinking is creating is a dimming effect.

What happens if you swap the two Delay Millisecond blocks? What if you change the values in each of the delay blocks (try to keep the sum of the delay times to around 10ms)?

Further Explorations

  • How long can you make the delays before you start noticing a blink?
  • Try comparing both LEDs to a fully-on LED. Add a Set Digital Pin block to the setup, and have it turn the D4 LED HIGH. Can you tell a difference between D4, D5, and D6?
  • What happens if you add something else to the loop section, like your animation from experiment two?

4: Dimming (the Easy Way)

Manual PWM is hard, and it doesn’t leave room for anything else in the program. Why can’t we offload that chore to the Digital Sandbox’s microcontroller? It’s smart enough for that…right?

Background Information

PWM is such a popular tool many microcontrollers implement special hardware so they can mindlessly toggle the pin while doing something else. We call this PWM-based output analog output.

Unlike digital outputs, which only have two possible values, analog outputs have a huge range of possible values. On the Sandbox we can analog-ly output 256 different values. If we set an analog output to zero, that’s like setting a pin LOW, and 255 is like setting a pin HIGH, but all of the values in between produce an output that’s neither HIGH or LOW – it’s somewhere in between.

Analog output seems great – why wouldn’t you use it all the time? Unfortunately, not all pins have special PWM powers. Only pins 3, 5, 6, 9, 10 and 11 are able to produce analog outputs.

Active Parts

alt text

Code Components

New block alert! While it may look similar, we’ll be using Set Analog Pin this time instead of its digital counterpart:

alt text

  • Set Analog Pin: This block looks a lot like the Set Digital Pin block. We still tell it which pin to control, but instead of a restrictive, digital output option, we get to choose any number between zero and 255 for the output. Find this block under the Pins bin.

Do This

Stack the blocks in the loop section. Order them so the analog values go from zero at the top to 255 at the bottom. Then upload away!

The LED on pin 5 should cycle through five different levels of brightness (including fully on and fully off). Remember that setting the analog output to zero turns the LED off, and 255 is like setting it to HIGH.

Try adding analog control of the pin 6 LED to the drawing. You can create the same effect from the last experiment, with just two lines of code (and you can execute other code while the LEDs remain in their dimmed state!).

Further Explorations

  • What’s the dimmest value you can set the LED and still see it on?
  • Why do you think there are 256 possible analog output values? That doesn’t seem like a very round number (hint: 28).

5: Color Mixing

Bleh…white. So boring. Let’s add some color to this Sandbox. By combining analog output with an RGB LED, we can mix varying levels of red, green and blue to create a rainbow of colors!

Background Information

In art class you probably learned about primary colors and how you can mix them to produce any other color. While the artsy primary colors you might be familiar with are red, yellow and blue, in electronics (and programming in general) our primary colors are red, green and blue.

By selecting different analog levels for our primary colors, we can mix them to create any other color we want. Need yellow? Mix green and red. Purple? Red and blue. In this experiment we’ll combine everything we’ve learned about analog output to add custom color to the Digital Sandbox.

Active Parts

alt text

Code Components

For the most basic RGB color-mixing sketch, this is all we need:

alt text

In the example, we added comments to each of the Set Analog Pin blocks. Comments have no effect on the actual code, but they do help make the code more readable to you or others. With those blocks commented, we don’t have to look back at the board to remember which pins go to which colors.

You can add comments by right-clicking on a block, and selecting “Add Comment”. Show or hide comments by clicking the “?”.

Do This

Stack those three Set Analog Pins on top of each other, in either the setup or the loop. This will set red’s value to 16, green to 255, and blue to 128. What color do you think it’ll make? Upload to find out! (If it’s hard to tell what the color is, put a piece of paper over the RGB LED.)

Play with the analog values to make your own colors. How about purple, or orange, or salmon? You can take it even further by adding delays, and blinking different colors to make animations.

Further Explorations

  • Mix the colors to make your favorite color. Or, if your favorite color is red, green or blue, try making your least favorite color.
  • Make a stop light blink from green, to yellow, to red and repeat.

6: Number Storage with Variables

The herky-jerky fading from experiment four accomplished the task, but just think of all the values we were missing! How do we make the LED fade smoothly? You can whip out 256 minutely different Set analog pin blocks, or you can reduce it to one, using variables.

Background Information

Variables are like storage containers for numbers. We can put any number in a variable, and either recall it and put it to use, or manipulate it to change the value it stores. Anywhere you stick a literal number (like “0” or “255”) you can instead use a variable.

There are a few rules when it comes to creating a variable. They can be any word, but they must begin with a letter, and they can’t have spaces (use “_” instead). They are case sensitive, so a variable named “fade” isn’t the same variable as “Fade.” Try to keep variables short, but use descriptive words to keep your code legible.

Active Parts

alt text

Code Components

Thanks to variables, here are all the blocks we need to create a smooth fade:

alt text

There are a few new blocks to familiarize yourself with this time:

  • Number Variable Name: These blocks are about the same size and shape as the literal number blocks we’ve been using. But, instead of writing a number in these blocks, you type in the name for your variable (make sure it’s spelled the same in every place you want to reference it). You can find this block under the Variables/Constants bin on the left.
  • Set Number Variable: This block, also found under the Variables/Constants bin, is used to set a variable to a specific value. Two blocks snap to this one – a variable name on top, and the value you want to set that variable to on the bottom. The value can be a literal number, another variable, or the result of a mathematical operator.
  • Math operator block: If you click on the Math Operators bin, and look at the first four entries, you should see some very familiar symbols: &plus;, −, ×, and &div;. These math operators can be used to do math on a pair of variables or numbers, or a combination of the two.

Do This

Add the first Set Variable Number block, which will include a blank variable and a value. Click into the number variable name and write “fade” into it. The “fade” variable will keep track of the the brightness of our LED. The Set Variable Number block in the setup area of the program should set the “fade” variable to zero.

You should be plenty familiar with Set Analog Pin and Delay Milliseconds; grab those blocks and stick them in the loop in either order.

We’ll need to throw away the value block that comes with Set Analog Pin (drag it over to the left side of the window) and replace it with a variable. To add a variable to your sketch, drag over the Number Variable Name block and type your variable’s name into it. Alternatively, once you’ve made one variable, you can right-click it and clone it to get more of the “fade” variables you’ll need.

Finally, add another Set Number Variable block, and replace the 0 value it includes with a + operator. Modify it so it adds a 1 to “fade,” and plug it into the value part of the Set Number Variable block. Then stick that block group at the end of the loop.

Whew! Let’s see what all that work was for by uploading the drawing. The LED on pin 5 should satisfyingly and smoothly flow from fully off to fully on.

Further Explorations

  • Does it matter what order you have the loop blocks in?
  • Can you make other LEDs fade? How about more than one fading at the same time?
  • Can you make the LED fade from HIGH to LOW? (Hint: You may need to change the setup value of “fade,” and change the + to a −.)

7: If This Then That

Fading from the last experiment was working just fine until we got to the maximum brightness level of 255. What happens then is a mystery known only to the compiler (and you, once you learn a little something about data types). What if we added “catch” to force that fade variable to reset when it hits a certain value?

Background Information

This experiment introduces the if statement, one of the most fundamental programming structures. Not only are if statements important for computers, they also rule most of the decisions we make in our lives: If it’s cloudy outside, then pack your umbrella. If you’re hungry, then make a sandwich. Like us, computers use if statements to make choices.

An if statement requires two components to be complete: a condition and a consequence. A condition is a value or mathematical operation that evaluates to either true or false. If the condition evaluates to true, then the consequence is executed. The consequence can be a code block of any size - one block or hundreds of blocks.

If the condition in the if statement is false, then the consequence is skipped, and the program starts running the code following the if block.

Active Parts

alt text

Code Components

Here are the blocks required to limit the fade value of our LED.

alt text

There are two new blocks to mention here:

  • If: The star of this experiment can be found under the Control bin. The If block requires at least two blocks to be snapped into it: the conditional and the consequence. In this case, the consequence is just a single block - Set Number Variable. The conditional part of the if block is a logical operator block.
  • Logical Operator: Logical operators are symbols which operate on one or two values and evaluate to either true or false, which makes them perfectly suited for the if statement conditional! In this case we’ll be using the less than (<) operator. If the value to the left of the < symbol is less than the value on the right, then the operator is true. If the left is not less than (either greater than or equal to), then the condition will evaluate to false.

Do This

In this sketch, we want the blue LED to progressively go from super bright to off, and repeat that cycle endlessly. We’ll use a variable called fade to keep track of the analog output value. At the very beginning of each loop, we’ll subtract 1 from the fade variable.

Then, after subtracting from fade, we need to use an if statement to make sure it’s not out of bounds. The if statement in this sketch states that iffade is less than 0 (that would mean it’s a negative number), then set fade to 255.

Finally, once we’ve generated our fade value, we can set pin 10 (or pick another LED if you please) to that analog output value.

Now upload and enjoy a nice, controlled fade.

Further Explorations

  • Can you make the fade work the other way? Start at 0, fade up to 255, and then go back to 0. (Hint: You’ll need to flip the logical operator around.)
  • Make it even smoother! Can you make it fade smoothly up and smoothly down in the same sketch? From 0 to 255, then 255 to 0, then 0 to 255, then back again.

8: The Reaction Tester

Computers are great at doing math and automating boring tasks, but everyone knows that their true purpose is to play games. Let’s create a game on the Digital Sandbox! In order to control the game we need to add input.

Background Information

Up to this point, our Digital Sandbox experience has been very one-sided. Output to tiny yellow LEDs. Output to larger white LEDs. Output to RGB LEDs. Change the fade value of the output. Output, output, output. Let’s flip the tables on the Sandbox, and send some input to the board!

Inputs are signals or values sent into a system. Some of the most common inputting components are buttons. Buttons on a keyboard are an input to your computer because they send data into that system.

if statements are critical when assessing the status of an input and taking an action based on it - if button A is pressed, then print an “a.” We can take the if statement a step further by adding an else condition, which allows us to control what happens if the if statement evaluates to false. So now we can say something like “if the egg floats, throw it away, otherwise (else) fry it and eat it!”

Active Parts

alt text

Code Components

Our game will use both the switch (on the bottom left of the Sandbox) and the small button - components tied to pins D2 and D12, respectively. The sketch is pretty massive, so we’ll snap it together for you. Here’s what it looks like:

alt text

  • If/Else: This block works just like the if block, but it allows you to determine what happens if the conditional evaluates false in addition to true. Again, you need a conditional block (or set of blocks) that evaluate to either true or false in the Test snap. You also need to add two separate blocks of code to fill both the then and else snaps.
  • Equivalence test (==): To test if two values are equivalent, we use the == statement. That’s right, there are two equals signs. This is to differentiate from a single equals sign, which is used to set one value to another. The double equals is like asking, “are these two values equal?”

Do This

Arrange your blocks so they match the image above. There are two important if/else statements in this program, which each test the status of an input. The top if/else tests pin 2, which is connected to the switch. If the switch is set to one (e.g. HIGH), then we set a variable called speed to 50. If the switch is set to zero (LOW), then speed becomes 150.

The second if/else tests pin 12, which is tied to the small button. When the button is pressed, then the input is set to one (HIGH), and it’s zero when released. This means that, when the button is being pressed, the code in the then will execute. When the button is not being pressed, the else blocks will run.

Can you guess what will happen in each of the pin 12 test cases? Upload the sketch to your board to find out!

This is a very simple game. Pick a number between four and eight, and try to make the LED stop on that number by pressing the button. To switch between easy and hard mode, move the switch from 0 to 1. Can you make it stop in the middle on hard mode?

Further Explorations

  • Trick your friend and swap which direction of the switch sets it to easy mode – make zero hard and one easy.
  • Swap the function of the switch and the button, so you have to press the button to set the difficulty and flick the switch to stop the LEDs.

9: Serial Calculator

While you probably can’t have a very stimulating conversation with the Digital Sandbox, it can send you some very interesting information. It’s great at math, so let’s have the Sandbox do some calculating for us! Trouble is, how do we get it to print numbers (without Morse code)? Enter serial communication!

Background Information

Serial communication is a form of data transmission where we can send a string of 1’s and 0’s between two devices and actually form a set of characters. So 01101000 01100101 01101100 01101100 01101111 00101100 00100000 01110111 01101111 01110010 01101100 01100100 becomes “Hello, world.”

With serial, we can send actual text from the Sandbox and display it on our computer using the Serial Monitor.

Active Parts

alt text

Code Components

Here is the layout for this experiment:

alt text

There are two new blocks this time, both of them shaded white and located under the communication bin:

  • Serial Print: This block takes two parameters. At the top, place the message you want to print. You can put anything you want into the message block (even spaces!). If you want to add a variable or number, you’ll need to add some glue. The bottom snap of Serial Print determines if a new line is printed after the message. Usually you’ll want this to be set to true.
  • Glue: Glue blocks allow you to print values like variables or numbers - anything that isn’t a message you’ve written in. If you want to print a variable, you’ll need to add a glue block between the variable and the Serial Print block. There are three different kinds of glue blocks, each with a different snap shape on the right. This time we’ll use the block with a wedge (<) termination.

Do This

At the very beginning of our sketch, we want to print a friendly message. How about a short description of what our calculator is going to do: “Powers of 2!” Then setup a variable that we can do some math on, starting at one.

In the loop, we only want to do math and print when the button is pressed. So, begin by adding an if block to check if pin 12 is HIGH (button is pressed). If the button is pressed, we’ll do our math and print out the result. To print a variable, we need to “glue” it to the Serial Print block with a wedge-shaped glue piece. Make your drawing match the one above.

With that, upload the sketch to your Sandbox. Then, to view the serial prints, click on the Serial Monitor button up top.

alt text

You’ll see your message printed. Now press the D2 button to start calculating.

alt text

Further Explorations

  • Something funny happens when the power of 2 gets past 16834, and then turns to -32768, and then turns to zero. This is because our variable has reached its maximum value and, in a sense, has gotten confused. Can you add an if statement to catch an out-of-bounds multiplier variable and reset it?
  • Try some of the other mathematical operators. You’re probably familiar with +, −, ×, and &div;, but what does the % operator do?

10: Do the Analog Slide

Digital inputs, like the button, only allow for two input values: HIGH or LOW. But what about the in-betweens? When you turn the volume up on your stereo, you’re not forced to pick between mute and “OMG MY EARS.” For volume control and other “finely-tuned” settings, we need analog inputs.

Background Information

Analog inputs are components that put data into a system with a range of more than two values. On the Digital Sandbox, analog inputs can produce a value anywhere between zero and 1023 (1024 total values). The value produced by an analog input is proportional to the voltage it produces. If an analog component reads a value of zero, the voltage is 0V. If the output value is 1023, then the voltage is 5V. An analog reading of 512 is about 2.5V, and so on.

A special component inside the Sandbox’s microcontroller called an analog-to-digital converter(ADC) is able to convert that range of input voltages to a discrete number. This is a special circuit that most pins on the Sandbox don’t have. It’s so special that the ADC pins are labeled with a preceding ‘A’. The analog sensors on the board are labeled as “A0”, “A1”, “A2” and “A3.”

Many electronic components produce analog output, the most common of which is a potentiometer. “Pots” come in a variety of shapes and sizes. Rotary pots are very commonly used to adjust the volume on a stereo. Slide potentiometers, like that on the bottom of the Sandbox, are often seen adjusting sound levels on mixing boards.

Active Parts

alt text

Code Components

Whew, after that last experiment it’s time for an easy drawing:

alt text

  • Analog Pin #: Like the Digital Pin block, this block reads in the value of an input. But, instead of producing either true or false (1/0, HIGH/LOW), this block produces a number between zero and 1024. The pink block snapped to the right of this one indicates which analog pin should be read.

Do This

Construct the block drawing as shown above. Then upload and open the serial monitor.

Every 100ms an analog input value should be printed. Move the analog slider to adjust the value. Can you make the output zero? 1023? 512? Take note of which slide pot position relates to which value.

Further Explorations

  • Can you make the slider control the LEDs? You could slide the white LEDs back and forth, or try controlling the brightness of the RGB LEDs with the slider.
  • Why are there only 1024 output values? Why not an even 1000? (Hint: 210.)

11: Automatic Night Light

We now have all the programming tools we need to make some totally awesome, interactive projects. Let’s incorporate the light sensor - another analog input component - to create an automatic night light that turns on when it’s dark.

Background Information

You may not see them, but light sensors are incorporated into all sorts of modern electronic devices. There are light sensors in smartphones, which measure how bright your environment is and adjust the screen brightness accordingly. There are light sensors in smoke detectors that detect particles in the air. Photogates use a light sensor to determine when an object passes a certain point - great for those photo finishes!

The light sensor on the Digital Sandbox is called a photo-transistor. It produces an analog voltage relative to the amount of light it sees. The lower the analog value, the darker the environment. If you cover the sensor completely, you might get the output all the way down to zero. Shine a flashlight on it and you might get a maximized reading of 1023.

Active Parts

alt text

Code Components

Here is the code block setup for this experiment:

alt text

There aren’t any new blocks, but we may have to adjust the value of the dark variable to make the night light work perfectly. That’s where serial communication will come in handy!

Do This

Snap your blocks together to match the diagram above, and upload.

The trick to this experiment is finding the perfect setting for the dark variable. If your room is nice and bright, the white LEDs on pins 4 and 8 should be off. When the lights are off (or the sensor is covered), the LEDs should light up.

If the lights aren’t behaving properly, that’s OK! You just need to fine-tune the dark variable. Open up the serial monitor to view the output of the light sensor. Take note of the sensor’s reading when the lights are on, then turn the lights off. What are the values now? Try setting the value of the dark variable just a bit higher than that.

Further Explorations

  • If the brightness is right on the border of on/off, the LEDs can blink unpleasantly. Try adding another if statement to catch if the light sensor is right in the middle range; from there you can dim the LEDs based on what the sensor reads.
  • Try incorporating the RGB LED into this project. If it’s super-bright, make it light up yellow. Kind of dim? Green. Totally dark? Blue.

12: Thermal Alert!

“Is it hot in here, or is it just me?” Using a temperature sensor, which is able to precisely measure the room temperature, we can answer that question once and for all!

Background Information

Temperature sensors are a critical component in many circuits, whether you’re controlling an A/C system or creating a safety mechanism for gas-powered appliances. Electronic temperature sensors come in many form-factors, from big thermocouples that can measure up to 1000 °C to that little black rectangle on the Digital Sandbox.

The temperature sensor on the Sandbox produces an analog voltage that represents the temperature around it. The voltage is actually linearly proportional to the Celsius temperature. If you know the output voltage of the sensor, you can calculate the temperature with this equation:

temperature = (voltage - 0.5) \times 100

We can have the microcontroller do all of that math for us as long as we find the right algorithm - an equation or set of instructions that accomplish a specified task.

Active Parts

alt text

Code Components

We warned you there’d be a lot of math on this one; here’s the setup (click the image to see it bigger):

alt text

There aren’t any new blocks here but, as you can see, we do get to use a wide variety of mathematical operators. Pay close attention to the order of operations. When you have a series of nested mathematical operators, the innermost operation is calculated first.

Do This

Construct the drawing as shown above. Make sure the mathematical operations are in the right order! Also important is the decimal part (e.g. “.0”, “.5”, “.01”) on most of the numbers in these equations. Those tell the microprocessor that you want it to use extra precision when calculating.

After you’ve completed the drawing, upload the sketch and check out the RGB LED. Is it red or green? If it’s red, you’re probably plenty toasty, as your room temperature is above 78 °F. If it’s green, try warming up the sensor by blowing on it. Can you get it to turn red?

To find the exact temperature reading, open up the serial monitor. After viewing the values here, you may want to alter the value of the 78 in the if/else test.

Further Explorations

  • Can you add a third check to alert when it’s too cold by turning on the blue LED? The real trick here is cooling the Sandbox off. One option is to power the board with a battery and stick it in the fridge.
  • Celsius and Fahrenheit are two of the most common temperature scales, but they’re not the only ones. Can you print the temperature in units of Kelvin or Rankine? You’ll need to find an algorithm to convert to them from Celsius.

13: Sound Detecting

<Pitchman voice> Introducing the fabulously groundbreaking SOUND (Sandbox’s Over/Under Nominal Decibels) System! Microphone check 1..2..1..2. With the SOUND you’ll always have an adjustable sound level detector handy! </Pitchman voice>

Background Information

In this experiment we’ll use the Sandbox’s on-board microphone to measure volume levels and display them on the LEDs. The microphone produces a sound wave, which is just another analog voltage that we can measure. The louder the sound, the higher the amplitude of the wave and the larger the voltage.

Without a lot of complicated math and filters, sound can be a difficult thing to measure and react to. Using the Sandbox for voice recognition isn’t quite possible, but it can be programmed pick out high volumes as long as it can sample the microphone input fast enough. We can use the slide potentiometer to set the sensitivity of the display.

Active Parts

alt text

Code Components

No new blocks to introduce this time. We’ll be taking the analog input of pin A2 to read in the microphone level, and light up LEDs based on that value.

alt text

Do This

After arranging the blocks, upload the sketch and have a look at the LEDs. Are they bouncing to your voice? If not, try tapping on the mic.

To adjust the sensitivity of the volume meter, move the slide pot up or down. With the slider set to the far right, it’ll take a really loud sound to make every LED turn on. But if you set the slider too low even the slightest noise will set the meter off.

Further Explorations

  • Can you rewrite the sketch to use the RGB LED instead of the white LEDs? Make it turn red when the volume is really loud, and blue and/or green otherwise. Bonus points for using analog outputs!

14: Opto-Theremin (Addon)

In this experiment we’ll attach a speaker to the Sandbox, and turn it into a musical instrument! By using the light sensor to control our speaker’s pitch, we can create a light-controlled theremin - a non-contact, electronic musical instrument.

Note: This experiment requires the Digital Sandbox Add-On Kit, purchased separately.

Background Information

By precisely modulating a pin, the Digital Sandbox can create electronic waves which, when routed through a loudspeaker, can produce a musical tone. We can program the Sandbox to control two characteristics of musical tone: pitch and duration.

A tone’s pitch is what we perceive when we think of a note as being very high (screams, forks scratching plates, etc.) versus very low (like earth-rumbling bass). The pitch of a tone is very closely related to the frequency played through a speaker. If we toggle a pin from HIGH-to-LOW then LOW-to-HIGH 440 times per second, for example, it produces a 440 Hz (hertz) frequency - a “middle A” pitch. Humans can hear frequencies ranging from 20 (low-pitch, bass) to 20,000 Hz (high-pitch, “ow, my ears”).

We can also program the duration of a tone - the length of time a pitch is played. In our program we’ll use the delay function to set the duration. Playing a tone with the Sandbox is very easy. Just give it a pitch and it’ll start toggling the output pin for you. Much like analog output, you can set it and forget it; the tone won’t stop playing until you tell it to.

Active Parts

alt text

Code Components

This program introduces the Tone and No Tone block. Here’s the full layout:

alt text

  • Tone: This block takes two inputs: a pin number and a frequency. The pin number can be any digital pin, but in this case we’ll use the expansion connector on pin 3. Frequency can be anything from 31 Hz to the extent of your audible range.

    A tone initiated by the Tone block will go on and on until you call a No Tone block. No Tone simply halts a pin from playing a tone. Both of these blocks can be found under the Utilities bin.
  • Map: This handy function maps a value from one range to another. In the example above, we’re taking a value (the output from A3) between zero and 60, and mapping that to a range from 440 to 880. So an analog reading of zero becomes 440, and a reading of 60 becomes 880, anything in between is relative to those two ranges. The map function can be especially useful in mapping an analog input (0-1023) to an output (0-255).

Do This

Arrange your blocks as shown in the image above, and upload to the Sandbox!

You’ll also need to connect the speaker to the expansion connector. Before you can do that, you will need to break off one group of three pins from the male breakaway headers. Now, you can connector the buzzer, with the top side facing down, to the expansion connector as shown in this image:

alt text

As fun as the opto-thermin may be, the sound is considered grating by some, so the code implements a simple ON/OFF function. Slide the switch over to the “1” position to turn the opto-theremin on.

Once the theremin is on, the speaker should start making noises. Try covering the light sensor; does the pitch change? We’ve turned the RGB LED white, so you can try to corral the light from that to control the light sensor.

You can adjust the duration of the tone by sliding the potentiometer. Slide the pot all the way to zero to get a really fast “zapper” sound, or slide to the right to create a soothing, slow sound.

Further Explorations

  • Try adding a “rest” function to your opto-theremin. Use the button to intermittently cut off the sound output.
  • Instead of using the Sandbox as a musical instrument, can you program it to play a written piece of music? Using a series of tones and delays, try reproducing the chorus of your favorite song!
  • Give yourself a hearing test! What’s the highest frequency you can hear? Can you hear tones others can’t? Can your pet hear pitches that you can’t?

15: Serial Motoring (Addon)

Motors make the world go round. Well, not literally, but they make a lot things we use every day spin and actuate. There are tiny vibration motors in cell phones, speedy motors that spin CDs and Blu-Ray discs, and of course, massive engine motors that help propel our cars. In this experiment we’ll explore one of the most fundamental motor types out there - DC motors - and we’ll tell the Sandbox precisely how fast we want the motor to spin.

Note: This experiment requires the Digital Sandbox Add-On Kit, purchased separately.

Background Information

A DC motor turns electrical energy into a rotational, mechanical energy. DC motors are popular because they’re very simple to control: Give them some voltage and they spin. You can control the speed of a motor much as you might control the intensity of an LED - with PWM - so in this experiment, we’ll be using the analog output block to control the motor’s speed.

This experiment also introduces serial input. Up to this point our conversations with the Sandbox have been very one-sided - the Sandbox has been outputting data to the serial monitor. Serial input allows us to send data to the Sandbox via the serial monitor.

Active Parts

alt text

Code Components

Here is the diagram for this program. The Set Analog Pin blocks are used to control the motor, and a speed variable is used to keep track of the motor speed. A few new blocks, related to serial communication, are introduced.

alt text

  • Serial Read: We’ll use this block to put serial data into the Sandbox. The Serial Read block is like a number variable, but instead of using a Set Number Variable block to set it, we use the Serial Monitor. This block will store the integer most recently sent to the Sandbox from the Serial Monitor.
  • Data Available: This block keeps track of whether or not any serial data is available. If no serial data has been sent to the Sandbox, this block stores a zero. If data is sent to the Sandbox this block will return a one. The value of this block will go back to zero once the serial data has been read (using the Serial Read block).

Do This

Construct the program as shown in the picture, then upload the code.

After uploading, connect the motor’s black wire (GND) to the GND pin on the Sandbox’s add-on header. Then, connect the motor’s red wire to the OUT pin on the Sandbox’s add-on header. Your motor should now be connected to the Sandbox as shown in this picture:

alt text

Now open the Serial Monitor, type a number between zero and 255 into the box next to “Send,” and then click that button. The Sandbox should respond with a message, and the motor should start spinning.

alt text

What happens when you send 255? How about zero? What happens when you send a number greater than 255 or less than zero (a negative)? Can you spot a block in the code that is restricting those values?

As a “safety mechanism,” if you ever need to stop the motor from spinning, press the button to bring it to a halt.

Further Explorations

  • Try connecting something mechanical to the motor. Perhaps tape a narrow piece of paper to create a spinner and play Twister. Or add a few pieces of paper to create a fan. What else can you connect to the axle to take advantage of the rotational motion?
  • As a programming challenge, can you make the motor smoothly speed up or down when a new serial value is received?

16: Servo Sweeper (Addon)

DC motors are great for spinning an object at high speed with no regard for where it starts or stops. For many applications, though, it’s important to precisely control the position of a motor. Wing flaps in a plane, steering mechanisms in RC cars, and robotic arm platforms are applications that benefit from motorized position control. For those applications we ditch the DC motor and whip out the servo!

Note: This experiment requires the Digital Sandbox Add-On Kit, purchased separately.

Background Information

A servo motor is like a DC motor with an internal controller and built-in sensors that help keep track of its shaft position. A servo motor knows, for example, if it’s pointing at 15° or 115°.

Servos all have three wires that need connecting to: supply voltage, ground, and a signal. The voltage and ground connections supply the motor with power, and the control signal - a PWM output (surprise, surprise) - sets the position of the motor. Once the motor reaches the desired position, it stops until it is commanded to move to a new position.

Servo motors vary in their range of motion - the minimum and maximum angles they can point to. Only specialized, continuous rotation servos can rotate a full 360°; most have a stated range of motion between 90° and 180°. The servo we’ll be using in this experiment has a 180° range of motion.

Active Parts

alt text

Code Components

This experiment introduces the Servo block. Here is the layout:

alt text

  • Servo: This block, found under the Utilities bin, allows you to move a servo to a set position. There are two inputs to supply to the Servo block: pin number and angle. Servos can be connected to any pin, we’ll use the multi-purpose pin 3 in this example. The angle should be a number between zero and the maximum range of your servo. In this case we’ll constrain the range between zero and 180 using the Map block.

Do This

Construct the program as shown, and upload it to the Sandbox.

After the code has been uploaded, connect the servo with the three pin male breakaway header to the Sandbox. Make sure the servo’s black wire (GND) is lined up to the GND pin on the Sandbox, as shown here:

alt text

This program allows you to control the position of the servo motor with the sliding potentiometer. Slide all the way to the right to set the servo to 180°, and all the way to the left sets it to 0°.

The servo will only move if the switch (connected to pin 2) is set to ON. If you leave the switch in the ON position, you can see how fast the motor responds to the servo block. If you move the switch to OFF, set the position of the slide pot, and set the switch to ON, you can see the speed and control mechanisms of the motor.

Further Explorations

  • What happens if you try to rotate the servo beyond 180° (change the last value in the map function)?
  • Think of something to attach to the servo! You could add a clock hand to make a weird, half-circle clock. Or add a papercraft hand, and have your Sandbox give you a high-five!

Resources & Going Further

Congratulations on completing the Digital Sandbox Experiment Guide! If you feel comfortable enough with ArduBlock, and want to continue challenging yourself, check out our parallel Digital Sandbox Guide for Arduino!

alt text

Re-live the memories of experiment 12! This time with Arduino code.

In that tutorial we re-create the same experiments from this guide using the actual Arduino programming language. Say goodbye to blocks and hello to semi-colons!

Resources

If you’re looking for more resources devoted to the Digital Sandbox, Arduino, or ArduBlock, check out these links:

Going Further

Now that you’ve introduced yourself to the world of electronics, hardware, programming, and Arduino, check out some of these tutorials and products to continue your learning.

  • What is An Arduino?– If you’re ready to step into a more open-ended development platform, we encourage you to continue working with Arduinos. This tutorial will help get you started.
  • SparkFun Inventor’s Kit– If you’re looking for more hardware to continue your learning journey, the SIK is the next logical step.

SIK product shot

This kit includes an Arduino, breadboard, and tons of wires, buttons, LEDs, and more components. It also includes a guide with a series of experiments that introduce you to the Arduino programming language (no more blocks!) and electronics.


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

Digital Sandbox Arduino Companion

$
0
0

Digital Sandbox Arduino Companion a learn.sparkfun.com tutorial

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

Introduction

The Digital Sandbox is a learning platform that engages both the software and hardware worlds. It’s powered by a microcontroller that can interact with real-world inputs – like light or temperature sensors – while at the same time controlling LEDs, motors, and other outputs. The Digital Sandbox is equipped with everything, on board, that you will need to complete 13 experiments including controlling an LED, measuring how loud things are, detecting the temperature is, and more. Think of this as a SparkFun Inventor’s Kit all in one board!

DS graphic

In our original Digital Sandbox Experiment Guide, we show you how to program the Sandbox using a simple, graphical programming language called ArduBlock. This time around, we’ll show you how to ditch the graphical editor in favor of actual Arduino code.

If you’re looking to get into Arduino coding, this is a great place to begin. Grab a Sandbox and get started!

Experiment List (Table of Contents):

We’ll explore the Sandbox through a series of progressive experiments. If you’ve already completed the Sandbox Experiment Guide, this list will look familiar. We’ve recreated the code from those experiments using Arduino code instead of ArduBlock.

After setting up your Sandbox, here’s what’s covered:

  1. Setup and Loop
  2. Exploring Blink
  3. Multi-Blink
  4. Dimming (the Hard Way)
  5. Dimming (the Easy Way)
  6. Color Mixing
  7. Number Storage with Variables
  8. If This Then That
  9. The Reaction Tester
  10. Serial Calculator
  11. Do the Analog Slide
  12. Automatic Night Light
  13. Thermal Alert!
  14. Sound Detecting
  15. Opto-Theremin (Addon)
  16. Serial Motoring (Addon)
  17. Servo Sweeper (Addon)

What is the Digital Sandbox?

The Digital Sandbox is a learning platform that engages both the software and hardware worlds. It’s powered by a microcontroller that can interact with real-world inputs – like light or temperature sensors – while at the same time controlling LEDs, motors, and other outputs.

By interfacing the Sandbox to your PC or Mac via a USB cable, the Sandbox can be programmed using the popular Arduino programming environment.

The Anatomy of the Digital Sandbox

The Digital Sandbox includes a variety of on-board inputs and outputs that are commonly encountered in the world of electronics. Here is an overview of what’s included on the board:

Annotated image of the Digital Sandbox

  1. USB Mini-B Connector– Used to connect to a computer.
  2. JST Right-Angle Connector– Used to supply power to the board.
  3. Slide Switch for Charging– Used to charge a lithium polymer battery that is plugged into the two-pin JST connector, while the Digital Sandbox is connected to a computer and the slide switch is in the “ON” position.
  4. Reset Button– This is a way to manually reset your Digital Sandbox, which will restart your code from the beginning.
  5. Slide Switch (Pin 2)– On or off slide switch.
  6. LEDs (Pins 4-8)– Use one or all of the LEDs (light-emitting diodes) to light up your project!
  7. LED (Pin 13)– Incorporate this into your sketch to show whether your program is running properly.
  8. Temperature Sensor (Pin A0)– Measures ambient temperature.
  9. Light Sensor (Pin A1)– Measures the amount of light hitting the sensor.
  10. RGB LED (Pins 9-11)– RGB (red/green/blue) LEDs have three different color-emitting diodes that can be combined to create many colors.
  11. Slide Potentiometer (Pin A3)– Change the values by sliding it back and forth.
  12. Microphone (Pin A2)– Measures how loud something is.
  13. Push Button (Pin 12)– A button is a digital input. It can be either “on” or “off.”
  14. Add-on Header (Pin 3)– Three-pin header for add-ons. Example add-ons are servos, motors and buzzers.

Digital Sandbox Baseplate Setup

Secure the Digital Sandbox board to the baseplate with the included Phillips-head screws.

baseplate assembly

Finger-tighten the screws for easy removal later.

Setup

If this is your first time using the Sandbox, we highly recommend checking out the parallel Digital Sandbox Guide for ArduBlock. That tutorial serves as a great introduction to programming – it eases you into the programming world with a more simple, graphical language: ArduBlock. With ArduBlock you don’t have to worry about misplacing semi-colons or making spelling mistakes, just drag and drop blocks to create your program.

If you’re ready for the big show, though, follow along from here. On this page we’ll get you set up with Arduino (or Codebender), from there it’s on to the experiments.

Sandbox Setup & Driver Installation

If you haven’t already, you’ll need to install the driver for your Digital Sandbox. Begin by connecting the Digital Sandbox to your computer.

Sandbox connected to computer

Once the board is connected, you will need to install drivers. Please go to www.sparkfun.com/ftdi for instructions specific to your operating system.

Choose Your Arduino Adventure

There are two options when it comes to programming your Sandbox via Arduino: the Arduino IDE and Codebender. Together, they give you a choice between a local code editor or a web-browser-based “cloud” editor. You’re free to choose either one, here’s how to set them up:

Codebender Setup

Browsing with Firefox or Chrome? We highly suggest giving Codebender a try. All of the example code in this tutorial is displayed using Codebender. Using their plugins for Firefox or Chrome, you can directly upload the code to your Sandbox without ever installing the Arduino software!

If you want to give Codebender a try, visit their webpage, create an account, and follow the Getting Started guide.

alt text

If you follow along with the Getting Started guide, set your board type as Arduino Pro or Pro Mini 3.3V/8MHz– it uses the same definitions as the Digital Sandbox.

Arduino Setup

You certainly don’t have to use Codebender, though. If you’d rather use the standard Arduino IDE, please read through our Installing Arduino tutorial, which will guide you through every step required to get your Arduino IDE all set up.

After you’ve installed Arduino, when you get to the board selection step, set your Board type to Arduino Pro or Pro Mini 3.3V/8MHz.

alt text

And don’t forget to set your Serial Port as well, under the “Tools > Serial Port” menu.

In addition, you may want to download all of the example sketches ahead of time. Click here to download a ZIP folder with every experiment sketch in this tutorial. Unzip it and store it somewhere memorable.

0. Setup and Loop

We’ll start off as basic as possible. This experiment introduces the Arduino bare bones – the least amount of code required to create any Arduino sketch. Every Arduino sketch is different, but they all include these few lines of code. Time to setup and loop!

Active Parts

Experiment 0 active parts

Code Components

In each experiment we’ll introduce one or two new Arduino-language concepts, and provide a brief overview of how and why we use them. This time, we’re introducing setup(), loop(), comments, and some syntax.

Setup: void setup() { }

This is a declaration for a function called “setup”. This exact line is required in every Arduino sketch ever.

Any code that lives inside setup()’s curly brackets ({ and }) runs once at the very beginning of your program and then never again – at least not until you reset the Arduino, or upload new code.

The setup() function is useful for … setting up your Arduino for the rest of the program. You’ll discover it’s power in future experiments. Learn more about setup() in Arduino’s reference guide.

Loop: void loop() { }

Like the setup line before it, this is another required Arduino-sketch function. While the setup() function sets your Arduino up, the loop() function…loops!

This is where the bulk of your Arduino sketch is executed. The program starts directly after the opening curly bracket (}), runs until it sees the closing curly bracket (}), and jumps back up to the first line in loop() and starts all over.

The loop() function will run over-and-over-and-over until the Arduino is reset.

You can learn more about loop in Arduino’s reference guide.

Comments

You’ll get used to these – and tired of reading them – by the time you’re done experimenting. Comments are lines or blocks of text in your code that are there solely for you or anyone reading your code. Comments have no effect on the operation of your Arduino sketch, but they can be immensely helpful in deciphering what you or someone else was thinking when that line of code was written.

Comments come in two flavors: single-line and multi-line. A single-line comment is any line in your code preceded by two forward slashes (//). For example:

language:c
// This is a single-line comment.
code_goes_here();

A multi-line comment can be used to comment out one or more lines. Multi-line comments are initialized with a slash-asterisk (/*) and they’re completed with an asterisk-slash (*/). For example:

language:c
/* This
        is
            a
                multi-line
                    comment */
code_goes_here();

Comments have no effect on your code’s operation – they’re completely ignored by the Arduino itself – but they are very useful to you and anyone else reading your code. Always comment your cod!

Syntax: Semicolons (;), Parenthesis (()), Curly Brackets ({}), Oh My.

The syntax of a programming language is analogous to the grammar rules that define our sentence structure. Just as every sentence you write requires a punctuation mark (., ?, !), (almost) every line of code your write in Arduino must end with a semicolon (;). We’ll see those soon, don’t worry!

More apparent in this example is the parenthesis and curly brackets. Whenever you open a parenthesis or bracket (( or {) you have to close it as well () and }).

You’ll discover where parenthesis and brackets are required in your code as you gain more experience. Brackets can be used to contain the entirety of loops, functions, and conditional statements. Parenthesis can be used to define a conditional test, function parameter, or mathematical order of operations. That’s probably all gobeldy-gook right now, but take comfort in knowing that you’ll understand what all of that means by the time you’ve explored all of these experiments.

One last thing you’ll have to get used to is case-sensitivity. Everything in Arduino is case sensitive: function, variable, library names, you name it. If the first letter is capitalized in the example code, make sure you capitalize it in your code! If you accidentally capitalize something the program editor will let you know with an error.

alt text

Example of Codebender’s error output.

Fortunately, those errors are usually pretty easy to trace, just look at the line it’s pointing you to.

The Sketch and Experiment

Here’s the sketch for this experiment. It’s about as simple as it gets, and introduces some of the most fundamental components of any Arduino sketch.

If you have the Codebender addon installed, you can simply select your Arduino’s COM port and click “Run on Arduino.” The board type, “Arduino Pro or Pro Mini (3.3V/8MHz)” should already be selected, but if not, make that change as well.

If you’re using the Arduino IDE on your computer, click the “Download” button in the Codebender window. Then unzip the downloaded ZIP file, and open “Sandbox_0_Setup_Loop_Blink.ino” in Arduino.

alt text

Then, select your Serial Port and Board, and click Upload (the right-facing arrow up top).

It turns out, this code doesn’t do very much. After uploading it to your Sandbox, you won’t actually see anything happen. That’s OK, there’s still a lot to learn!

Well, that last experiment was certainly boring. Let’s make the Sandbox actually do something. When faced with a new platform, a coder’s first task is to write a “Hello, world” program. Usually a “Hello, world” program actually prints those comforting words on a screen. The Digital Sandbox doesn’t give us a screen to print words on, but we do have LEDs! Wonderful, blinky, bright, shiny LEDs. Instead of printing words, let’s blink an LED to say “Hello, world.”

Background Information

This experiment digs into the anatomy of the blinking an LED. We can customize an LED blink with a combination of two Arduino functions – digitalWrite([pin], [HIGH/LOW]) and delay([milliseconds]).

This experiment introduces the concept of digital output. We call the Sandbox’s LEDs “outputs,” because it’s an effect that the board produces.

The term “digital” means that the output can only take one of two states: ON or OFF. We may also refer to those two opposing states as HIGH/LOW or 1/0. When an output connected to an LED is HIGH, the LED turns on. When the output is LOW, the LED turns off.

Active Parts

alt text

Code Components

This time we introduce two functions required to turn an LED on and off.

Digital Output: digitalWrite([pin], [HIGH/LOW])

The digitalWrite() function is used to set the digital state of a pin to either HIGH or LOW.

We’ll learn more about the first parameter – pin– in the next experiment. For now, we’re simplying toying around with the second parameter – the digital value of the pin.

When a pin goes HIGH, it outputs a voltage of about 5V. That’s enough energy to push current through an LED and illuminate it. When a pin goes LOW, it outputs 0V. In this configuration, that doesn’t allow any power to run through the LED, so it turns off.

Millisecond Delay: delay([ms])

The Digital Sandbox runs code so fast that sometimes we need to slow it down with a delay. This function will halt the Sandbox from doing anything for a specified number of milliseconds. There are 1000 milliseconds (ms) in a second, so delaying for 1000ms will stop for one second.

Sketch and Experiment

Here’s the sketch. Check out the comments in the sketch to gain a more thorough understanding of what’s happening.

Upload the sketch to your Sandbox, and take note of the small, yellow-ish LED labeled “D13”. Is it blinking? How fast is it blinking?

Your Turn!

  • Try modifying the value in the delay() funciton. Make it lower than 1000. How short can you make the delays and still notice a blink? Ten milliseconds? One millisecond?
  • What happens if you take the delay() functions out of the sketch? You can quickly remove a function by commenting it out. Try this for your loop():
        void loop()
        {
          digitalWrite(13, HIGH);
          //delay(1000);
          digitalWrite(13, LOW);
          //delay(1000);
        }
    Comments are a great tool for deleting a line of code without actually deleting it.

Background Information

In this experiment we explore the subject of pins– the manipulators of the Sandbox. Each LED (as well as the other inputs and outputs on the Digital Sandbox) is connected to a specific pin on the Sandbox’s microcontroller.

Pins are all uniquely numbered, and each input or output component on the Sandbox is labeled with the pin number it’s connected to – that’s the D2, D4, D11, A1, etc. lettering next to each LED, switch and sensor.

Every pin can be separately controlled; for instance pin 4 can be set HIGH at the same time pin 5 is set LOW. Some pins (as we’ll later discover) have special powers, but every pin is at least able to accomplish digital input and output.

Active Parts

alt text

Code Components

Just one new function to introduce here. We kind of cheated last time by not using it, so we’ll use it five times in this experiment.

Pin Mode: pinMode([pin], [INPUT/OUTPUT])

Every pin on an Arduino can be used as either an input or output, and one of your jobs is telling it which pin is which. To tell an Arduino what a pin’s job is, you use the pinMode() function.

pinMode() takes two parameters inside its parenthesis. The first value is the pin that you want to set as an input or output. The second parameter is the mode, which can be either INPUT or OUTPUT. That’s case-sensitive, those mode values need to be all caps!

Usually you’ll stick your pinMode() declarations at the top of your sketch, in the setup() function. It only needs to run once, at the very start of your program, the pin will be set up that way for the rest of the sketch’s run.

Sketch and Experiment

Here’s our sketch, upload away!

Notice how each of our pinMode() declarations occur in the setup() function. Then the loop() is used to write each of those LEDs either HIGH or LOW.

Your Turn!

  • Try adding more blocks of code to create slicker patterns. Can you make a Larson scanner (ask an old person about Cylons or Knight Rider)? A chaser? Flip from odds to evens?
  • Try turning on more than one LED at a time. Turn them all on (and shield your eyes)!

3. Dimming (the Hard Way)

Yikes! Those white LEDs are blindingly bright! Is there any way to dim them? (Unless one of your hobbies is staring into the sun, we recommend putting a piece of paper over the LEDs in this experiment…or wear sunglasses.)

Background Information

Remember that the Digital Sandbox is fast. It can flick an LED on and off millions of times per second. What if we blinked the LED super fast, but also make it so the length of time the LED is off is more than the length of time it’s on? This is called pulse-width modulation(PWM), a tool with a variety of applications, including dimming the LEDs.

In this experiment we’ll explore PWM the hard way, by coding it in manually.

Active Parts

alt text

The Sketch and Experiment

Here’s our sketch! Upload away. Check out the comments for a line-by-line overview of what’s going on.

After uploading the sketch, keep an eye on the D5 and D6 LEDs. Do you notice a difference in their intensity? Which one is brighter?

Our sketch runs through the loop really fast– it takes about 10ms to get through the whole thing, so it’s running about 100 times per second. Nine times out of ten, the LED on pin 5 is off and the D6 LED is on. Because it’s looping so fast you can’t see any blinking, but you can sense a dimness in the D5 LED.

Your Turn!

  • How long can you make the delays before you start noticing a blink?
  • Try comparing both LEDs to a fully-on LED. Add pinMode(4, OUTPUT) and digitalWrite(4, HIGH) to the setup(), so the D4 LED turns on. Can you tell a difference between D4, D5, and D6?
  • What happens if you add something else to the loop section, like your animation from experiment two?

4. Dimming (the Easy Way)

Manual PWM is hard, and it doesn’t leave room for anything else in the program. Why can’t we offload that chore to the Digital Sandbox’s microcontroller? It’s smart enough for that…right?

Background Information

PWM is such a popular tool many microcontrollers implement special hardware so they can mindlessly toggle the pin while doing something else. We call this PWM-based output analog output.

Unlike digital outputs, which only have two possible values, analog outputs have a huge range of possible values. On the Sandbox we can analog-ly output 256 different values. If we set an analog output to zero, that’s like setting a pin LOW, and 255 is like setting a pin HIGH, but all of the values in between produce an output that’s neither HIGH or LOW – it’s somewhere in between.

Analog output seems great – why wouldn’t you use it all the time? Unfortunately, not all pins have special PWM powers. Only pins 3, 5, 6, 9, 10 and 11 are able to produce analog outputs.

Active Parts

alt text

Code Components

It’s time to introduce digitalWrite()’s analog analogue: analogWrite().

Analog Output: analogWrite([pin], [0-255])

The analogWrite() function looks a lot like digitalWrite(). We still tell it which pin to control, but instead of a restrictive, digital output option, we get to choose any number between zero and 255 for the output.

There are two parameters to analogWrite(). The first is our pin, and the second is any value between 0 and 255. A 0 will output 0V, 255 will output 5V, 128 will do about 2.5V, and so on.

Unfortunately, not every pin is capable of analog output. You can only use analogWrite() on pins 3, 5, 6, 9, 10, and 11.

Sketch and Experiment

Here’s our sketch, check out the code comments for help deciphering it. Upload away!

After uploading, keep an eye on the D5 LED. Can you identify 5 different levels of brightness (including off)? Don’t stare at the LEDs for too long.

Your Turn!

  • What’s the dimmest value you can set the LED and still see it on?
  • Can you add more brightness levels to the sketch to make it ramp up more smoothly? Get your copy/paste engines roaring!
  • Why do you think there are 256 possible analog output values? That doesn’t seem like a very round number (hint: 28).

5. Color Mixing

Bleh…white. So boring. Let’s add some color to this Sandbox. By combining analog output with an RGB LED, we can mix varying levels of red, green and blue to create a rainbow of colors!

Background Information

In art class you probably learned about primary colors and how you can mix them to produce any other color. While the artsy primary colors you might be familiar with are red, yellow and blue, in electronics (and programming in general) our primary colors are red, green and blue.

By selecting different analog levels for our primary colors, we can mix them to create any other color we want. Need yellow? Mix green and red. Purple? Red and blue. In this experiment we’ll combine everything we’ve learned about analog output to add custom color to the Digital Sandbox.

Active Parts

alt text

Sketch and Experiment

Here’s our sketch, nothing new to introduce this time. Check out the values in the three analogWrite() functions. What color do you expect will be made? Upload and finde out.

If it’s hard to tell what the color is, put a piece of paper over the RGB LED.

Your Turn!

  • Play with the analog values to make your own colors. How about purple, or orange, or salmon? You can take it even further by adding delays, and blinking different colors to make animations. If you need help designing an RGB color code, try picking one out from this color picker website.
  • Make a stop light blink from green, to yellow, to red and repeat. You’ll need some delay()’s and a handful of analogWrite() trio’s.

6. Number Storage with Variables

The herky-jerky fading from experiment four accomplished the task, but just think of all the values we were missing! How do we make the LED fade smoothly? You can whip out 256 minutely different analogWrite() blocks, or you can reduce it to one, using variables.

Background Information

Variables are like storage containers for numbers. We can put any number in a variable, and either recall it and put it to use, or manipulate it to change the value it stores. Anywhere you stick a literal number (like “0” or “255”) you can instead use a variable.

There are a few rules when it comes to creating a variable. They can be any word, but they must begin with a letter, and they can’t have spaces (use “_” instead). They are case sensitive, so a variable named “fade” isn’t the same variable as “Fade.” Try to keep variables short, but use descriptive words to keep your code legible.

Active Parts

alt text

Code Components

We’ve been slacking off on introducing new functions and syntax, so it’s time to throw some new stuff at you! As you’ll discover, there’s a lot that goes into creating and using a variable.

Declaring Variables

In order to use a variable, you first have to declare it. There are two parts to a variable declaration: a name and a type.

There are a few hard-coded rules to variable naming: a name can’t start with a number and it can’t contain spaces or special characters. Variables can only be composed of 0-9, a-z, A-Z, and _. When you’re picking out a name for a variable try to make it descriptive, that’ll help to make your code easier to read and write.

A variable type determines the minimum and maximum values a variable can be. There’s no such thing as infinity in an Arduino – there are limits to how big a number can be. In this example we’ll be using one of the more fundamental variable types out there: int. An int variable can be anywhere from -32768 to 32767 – plenty of room for us to play with. (Those seemingly random numbers come from the fact that an int is a 16-bit signed value, which means the range is from 215 to 215-1.)

Once you’ve picked out your variable type and name, you can declare it like this:

language:c
int example_variable;  // Declare a variable of type int, named example_variable

That’s it! Now you can store numbers in the example_variable variable, and even manipulate it with some math.

Variable Scope

You can declare a variable anywhere in your code, but exactly where you declare it is actually really important, because every variable has scope. A variable’s scope determines where it can be used and recalled. As a general rule of thumb, a variable can only be used within the curly bracket’s ({ and }) that is was declared in – that’s its scope.

You can create a global variable by declaring your variable abovesetup(). Global variables can be used in both the setup() and loop() functions.

But, on the other hand, if you create a variable inside setup() that variable’s scope is limited to the setup() function. So we can’t create a variable in setup() and use it inside loop()– it’s out of scope!

Using Variables

To assign a value to a variable, you use the assignment operator=. The assignment operator takes the value on the right-side of the equals-sign, and stores it into the value on the left side.

So, for example, if we want to assign the value 5 to our example_variable variable, this line of code will do:

language:c
example_variable = 5;

But you can do so much more with variables than static value assignments. Variables are awesome because we can do math on them. You can add, subtract, multiply, or divide a variable with any one of these symbols:

Math OperationCode symbol
Add+
Subtract-
Multiply*
Divide/
Remainder%

You can use the Sandbox as a calculator, make it do some hard math with lines like this:

language:c
example_variable = (1024 / 8) * 52 - 163;

Parenthesis can be used, as they are in the above example, to define an order of operations. The stuff inside the parenthesis happens first, then multiplications and divisions, then additions and subtractions.

You’re not limited to literal values on the right-hand side either! You can perform math on variables and store them into other variables. You can even perform math on a variable and store it in the same variable. For example, if I wanted to increase the value of example_variable by 1, this line of code would do:

language:c
example_variable = example_variable + 1;

In that case, if example_variable was 0, after running that line of code it would become 1.

Sketch and Experiment

Whew! That’s a lot to read about variables. As you begin to use them, though, all of that information will start to become ingrained in your brain. Here’s our sketch:

Upload away and keep an eye on the D5 LED. Much smoother!

Your Turn!

  • Can you make the LED fade from HIGH to LOW? (Hint: You may need to change the setup value of fade, and change the + to a -.)
  • Can you make other LEDs fade? How about more than one fading at the same time? Can you do the math to make the D6 LED fade in the direction opposite of our D5 LED? (Hint: try adding an analogWrite(6, 255-fade) function call somewhere.)

7. If This Then That

Fading from the last experiment was working just fine until we got to the maximum brightness level of 255. What happens then is a mystery known only to the compiler (and you, once you learn a little something more about data types). What if we added “catch” to force that fade variable to reset when it hits a certain value?

Background Information

This experiment introduces the if statement, one of the most fundamental programming structures around. Not only are if statements important for computers, they also rule most of the decisions we make in our lives: If it’s cloudy outside, then pack your umbrella. If you’re hungry, then make a sandwich. Like us, computers use if statements to make choices.

An if statement requires two components to be complete: a condition and a consequence. A condition is a value or mathematical operation that evaluates to either true or false. If the condition evaluates to true, then the consequence is executed. The consequence can be a code block of any size - one block or hundreds of blocks.

If the condition in the if statement is false, then the consequence is skipped, and the program starts running the code following the if block.

Active Parts

alt text

Code Components

Time to introduce the if statement. Time to whip out some parenthesis and curly brackets.

If Statement: if ( [condition] ) { [consequence] };

An if statement requires two components: a condition and a consequence. The anatomy of an if always looks a little something like this:

language:c
if ( [condition] )
{
    [consequence]
}

Those parenthesis and curly-brackets are required (ignore the square brackets)!

The [condition] part of an if statement can be any statement that can evaluate to either true or false. To build those conditional statements, we usually use comparison operators. There are all sorts of comparison operators, including:

Comparison OperatorCode Symbol
Less than<
Greater than>
Less than or equal to<=
Greater than or equal to>=
Equal to==
Not equal to!=

You can use variables and/or literal numbers in conjunction with comparison operators. For example, if we want to test if example_varible is greater than or equal to 255, this statement will do:

language:c
if ( example_variable >= 255)
{
    // example_variable is greater than or equal to 255
    // do some stuff!
}

If the conditional statement turns out to be true, then the Sandbox executes each line in the if statement sequentially. If the statement is false, though, then the Sandbox jumps over the if statement’s curly brackets and runs the first line of code after the }.

You’re free to put any line of code inside the if statement’s [consequence] section. You can even modify the variable that you tested in the condition. Building off the last example, if we wanted to set example_variable to 0 when it rises above 254, we can do something like this:

language:c
if (example_variable >= 255)
{
    example_variable = 0;   // Reset example_variable to 0
}

Something like that might look familiar in our sketch for this experiment.

Sketch and Experiment

Here’s our sketch for this experiment. Just one if statement for now. Read through the comments to get an idea for what’s going to happen.

Run the code on your Sandbox and keep an eye on the blue LED. It should progressively go from super bright to off, and repeat that cycle endlessly.

We use a variable called fade to keep track of the analog output value. At the very beginning of each loop, we’ll subtract 1 from the fade variable. Then, after subtracting from fade, we need to use an if statement to make sure it’s not out of bounds. The if statement in this sketch states that iffade is less than 0 (that would mean it’s a negative number), then set fade to 255.

Your Turn!

  • Can you make the fade work the other way? Start at 0, fade up to 255, and then go back to 0. (Hint: You’ll need to flip the logical operator around.)
  • Make it even smoother! Can you make it fade smoothly up and smoothly down in the same sketch? From 0 to 255, then 255 to 0, then 0 to 255, then back again.

8. The Reaction Tester

Computers are great at doing math and automating boring tasks, but everyone knows that their true purpose is to play games. Let’s create a game on the Digital Sandbox! But in order to control the game we need to add input.

Background Information

Up to this point, our Digital Sandbox experience has been very one-sided. Output to tiny yellow LEDs. Output to larger white LEDs. Output to RGB LEDs. Change the fade value of the output. Output, output, output. Let’s flip the tables on the Sandbox, and send some input to the board!

Inputs are signals or values sent into a system. Some of the most common inputting components are buttons or switches. Buttons on a keyboard are an input to your computer because they send data into that system.

if statements are critical when assessing the status of an input and taking an action based on it - if button A is pressed, then print an “a.” We can take the if statement a step further by adding an else condition, which allows us to control what happens if the if statement evaluates to false. So now we can say something like “if the egg floats, throw it away, otherwise (else) fry it and eat it!”

Active Parts

alt text

Code Components

This time we introduce a new function, plus a riff on the if statement.

Digital Input: digitalRead([pin])

The digitalRead([pin]) function is used to read the voltage of a pin. It can tell you if a pin is HIGH (~5V) or LOW (~0V).

There’s just one parameter to the digitalRead() function – a pin that you want to read. Make sure to set the pin as an INPUT, using the pinMode() function, before you read it!

This function is different from the others because it returns a value. Instead of just writing out the function call and skipping to the next line, we actually have to use the digitalRead() function in conjunction with other bits of code.

The digitalRead() function will come back with one of two values: HIGH or LOW. You can use that return value as part of a conditional test in an if statement, for example:

language:c
if (digitalRead(2) == HIGH)
{
    // Do something, because the button is pressed
}

Or, if you so pleased, you could store the value of the digitalRead() function inside a variable, like this:

language:c
example_variable = digitalRead(2);

If/Else: if( [condition] ){ [true consequence] } else { [false consequence] }

We’ll use an extension of the if statement this time: the if…else statement. if/else allows us to take one action if the condition is true and a different action if it’s false.

Here’s the anatomy of an if/else:

language:c
if ( [consequence] )
{
    // Do something because the consequence is true
}
else
{
    // Do something because the consequence is false
}

if/else is really handy when you’re dealing with digital outputs which can only be in one of two states. If a button is pressed, do something, otherwise do something else.

Equivalence Test

In this experiment we’ll be using the equivalence test (==) in our if statement conditional. That’s right, there are a pair of = signs. That’s to differentiate the equivalence test from the assignment operator (=). While the single equal-sign assignment sets one value to another, the equivalence test is asking if two values are equal and producing either a true or false response.

If you’re ever creating a conditional statement, make sure you use the equivalence operator if you’re asking if two values are equal.

Sketch and Experiment

Here’s the sketch. It’s a big one! Check out the comments for a line-by-line explanation.

There are two important if/else statements in this program, which each test the status of an input. The top if/else tests pin 2, which is connected to the switch. If the switch is set to one (e.g. HIGH), then we set a variable called speed to 50. If the switch is set to zero (LOW), then speed becomes 150.

The second if/else tests pin 12, which is tied to the small button. When the button is pressed, then the input is set to one (HIGH), and it’s zero when released. This means that, when the button is being pressed, the code in the then will execute. When the button is not being pressed, the else code will run.

Can you guess what will happen in each of the pin 12 test cases? Upload the sketch to your board to find out!

This is a very simple game. Pick a number between four and eight, and try to make the LED stop on that number by pressing the button. To switch between easy and hard mode, move the switch from 0 to 1. Can you make it stop in the middle on hard mode?

Your Turn!

  • Trick your friend and swap which direction of the switch sets it to easy mode – make zero hard and one easy.
  • Swap the function of the switch and the button, so you have to press the button to set the difficulty and flick the switch to stop the LEDs.

9. Serial Calculator

While you probably can’t have a very stimulating conversation with the Digital Sandbox, it can send you some very interesting information. It’s great at math, so let’s have the Sandbox do some calculating for us! Trouble is, how do we get it to print numbers (without Morse code)? Enter serial communication!

Background Information

Serial communication is a form of data transmission where we can send a string of 1’s and 0’s between two devices and actually form a set of characters. So 01101000 01100101 01101100 01101100 01101111 00101100 00100000 01110111 01101111 01110010 01101100 01100100 becomes “Hello, world.”

With serial, we can send actual text from the Sandbox and display it on our computer using the Serial Monitor.

Active Parts

alt text

Code Components

This sketch introduces a pair of functions related to Serial communication. Plus, a new data type!

Serial Communication

In order to use serial communication, you first have to initialize it by calling Serial.begin([speed]). The begin function requires one parameter – the baud rate– which controls how fast data is transmitted. The baud rate is usually selected among a set of common speeds: 4800, 9600, 19200, 38400, 57600, or 115200. For example, to initialize Serial at 9600 baud, this line of code will do:

language:c
Serial.begin(9600);

9600 is a good, default speed for most applications. We’ll use it throughout our experiments. You’ll usually want to stick your Serial.begin() statement in the setup() function. Call it once, set it, and forget it.

After Serial has been initialized, you can start printing messages using either Serial.print([message]) and Serial.println([message]). Both functions work to print a message, but the Serial.println() function adds a new line after the message.

You can print all sorts of with Serial. You can print static, pre-coded messages, by surrounding them with quotes ("), like this:

language:c
Serial.print("This is a long message, which you can print with Serial!");

Or you can print a variable, like this:

language:c
Serial.println(example_variable);   // Print the value of example_variable

As you continue to explore with Serial, you’ll find it’s a powerful debugging tool. It gives you a window into the Sandbox’s mind – you can print out the values of your variables.

Long Data Type

We’ll be using a new variable data type in this experiment: long. A long variable stores 65536-times more values the the int! It can store numbers in the range of -2,147,483,648 to 2,147,483,647. Billions!

Why not always use long? Well it uses twice as much memory – 32-bits. The Sandbox doesn’t have unlimited memory, so it’s best to conserve it when you can.

Sketch and Experiment

Here’s our sketch. Check out the comments for a line-by-line overview.

After uploading the sketch, if you’re waiting for the Sandbox to do something visual, you’ll be waiting forever. Instead open the serial monitor. If you’re using Codebender, you can simply click “Open Serial Monitor” below. If you’re using the Arduino IDE, click the Serial Monitor button up in the top right.

After opening the Serial Monitor, press the D12 button. You should see multiples of 2 start to zoom by. Now you’re calculating!

Your Turn!

  • Something funny happens when the power of 2 gets past 1073741824, and then turns to -2147483648, and then turns to zero. This is because our variable has reached its maximum value and, in a sense, has gotten confused. Can you add an if statement to catch an out-of-bounds multiplier variable and reset it?
  • Try some of the other mathematical operators. Add with +, subtract with -, or divide with /. Can you figure out what the % (modulo) operator does?

10. Do the Analog Slide

Digital inputs, like the button, only allow for two input values: HIGH or LOW. But what about the in-betweens? When you turn the volume up on your stereo, you’re not forced to pick between mute and “OMG MY EARS.” For volume control and other “finely-tuned” settings, we need analog inputs.

Background Information

Analog inputs are components that put data into a system with a range of more than two values. On the Digital Sandbox, analog inputs can produce a value anywhere between zero and 1023 (1024 total values). The value produced by an analog input is proportional to the voltage it produces. If an analog component reads a value of zero, the voltage is 0V. If the output value is 1023, then the voltage is 5V. An analog reading of 512 is about 2.5V, and so on.

A special component inside the Sandbox’s microcontroller called an analog-to-digital converter(ADC) is able to convert that range of input voltages to a discrete number. This is a special circuit that most pins on the Sandbox don’t have. It’s so special that the ADC pins are labeled with a preceding ‘A’. The analog sensors on the board are labeled as “A0”, “A1”, “A2” and “A3.”

Many electronic components produce analog output, the most common of which is a potentiometer. “Pots” come in a variety of shapes and sizes. Rotary pots are very commonly used to adjust the volume on a stereo. Slide potentiometers, like that on the bottom of the Sandbox, are often seen adjusting sound levels on mixing boards.

Active Parts

alt text

Code Components

First there was digitalWrite() then analogWrite(). Then there was digitalRead()…can you guess what’s next?

Analog Input: analogRead( [analog pin] )

To read the value of an analog input we use the analogRead( [analog pin] ) function. Like digitalRead(), this function requires just a single parameter – a pin to read.

That’s where the similarities stop though. Unlike digitalRead() the only pins you can analogRead() on are those with a preceding ‘A’: A0, A1, A2, and A3.

Also, instead of simply returning HIGH or LOW, analogRead()returns a number between 0 and 1023– 1024 possible analog values! An output of 0 equates to 0V, and 1023 means the pin reads 5V. If you get 512, you’re somewhere in the middle ~ 2.5V.

You can store the return value of an analogRead() in a variable, and use it from there. For example, here’s how we store the analog input of A0 into a variable:

language:c
example_variable = analogRead(A0);

Or you can use it directly, like in a comparison for example:

language:c
if (analogRead(A0) > 512)
{
    Serial.println("The analog voltage is above 2.5V");
}

Don’t forget to set your analog pin as an INPUT some time before you read it!

Sketch and Experiment

Here’s the sketch. Upload away!

After uploading the sketch, open up the Serial Monitor. Numbers should begin to stream by. Try sliding the potentiometer, do the values change?

Can you make the output 0? 1023? 512? Take note of which slide pot position relates to which value.

Your Turn!

  • Can you make the slider control the LEDs? You could slide the white LEDs back and forth, or try controlling the brightness of the RGB LEDs with the slider.
  • Why are there only 1024 output values? Why not an even 1000? (Hint: 210.)

11. Automatic Night Light

We now have all the programming tools we need to make some totally awesome, interactive projects. Let’s incorporate the light sensor - another analog input component - to create an automatic night light that turns on when it’s dark.

Background Information

You may not see them, but light sensors are incorporated into all sorts of modern electronic devices. There are light sensors in smartphones, which measure how bright your environment is and adjust the screen brightness automatically. There are light sensors in smoke detectors that detect particles in the air. Photogates use a light sensor to determine when an object passes a certain point – critical for those photo finishes!

The light sensor on the Digital Sandbox is called a photo-transistor. It produces an analog voltage relative to the amount of light it sees. The lower the analog value, the darker the environment. If you cover the sensor completely, you might get the output all the way down to zero. Shine a flashlight on it and you might get a maximized reading of 1023.

Active Parts

alt text

Code Components

Nothing too major to introduce this time, but there is a new variable type!

Constant Variables & Initializing a Variable

The const keyword isn’t really a variable type. It’s a add-on to a variable type, which modifies how that variable works. const is short for constant. When you stick it in front of a variable declaration that variable becomes read-only.

It’s good practice to assign const to any variable you never want to change. In our example, we have a constant darkness threshold that will never change, but may need to be adjusted between code uploads.

When you declare a constant variable, you’re forced to assign it a variable right then-and-there. That means after the variable declaration, you have to add = something;. For example, here’s how we create a const int variable and assign it the value 0:

language:c
const int example_variable = 0; // Create a constant variable, with the value 0

You can initialize any variable, not just constants. Do it when you can. It can save you a line of code, or sometimes your sanity!

Sketch and Experiment

Here’s our sketch. Check through the comments, then go ahead and upload it.

After uploading the sketch, try to cover the light sensor. Do the LEDs turn on? Do they turn back off once you uncover the sensor?

If the LEDs don’t turn on as expected, check to see what value the photocell is reading by opening the Serial Monitor.

By default, we set the dark variable to 10. If the photocell is at or below that, the LEDs turn on, otherwise they’ll stay off. Does that value need to go higher or lower for your night light to switch?

Your Turn!

  • If the brightness is right on the border of on/off, the LEDs can blink unpleasantly. Try adding another if statement to catch if the light sensor is right in the middle range; from there you can dim the LEDs based on what the sensor reads.
  • Try incorporating the RGB LED into this project. If it’s super-bright, make it light up yellow. Kind of dim? Green. Totally dark? Blue.

12. Thermal Alert!

“Is it hot in here, or is it just me?” Using a temperature sensor, which is able to precisely measure the room temperature, we can answer that question once and for all!

Background Information

Temperature sensors are a critical component in many circuits, whether you’re controlling an A/C system or creating a safety mechanism for gas-powered appliances. Electronic temperature sensors come in many form-factors, from big thermocouples that can measure up to 1000 °C to that little black rectangle on the Digital Sandbox.

The temperature sensor on the Sandbox produces an analog voltage that represents the temperature around it. The voltage is actually linearly proportional to the Celsius temperature. If you know the output voltage of the sensor, you can calculate the temperature with this equation:

temperature = (voltage - 0.5) \times 100

We can have the microcontroller do all of that math for us as long as we find the right algorithm - an equation or set of instructions that accomplish a specified task.

Active Parts

alt text

Code Components

Time for another new variable type!

Variables with Decimals: float

Up to this point, every variable and value we’ve used has been an integer. Integers are whole numbers, which means they can’t have decimal points. If you need the precision of decimal points, you have to call up the floating-point variable type.

To declare a floating-point variable, simply use the float keyword and create a variable like you normally would:

language:c
float myPi = 3.1415;

float variables can be huge anywhere from 3.4028235×1038 to -3.4028235×1038.

Floating point numbers may seem great, but they do have their assortment of problems: they take up lots of space, and they take a large chunk of time for the processor to work with. Try to avoid them if you can.

Sketch and Experiment

Here’s our experiment. Take a peek at the comments and upload!

After uploading the sketch, open the Serial Monitor.

You’ll see the temperature in Celsius and Fahrenheit start to flow by. You should also see either the green or red LED illuminate, depending on that temperature reading. If the temperature is above 80 °F, there’ll be a red thermal alert!

Your Turn!

  • Can you add a third check to alert when it’s too cold, by turning on the blue LED? The real trick here is cooling the Sandbox off. One option is to power the board with a battery and stick it in the fridge.
  • Celsius and Fahrenheit are two of the most common temperature scales, but they’re not the only ones. Can you print the temperature in units of Kelvin or Rankine? You’ll need to find an algorithm to convert to them from Celsius.

13. Sound Detecting

<Pitchman voice> Introducing the fabulously groundbreaking SOUND (Sandbox’s Over/Under Nominal Decibels) System! Microphone check 1..2..1..2. With the SOUND you’ll always have an adjustable sound level detector handy! </Pitchman voice>

Background Information

In this experiment we’ll use the Sandbox’s on-board microphone to measure volume levels and display them on the LEDs. The microphone produces a sound wave, which is just another analog voltage that we can measure. The louder the sound, the higher the amplitude of the wave and the larger the voltage.

Without a lot of complicated math and filters, sound can be a difficult thing to measure and react to. Using the Sandbox for voice recognition isn’t quite possible, but it can be programmed pick out high volumes as long as it can sample the microphone input fast enough. We can use the slide potentiometer to set the sensitivity of the display.

Active Parts

alt text

Code Components

You’re probably getting used to this now: time for more variable types! This time it’s not so much a new variable type as a common storage space for variables.

Arrays

Arrays are a group of variables all housed under a single variable name. Array syntax makes heavy use of the square brackets [ and ]. Here’s an example of an array declaration:

language:c
int myArray[3]; // Create an array of 3 int's

You can also initialize your array, using curly brackets:

language:c
// Create and initialize an array containing 5 long variables
long myBigArray[5] = {0, 1000, -44321, 412355234, 42};

To reference a single variable in an array we use an index. Here’s where the most confusing array-related thing comes into play: arrays are 0-indexed. That means, to access the first value in an array you put a 0 inside those square brackets. To access the last variable, you use an index of length_of_array - 1. For example:

language:c
int example_array[4] = {10, 20, 30, 40}; // Declare an array with four values
...
Serial.print(example_array[0]);  // Prints 10 (first value in array)
Serial.print(example_array[2]);  // Prints 30 (third value in array)
Serial.print(example_array[3]);  // Prints 40 (fourth value in array)
// Illegal: Serial.print(example_array[5]); // No good, there's no such thing.

You can create an array of two variables, or you can create an array of hundreds of variables. The size of the array is determined when you declare it. Your array can be of any type you wish.

for Loops

Time to introduce your first real loop: the for loop. for loops are used to repeat a block of code for a specified set of repetitions. Instead of looping indefinitely, like the loop() function, the for loop can be controlled to repeat once, twice, thrice, or thousands of times. It’s up to you.

Here’s the anatomy of a for loop:

language:c
for ( [variable declaration] ; [conditional]; [increment])
{
    // For loop statements
}

There are three important aspects to a for loop declaration:

  1. Variable declaration– Each for loop allows you to declare and initialize a variable. That variable’s scope is limited to the for loop and anything inside that loop.
  2. Conditional test– This test determines when you break out of the for loop. As long as the result of the conditional is true, then the loop runs at least one more time. Once the result of the conditional test is false, we break out of the loop. This is kind of like an if statement inside the for loop. Traditionally you’ll test the variable from the declaration section here.
  3. Variable increment– The point of the for loop is to not loop indefinitely. Each time through, you want to get closer and closer to breaking that conditional statement. That’s what the variable increment section is for. Traditionally, you’ll increment the variable from the declaration section here.

Here’s an example for loop that should run exactly five times:

language:c
for (int i=0; i<5; i = i + 1)
{
    // Loop through here 5 times.
    // i starts at 0
    // each time through i increases by 1
    // once i increases to 5, we break
    // out of this loop.
}

The order of operations of this loop looks a little something like this:

  1. Create a variable called i and set it to 0.
  2. Test i. If i < 5 we run through the for loop. If i >= 5 break out of the loop, we’re done.
  3. After running through the loop, run the increment: add 1 to i.
  4. After the increment jump back up to step 2. And repeat until the condition becomes false (i >= 5).

In this case we’ll exit the for loop after i increases to 5. We’ll have run through it 5 times by then.

Arrays are the perfect partner for for loops. When you need to run through each variable in an array, you can place a variable in the index section, and for loop through each member of the array. We’ll be doing just that in this experiment…

Sketch and Experiment

Here’s the sketch. Read through the comments, they’ll help re-inforce what you’ve just learned about array’s and for loops.

Go ahead an upload the sketch, then make some noise at your Sandbox. Are the LEDs bouncing to your voice? If not, try tapping on the mic.

To adjust the sensitivity of the volume meter, move the slide pot up or down. With the slider set to the far right, it’ll take a really loud sound to make every LED turn on. But if you set the slider too low even the slightest noise will set the meter off.

Your Turn!

  • Can you rewrite the sketch to use the RGB LED instead of the white LEDs? Make it turn red when the volume is really loud, and blue and/or green otherwise. Bonus points for using analog outputs!

14. Opto-Theremin (Addon)

In this experiment we’ll attach a speaker to the Sandbox, and turn it into a musical instrument! By using the light sensor to control our speaker’s pitch, we can create a light-controlled theremin - a non-contact, electronic musical instrument.

Note: This experiment requires the Digital Sandbox Add-On Kit, purchased separately.

Background Information

By precisely modulating a pin, the Digital Sandbox can create electronic waves which, when routed through a loudspeaker, can produce a musical tone. We can program the Sandbox to control two characteristics of musical tone: pitch and duration.

A tone’s pitch is what we perceive when we think of a note as being very high (screams, forks scratching plates, etc.) versus very low (like earth-rumbling bass). The pitch of a tone is very closely related to the frequency played through a speaker. If we toggle a pin from HIGH-to-LOW then LOW-to-HIGH 440 times per second, for example, it produces a 440 Hz (hertz) frequency - a “middle A” pitch. Humans can hear frequencies ranging from 20 (low-pitch, bass) to 20,000 Hz (high-pitch, “ow, my ears”).

We can also program the duration of a tone - the length of time a pitch is played. In our program we’ll use the delay function to set the duration. Playing a tone with the Sandbox is very easy. Just give it a pitch and it’ll start toggling the output pin for you. Much like analog output, you can set it and forget it; the tone won’t stop playing until you tell it to.

Active Parts

alt text

Code Components

This experiment introduces two functions related to sound-making, and another universally handy variable-altering function.

Playing (and Stopping) Tones

The tone function can be used to generate a sound wave and play it using an attached speaker or buzzer.

There are two parameters required to play a tone: a pin and a pitch. The pin should be set to whichever Arduino pin you have a buzzer connected to (don’t forget to set it as an OUTPUT). The pitch should be set to the frequency of the tone you want to play.

Want to play an A440 out of pin 3? Here’s the code:

language:c
tone(3, 440);   // Play a 440Hz wave on pin 3

As you’ll quickly discover, the Sandbox isn’t the most musical device out there. The tones it creates can be just a little-bit grating. If you ever need to halt a pin from playing a tone, use the noTone() function. You’ll just need to specify which pin you want to noTone(), like this:

language:c
noTone(3);  // Stop playing "music" on pin 3

Map: map([value], [fromLow], [fromHigh], [toLow], [toHigh])

Arduino comes with all sorts of handy functions for manipulating variables, one of which is the map function. map translates a value from one range of values to another.

In our experiment, we want to map the 0-1023 input value of the light sensor, and map it down to a scales-worth (440-880) of tones for the speaker. Here’s how we’ll do it:

language:c
int lightSensorValue = analogRead(A1);
int frequency = map(lightSensorValue, 0, 1023, 440, 880);

That maps our frequency from the 0-1023 range to a proportional value in the 440-880 range.

Sketch and Experiment

Here is the sketch for this experiment. Read through the comments and upload away!

Then you’ll need to attach the speaker to the expansion connector. Before you can do that, you will need to break off one group of three pins from the male breakaway headers. Now, you can connector the buzzer, with the top side facing down, to the expansion connector as shown in this image:

alt text

As fun as the opto-thermin may be, the sound is considered grating by some, so the code implements a simple ON/OFF function. Slide the switch over to the “1” position to turn the opto-theremin on.

Once the theremin is on, the speaker should start making noises. Try covering the light sensor; does the pitch change? We’ve turned the RGB LED white, so you can try to corral the light from that to control the light sensor.

You can adjust the duration of the tone by sliding the potentiometer. Slide the pot all the way to zero to get a really fast “zapper” sound, or slide to the right to create a soothing, slow sound.

Your Turn!

  • Try adding a “rest” function to your opto-theremin. Use the button to intermittently cut off the sound output.
  • Instead of using the Sandbox as a musical instrument, can you program it to play a written piece of music? Using a series of tones and delays, try reproducing the chorus of your favorite song!
  • Give yourself a hearing test! What’s the highest frequency you can hear? Can you hear tones others can’t? Can your pet hear pitches that you can’t?

15. Serial Motoring (Addon)

Motors make the world go round. Well, not literally, but they make a lot things we use every day spin and actuate. There are tiny vibration motors in cell phones, speedy motors that spin CDs and Blu-Ray discs, and of course, massive engine motors that help propel our cars. In this experiment we’ll explore one of the most fundamental motor types out there - DC motors - and we’ll tell the Sandbox precisely how fast we want the motor to spin.

Note: This experiment requires the Digital Sandbox Add-On Kit, purchased separately.

Background Information

A DC motor turns electrical energy into a rotational, mechanical energy. DC motors are popular because they’re very simple to control: Give them some voltage and they spin. You can control the speed of a motor much as you might control the intensity of an LED - with PWM - so in this experiment, we’ll be using the analog output block to control the motor’s speed.

This experiment also introduces serial input. Up to this point our conversations with the Sandbox have been very one-sided - the Sandbox has been outputting data to the serial monitor. Serial input allows us to send data to the Sandbox via the serial monitor.

Active Parts

alt text

Code Components

There are a couple new serial-related functions to discuss in this example. In addition to printing out to the Serial Monitor, we’ll be reading from it. Two-way communication!

Reading In Serial Data

To begin, we need to know if any data has been sent from the Serial Monitor. We can use the Serial.available() function to find out how many, if any, characters are waiting for us. There’s a good chance Serial.available() returns 0, which means there’s no data to be read, but it could also return 1, 2, 3, or more. Here’s how we usually use this function:

language:c
if (Serial.available() > 0)
{
    // do something with the Serial data,
    // like Serial.read() or Serial.parseInt();
}

There are a few functions that can be used to read data in from the Serial Monitor. Serial.read() is one of the more common functions – it reads in a single character at a time. In this experiment we’ll be using Serial.parseInt(), which can be used to read in an integer value. This will be handy for our experiment because we want to read in values containing anywhere between 1 and 3 digits.

Here’s an example using Serial.parseInt():

language:c
if (Serial.available() > 0)
{
    // Read a value in from Serial and store it in serial_in:
    int serial_in = Serial.parseInt();
}

When you do a Serial.parseInt() (or Serial.read()) the value of Serial.available() decreases by however many characters you read in. So you’ll only be able to read a serially-sent value once.

Sketch and Experiment

Here’s the sketch. You know the drill: read the comments and upload.

After uploading, connect the motor’s black wire (GND) to the GND pin on the Sandbox’s add-on header. Then, connect the motor’s red wire to the OUT pin on the Sandbox’s add-on header. Your motor should now be connected to the Sandbox as shown in this picture:

alt text

Now open the Serial Monitor, type a number between zero and 255 into the box next to “Send,” and then click that button. The Sandbox should respond with a message, and the motor should start spinning.

What happens when you send 255? How about zero? What happens when you send a number greater than 255 or less than zero (a negative)? Can you spot a block in the code that is restricting those values?

As a “safety mechanism,” if you ever need to stop the motor from spinning, press the button to bring it to a halt.

Your Turn!

  • Try connecting something mechanical to the motor. Perhaps tape a narrow piece of paper to create a spinner and play Twister. Or add a few pieces of paper to create a fan. What else can you connect to the axle to take advantage of the rotational motion?
  • As a programming challenge, can you make the motor smoothly speed up or down when a new serial value is received?

16. Servo Sweeper (Addon)

DC motors are great for spinning an object at high speed with no regard for where it starts or stops. For many applications, though, it’s important to precisely control the position of a motor. Wing flaps in a plane, steering mechanisms in RC cars, and robotic arm platforms are applications that benefit from motorized position control. For those applications we ditch the DC motor and whip out the servo!

Note: This experiment requires the Digital Sandbox Add-On Kit, purchased separately.

Background Information

A servo motor is like a DC motor with an internal controller and built-in sensors that help keep track of its shaft position. A servo motor knows, for example, if it’s pointing at 15° or 115°.

Servos all have three wires that need connecting to: supply voltage, ground, and a signal. The voltage and ground connections supply the motor with power, and the control signal - a PWM output (surprise, surprise) - sets the position of the motor. Once the motor reaches the desired position, it stops until it is commanded to move to a new position.

Servo motors vary in their range of motion - the minimum and maximum angles they can point to. Only specialized, continuous rotation servos can rotate a full 360°; most have a stated range of motion between 90° and 180°. The servo we’ll be using in this experiment has a 180° range of motion.

Active Parts

alt text

Code Components

In the final experiment, we’re introducing you to one of the most powerful aspects of Arduino: importing libraries. Libraries are code written by Arduino or members of the Arduino community which go beyond the basic Arduino core to add unique features.

Using the Servo Library

In this case, we’ll be using the Servo library, which includes all sorts of functions and data types to make controlling servo motors super-easy. To be able to use the Servo library, you first need to include it. That can be acheived with this statement, which should go at the very top of your code:

language:c
#include <Servo.h>  // Include the servo library.

Once you’ve included the library, the next step is to create a Servo variable– an object you’ll refer to throughout your sketch to control the servo. Here’s how we create a Servo object named myServo:

language:c
Servo myServo;  // Create a servo object, which we'll use from here on out.

You’ll usually want this line to go above the setup() function as well – making it a global object. That way we can use it in both the setup() and loop() functions.

So far, so good. As with most everything, we need to initialize the servo. In this case, we need to attach a pin to it. Here’s how we attach a servo to pin 3:

language:c
myServo.attach(3); // Attach myServo to pin 3

Notice how we’re using the myServo object declared earlier. This line of code will usually go in the setup() function. Run it once, then it’s attached for the rest of the program.

Finally, to set your servo to a specific position, you use the write() function. For example, to set your servo to a 55° angle, here’s the code you’ll need:

language:c
myServo.write(55);  // Set the servo to 55 degrees.

After executing that line, your Servo should immediately start spinning till it finds its position.

Sketch and Experiment

Here we go one more time! Upload away.

After the code has been uploaded, connect the servo with the three pin male breakaway header to the Sandbox. Make sure the servo’s black wire (GND) is lined up to the GND pin on the Sandbox, as shown here:

alt text

This program allows you to control the position of the servo motor with the sliding potentiometer. Slide all the way to the right to set the servo to 180°, and all the way to the left sets it to 0°.

The servo will only move if the switch (connected to pin 2) is set to ON. If you leave the switch in the ON position, you can see how fast the motor responds to the servo block. If you move the switch to OFF, set the position of the slide pot, and set the switch to ON, you can see the speed and control mechanisms of the motor.

Your Turn!

  • What happens if you try to rotate the servo beyond 180° (change the last value in the map function)?
  • Think of something to attach to the servo! You could add a clock hand to make a weird, half-circle clock. Or add a papercraft hand, and have your Sandbox give you a high-five!

Resources & Going Further

Congratulations on completing the Digital Sandbox Experiment Guide! If you’re looking for more resources devoted to the Digital Sandbox, Arduino, or ArduBlock, check out these links:

Going Further

Now that you’ve introduced yourself to the world of electronics, hardware, programming, and Arduino, check out some of these tutorials and products to continue your learning.

  • What is An Arduino?– If you’re ready to step into a more open-ended development platform, we encourage you to continue working with Arduinos. This tutorial will help get you started.
  • SparkFun Inventor’s Kit– If you’re looking for more hardware to continue your learning journey, the SIK is the next logical step.

SIK product shot

This kit includes an Arduino, breadboard, and tons of wires, buttons, LEDs, and more components. It also includes a guide with a series of experiments that introduce you to the Arduino programming language (no more blocks!) and electronics.


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

RGB Panel Jumbotron

$
0
0

RGB Panel Jumbotron a learn.sparkfun.com tutorial

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

Introduction

If you’ve ever wanted to simulate live video on an array of RGB LEDs (kinda like the Jumbotron at a sports game), this tutorial is for you. Basically, we’re going to take in live video from a webcam, do a little magic in Processing to translate the color values for the RGB panel, then push them out to a Teensy 3.1 Microcontroller (using the Arduino IDE), which we will program to take in the color values from Processing and turn on the proper LEDs to create a pixelated image of whatever the webcam is pointed at. Fun!

Required Materials

There are a few things you will need in order to complete this project, which are conveniently located in the wish list below:

Suggested Reading

In addition to the hardware, you may want to take a look at some background material that’s relevant to this project. Here are some good links to get you started:

Setup

Once you’ve got the hardware, your first stop is our RGB Panel Hookup Guide - specifically the part about powering the panel. We’ll be powering our project the exact same way, so go ahead a take a little detour over there. Note: Just do the power supply part, NOT the hardware hookup - our configuration is different.

Your power supply should look like this when finished:

alt text

You’ll also want to solder some headers (the ones in the wish list) onto your Teensy so we can stick it into a breadboard and hook it up to the RGB Panel.

alt text

It should look something like this

We’ll be programming using Processing and Arduino - so you’ll want to download both of those if you don’t have them already (the latest versions should work just fine). In order to program the Teensy from the Arduino IDE, you’ll also need to install the Teensyduino library (instructions from the link).

Hardware Hookup

Here are the pin connections between LED panel connector and the Teensy 3.1:

Panel Pin LabelPanel Connector Pin #Arduino PinNotes
R012Red data (columns 1-16)
G0214Green data (columns 1-16)
B037Blue data (columns 1-16)
GND4GNDGround
R158Red data (columns 17-32)
G166Green data (columns 17-32)
B1720Blue data (columns 17-32)
GND8GNDGround
A915Demux input A0
B1022Demux input A1
C1123Demux input A2
D129Demux input E1, E3 (32x32 panels only)
CLK1310LED drivers' clock
STB1413LED drivers' latch
OE1511LED drivers' output enable
GND16GNDGround

Panel connector pin numbering convention: Pin 1 is top left (R0), pin 2 is to the right of pin 1, pin 3 is below pin 1, pin 4 is to the right of pin 3, etc. Pin 16 is the bottom right.

And for handy reference, here’s a pinout chart for the Teensy 3.1:

alt text

When connecting into the ribbon cable connector, pay attention to the notch that signifies polarity. When looking at the cable with the notch facing up and on the left side, R0 (pin 1) should be at the top left.

Red, green, and blue wires inserted into cable

Both red and blue wires should be on the notch side, the greens should be on the other.

alt text

Your hardware hookup should look something like this when you’re done.

Teensy Code

The Teensy code is fairly long and involved, so we’re just going to embed the whole thing here.

As Codebender doesn’t currently support the Teensy boards, you’ll have to copy and paste the code into an Arduino sketch on your computer.

Remember to have the board type (Teensy 3.1), USB Type (serial), and CPU Speed (96kHz overclock) set correctly under the ‘Tools’ menu in the Arduino IDE.

Processing Code

Below is the Processing code in its entirety - BUT - there are a few lines you will most likely need to change, so hold your horsies for a minute.

This line, where we choose our serial port:

serialPort = new Serial(this, Serial.list()[5], 500000);

will need to reflect the actual serial port your Teensy 3.1 is connected to. So you’ll want to replace the ‘5’ in brackets with the number reflective of the array index belonging to your port, which is to say: running this code will cause Processing to print out a list of serial ports, and you need to pick the place in this list that your Teensy is connected to, starting from zero (because it’s an array).

Here’s a screenshot from my computer - the Teensy is on /dev/tty/usbmodem40671 - so I count from zero from the upper left and get 5, which is why there’s a 5 in my code. Make sense? Yeah, me neither.

alt text

We need to go through a similar process with picking the port our USB webcam is connected to.

cam = new Capture(this, cameras[3]);

In this case, you would want to replace the ‘3’ above with the place you find something like ‘USB 2.0 Camera, size=320x240, fps=30’ - in my case it was the fourth one down, and since we count from zero, I put in a ‘3’.

alt text

We’re using the 320x240 resolution because it makes the math a little easier since we have 32 rows of LEDs. Feel free to experiment with the other settings to see what happens.

language:java
/* Live video to 32x32 RBG panel by Ben Leduc-Mills
Adapted from Benjamin Poilvé www.theelectrisquid.fr
based on the work of Markus Lipp and by Alex Medeiros
*/

import processing.serial.*;
import processing.video.*;

Capture cam;
Serial serialPort;
PImage img;
byte[] matrixbuff = new byte[4096];

void setup(){
println(Serial.list());

// Open the port you are using at the rate you want:
serialPort = new Serial(this, Serial.list()[5], 500000);
String[] cameras = Capture.list();

if (cameras.length == 0) {
  println("There are no cameras available for capture.");
  exit();
} else {
  println("Available cameras:");
for (int i = 0; i < cameras.length; i++) {
  println(cameras[i]);
}

// The camera can be initialized directly using an
// element from the array returned by list():
cam = new Capture(this, cameras[3]);
cam.start();
  }
}

void draw(){
  if (cam.available() == true) {
   cam.read();
  }
  img=cam.get(0,0,320,240);
  img.resize(32,24);
  image(img,0,0);
  update();
}

void update(){
  if (serialPort != null ) {

      serialPort.write((byte)(192)); //00001000
      serialPort.write((byte)(192)); //00100001

      int pIdx = 0;
      for (int y = 0; y < 32; y++) {
        for (int x = 0; x < 32; x++) {

          float ga = 4f;

          color c = img.get(x, y);
          int r = int(red(c));
          int g = int(green(c));
          int b = int(blue(c));

          r = (byte)(Math.pow(((float)r)/255.0,ga)*255.0);
          g = (byte)(Math.pow(((float)g)/255.0,ga)*255.0);
          b = (byte)(Math.pow(((float)b)/255.0,ga)*255.0);

          matrixbuff=drawPixel888(x,y,(byte)r,(byte)g,(byte)b,matrixbuff);
          pIdx++;
        }}

    serialPort.write(matrixbuff);
    //println(matrixbuff);
  }
}


byte[] drawPixel888(int x, int y, byte r, byte g, byte b, byte target[]) {
int rowLength = 32*8;

int targetRow =getTargetRow(y);
boolean targetHigh =  getTargetHigh(y);

int baseAddr = targetRow*rowLength;
for (int i=0; i<8; i++)
{
  int baseAddrCol = baseAddr+getTargetCol(x,i);
  int bit = 1<<i;

  target[baseAddrCol]&= targetHigh?7:56; //zero target bits

  if ((r & bit) != 0)
    target[baseAddrCol]|=targetHigh?8:1;
  if ((g & bit) != 0)
    target[baseAddrCol]|=targetHigh?16:2;
  if ((b & bit) != 0)
    target[baseAddrCol]|=targetHigh?32:4;
    }
  return target;
}

int getTargetRow(int y)
{
  return y%16;
}

int getTargetCol(int x, int bit)
{
  return x+bit*32;
}

boolean getTargetHigh(int y)
{
  return y>=16;
}

Putting it All Together

Now for the big finish! Plug in the RGB Panel power supply to a wall outlet, the Teensy 3.1 and webcam get plugged in to your computer’s USB ports. Now start the Processing sketch; it will take a little bit to start up as it goes through all the available cameras (if you have a Mac you’ll notice the green light on your iSight flash on and off once or twice). Once it starts up, a little preview box will pop up on your computer, and your RGB matrix should come to life, with the image from the webcam showing up (somewhat pixelated) on the RGB panel.

For photos, we set it up to look at a SparkFun flame sticker:

alt text

The webcam is attached to the tripod arm, facing downward at the flame. Pretty sweet!

You may have noticed a few scraps of red cardboard on top of the sticker. Turns out the lighting in the studio and the reflectivity of the sticker (it’s shiny) caused the sticker to get washed out - so we improvised.

Resources & Going Further

A lot of people have been playing around with these awesome RGB LED panels and have developed some pretty sweet tools and hacks to explore and integrate into your own experiments. Here are a few I dug up, and please suggest other resources in the comments!

That’s all I’ve got for now - post your projects in the comments below - we’d love to check them out!


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

HMC6343 3-axis Compass Hookup Guide

$
0
0

HMC6343 3-axis Compass Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The HMC6343 is a fully-integrated, high-end, digital compass module that can compute and give the user a heading direction that’s accurate within a couple degrees! It is tilt compensated and is calibrated to handle magnetic distortions. The IC combines 3-axis magneto-resistive sensors and 3-axis MEMS accelerometers, analog and digital support circuits, a microprocessor and algorithms in firmware required for heading computation.

The HMC6343 in all its glory

The breakout board allows for easy use of the HMC6343. All that is required is power (3.3V @ 4.5mA in run mode) and I2C connections to a microcontroller so that the module can receive commands and send data back to the user.

Covered in this Tutorial

In this tutorial, we will help you learn how to use this electronic compass so you can quickly and painlessly integrate them into your project[s]. Here is what we’ll cover:

  • Hardware Overview– An overview of the HMC6343 breakout board as well as some details about the IC.
  • Example Hookup– How to connect the compass to the ubiquitous Arduino so we can start writing code to work with it.
  • Example Code– We’ve written example sketches and a library that demonstrate how to collect sensor data as well as make sense of it.

Required Materials

You may also need a breadboard, jumper wires, and straight male headers to follow the example setup, if you don’t already have these or another way of connecting the Arduino to the breakout board.

Suggested Reading

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

Hardware Overview

The Breakout Board for the HMC6343 breaks out the all the pins you’ll need to send commands and collect data from the electronic compass.

Top down view of the HMC6343 breakout board

As you can see, the breakout has only four pins broken out. Two are for power, 3.3V and GND. Two are for I2C communication, SCL (clock) and SDA (data).

Voltage Supply Requirements

The big alert here is that the HMC6343 has an input voltage range of 2.7V - 3.6V– that range applies to both the power supply and the I2C lines. You can use a 5V or 3.3V micro with this sensor as long as you power the board with 3.3V and use a logic level converter for the I2C lines if you’re using a 5V micro like the Arduino Uno.

Fortunately, you don’t need a lot of power to make the HMC6343 work. In the normal operating mode, the IC typically draws about 4.5mA. It draws even less current in standby (1mA) or sleep (10µA) modes.

Extra Hardware Notes

The HMC6343 can measure and compute a heading direction every 200ms (5Hz). Being able to easily acquire a tilt compensated heading direction accurate within a couple degrees without having your microprocessor spend a lot of time on computation is the highlight of this IC. However, you can read raw magnetometer and accelerometer values if needed.

The HMC6343 has two mounting holes to allow for a secure physical connection to your project. You certainly don’t want the board moving/twisting around independently of your system if you’re depending on it to give you a sense of direction.

Also, there is a solder jumper on the top of the board that is closed by default so that the I2C lines have 10K&ohm; pull-up resistors. If you want to use a different values for your I2C pull-ups, you can disconnect these default resistors by removing the solder from the jumper.

Example Hookup

Soldering

Before you can plug your compass breakout board into a breadboard and connect it to anything, you’ll need to solder connectors or wires to the breakout pins. What you solder to the board depends on how you’re going to use it.

If you’re going to use the breakout board in a breadboard or similar 0.1"-spaced perfboard, we recommend soldering straight male headers into the pins (there are also long headers if you need).

If you’re going to mount the breakout into a tight enclosure, you may want to solder wires (stranded or solid-core) directly into the pins.

Simple Hookup

This example will use an Arduino Uno to collect and interpret the sensor data from the HMC6343. Since the sensor uses I2C communication, all we need are two connections, one for a clock (SCL) and one for data (SDA) in addition to two for power (3.3V and GND).

We simply have to supply the accelerometer with power (3.3V and GND), then hookup the I2C connections. The HMC6343 IC has a max rating of 3.6V on any pin so in order to talk to the HMC6343 with the Arduino Uno or any other 5V microcontroller, we will need a bi-directional logic level converter for the I2C lines.

The following tables shows the connections made for using the HMC6343 breakout with an Arduino Uno and logic level converter.

HMC6343 BreakoutLogic Level ConverterArduino Uno
3.3VLV3.3V
GNDGNDGND
N/AHV5V
SDASDA(A4)
SCLSCL(A5)

Set up this way, I2C communication will be 3.3V on the breakout board side and 5V on the Arduino Uno side. If this is your first time using a logic level converter, or the above table seems confusing, check out our tutorial on logic levels and the hookup guide for the logic level converter. That should clear up any confusion with your setup before proceeding to the code examples.

Example Code

Now that your electronic compass breakout is electrically connected to your Arduino, it’s time to dive into the code. The full library (SFE_HMC6343_Library) and example sketches can be found in the github repository. If you need help with GitUb, visit our tutorial. The same goes for installing an Arduino library.

Once the library is installed, open the example labeled HMC6343_basics.ino. This sketch will teach you how to get a heading direction, pitch, and roll angles as well as accelerometer measurements.

The first lines of this example sketch include the necessary libraries, one for I2C and the other so we can declare and interact with the compass object.

language:c
// Libraries for I2C and the HMC6343 sensor
#include <Wire.h>
#include "SFE_HMC6343.h"

SFE_HMC6343 compass; // Declare the sensor object

The variable compass will be used for all interactions with the sensor itself.

Next we use the setup() function in initialize serial communication and the HMC6343. If the HMC6343 is not detected, an error message will be reported to the Serial Monitor. We also wait half a second before we try to initialize the HMC6343 since it takes that long to be responsive after being powered on.

language:c
void setup()
{
  // Start serial communication at 115200 baud
  Serial.begin(115200);

  // Give the HMC6343 a half second to wake up
  delay(500);

  // Initialize the HMC6343 and verify its physical presence
  if (!compass.init())
  {
    Serial.println("Sensor Initialization Failed\n\r"); // Report failure, is the sensor wiring correct?
  }
}

In the loop() function, we call two functions to read the sensor data and two more to print the data to the Serial Monitor in an easily readable format. compass.readHeading() is a library function that commands the sensor to collect heading direction, pitch angle, and roll angle and then store these values. We will see how to use and print these values in the printHeadingData() function. compass.readAccel() gets a reading from the IC’s 3-axis accelerometer values and these are used and printed in printAccelData(). Here is the loop in full:

language:c
void loop()
{
  // Read, calculate, and print the heading, pitch, and roll from the sensor
  compass.readHeading();
  printHeadingData();

  // Read, calculate, and print the acceleration on the x, y, and z axis of the sensor
  compass.readAccel();
  printAccelData();

  // Wait for two seconds
  delay(2000); // Minimum delay of 200ms (HMC6343 has 5Hz sensor reads/calculations)
}

After calling compass.readHeading(), the variables compass.heading, compass.pitch, and compass.roll carry the heading, pitch, and roll values given by the sensor in tenths of degrees. In the printHeadingData() function, we print these raw values and also print the value converted to degrees. Let’s look at how we do this using the heading direction as an example:

language:c
Serial.print("Heading: ");
Serial.print(compass.heading); Serial.print(""); // Print raw heading value
Serial.print((float) compass.heading/10.0);Serial.write(176);Serial.println(); // Print heading in degrees

In the first line, we print the label. In the second line, we print the actual raw value returned by the sensor, compass.heading and a couple spaces. In the third line, we scale the heading direction by dividing it by 10 so that we can print it in degrees. Serial.write(176) draws a degree symbol and then we print a new line.

Within printHeadingData(), the same process is followed for pitch and roll. When running the program, the Serial Monitor’s output of this function will look like the following:

language:c
Heading Data (Raw value, in degrees):
Heading: 3249  324.90°
Pitch:   28    2.80°
Roll:    24    2.40°

If you have the breakout board parallel to the ground, pitch and roll will be about 0 degrees and you will see the heading angle change as you slowly rotate the board. Try angling the board relative to the X and Y axis and see how that affects your pitch and roll angles.

Printing accelerometer values is very similar. Under the printAccelData() function, we print the acceleration measured on the x axis as follows:

language:c
Serial.print("X: ");
Serial.print(compass.accelX); Serial.print(""); // Print raw acceleration measurement on x axis
Serial.print((float) compass.accelX/1024.0);Serial.println("g"); // Print x axis acceleration measurement in g forces

Again, in the first line we print the label. On the second line, we print the raw acceleration measurement felt on the x axis using the variable compass.accelX. Acceleration measurements for y and z are accessed with the variables compass.accelY and compass.accelZ respectively. On the third line above, we scale the raw value by dividing it by 1024 to get the accleration in g forces. We print that scaled value as well as the unit symbol, g.

Here an example of what you’ll see in the Serial Monitor after calling the printAccelData() function:

language:c
Accelerometer Data (Raw value, in g forces):
X: -52    -0.05g
Y: -44    -0.04g
Z: -1047  -1.02g

At the end of loop() there is a delay of two seconds before new sensor data is read and printed. The fastest you can consecutively acquire new sensor readings is 5Hz or every 200ms.

Advanced Features

All the additional features of the HMC6343 device library are covered in the HMC6343_advanced sketch. However, I’ll overview some of the more appealing features here.

If you want to save power, you’ll want to be able to use the sleep or standby modes. The IC in standby draws 1.0mA as opposed to 4.5mA under normal run mode operation. Under sleep mode, the IC only uses 10µA however it takes the device longer to wake up after entering that low power state. Here are examples of how the two modes can be entered and exited:

language:c
// Enter and exit standby mode (4.5mA draw in run mode, 1.0mA in standby)
// HMC6343 requires 1 ms before it can receive commands after switching modes
compass.enterStandby();
delay(1);
compass.exitStandby(); // Exit standby, enter run mode (default)
delay(1);

// Enter and exit sleep mode (4.5mA draw in run mode, 10uA in sleep)
// HMC6343 requires 1ms after entering sleep and 20ms after exiting before it's able to receive new commmands
compass.enterSleep();
delay(1);
compass.exitSleep();
delay(20);

If you don’t want to mount the HMC6343 breakout board parallel to the ground, then you’ll need to know how to set the new orientation of the board in order to get correct heading, pitch, and roll values. Here is a list of the three possible orientations and the command to configure the HMC6343 to use a new orientation:

language:c
// Possible orientations:
// LEVEL      X = forward, +Z = up (default)
// SIDEWAYS   X = forward, +Y = up
// FLATFRONT  Z = forward, -X = up
compass.setOrientation(LEVEL);
delay(1);  // 1 ms before sensor can receive commands after setting orientation

Those are the most important additional features. However, the advanced example covers reading/printing raw 3-axis magnetometer values and raw ‘tilt’ values (pitch, roll, and temperature). It also covers reading the primary status register (OPMode1) as well as reading and writing to the EEPROM registers of the sensor. There is also a command to reset the processor of the HMC6343 as well as a way to enter and exit user calibration mode.

While the library provides a convenient way to do all these things (every HMC6343 command in the datasheet is used by the library), if you want to know the details of each EEPROM register or how to properly calibrate the sensor, consulting the datasheet is a must.

My hope is that the library allows you to read sensor data and interact with the HMC6343 as easily as possible and allows you to quickly integrate the breakout board into your project.

Resources & Going Further

Thanks for reading! By now you’ve become familiar with both the hardware and software to use the HMC6343, the high end electronic compass. We’re excited to see what you build with this. The following resources may be helpful for you when building your related projects:


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


Hackers in Residence - Cosmic Ray Detector

$
0
0

Hackers in Residence - Cosmic Ray Detector a learn.sparkfun.com tutorial

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

Catching Some Rays

This project seeks to create an inexpensive cosmic ray detector capable of sensing rays greater than 1 GeV in energy. These can be used either as part of a timing synchronization solution, or as part of a large, distributed cosmic ray telescope.

The RayCatcher

The RayCatcher

WARNING!

This project deals with high voltage. Make certain to use appropriate precautions. Do not cut any wires while all batteries are connected; remove and replace batteries while wearing nitrile gloves if using standard battery clips. Drawer-type battery holders, such as the ones used in this project, do not necessitate the use of gloves.

Required Materials


Along with the parts listed above, you will also need a neon bulb.

Note that there are two options for battery holders. The less expensive one certainly works, but the more expensive one is safer, as it allows separation of the battery mechanically with no shock risk.

Tools Needed

Suggested Reading

Circuit

Detector Circuit

In this circuit diagram, R is the sense resistor, usually about 1 kΩ, and V is the bias voltage. The bias voltage should be less than the turn-on voltage (usually either 95 or 65 VDC depending on the type of bulb being used), but should be high enough that a cosmic ray can trigger the circuit, causing a current to flow through the resistor. This is usually about 80-94 VDC, and can be supplied by a bank of 9-volt batteries, or a DC-DC converter that has a sufficiently large capacitor across it to absorb all transients.

alt text

Assembly

Begin by clipping the end connectors off of the 9-volt battery holders. Strip about 5-10 mm of insulation off of the end of each wire.

Twist the red (+) wire of one connector and the black (-) wire of another together. Hold the joint in a pair of tweezers while soldering it together. Repeat until all of the 9-volt connectors have been soldered in this fashion into a line.

alt text

Solder the 1 kΩ resistor across the two wires on the female BNC connector. Glue over the 1 kΩ resistor on the bottom of the BNC connector. Connect the ground (outer) wire from the BNC connector to the loose black (-) wire on the 9-volt connectors, and solder it.

Solder the signal (inner) wire from the BNC connector to one of the two leads of the Neon bulb. Repeat for the other lead of the Neon bulb to one of the two outer pins of the 10 kΩ trimpot. Cut the other outer pin of the trimpot.

Attach the middle pin of the trimpot to the loose red (+) wire on the 9-volt connectors. Then solder the black (ground) lead from the battery connectors to the bottom of the black binding post and solder the red (+V) lead from the battery connectors to the red binding post. Put small globs of hot glue on each and every soldered connection. Turn the trimpot all the way in the direction that is towards the remaining outside pin.

alt text

Bottom view.

alt text

Top view.

Last, connect the batteries to their connectors.

Testing

Tools Needed

  • Oscilloscope, Arduino, Audio Recorder, or Other Output/Logging Device
  • Smoke Detector or Propane Lamp Mantle as Radiation Source
  • BNC-to-BNC or BNC-to-Dual Alligator Cable
  • Nitrile Gloves

Procedure

  1. Connect the detector to the output or logging device using one of the above cables.
  2. Allow for the unit to sit for a few hours with data being logged at as high of a sampling rate as possible.
  3. Put on gloves.
  4. Power down the detector by removing one battery.
  5. Re-power the detector by reconnecting the battery.
  6. Place smoke detector sensor or propane lamp mantle right over the neon bulb, and allow it to sit there for a few minutes.
  7. Remove the radiation source, and remove gloves using this method.
  8. Check the data: there should be some spikes in the signal several samples wide during the first few hours, while there should be no additional spikes during the time that the detector was exposed to the radiation source.

Troubleshooting

  • If there is a greater rate of spikes in the region of the data after the radiation source is introduced, turn the trimpot a few degrees and try again until the rate is as low as can be.
  • If at any point the neon bulb turns on, remove one battery to turn the detector off, rotate the trimpot a few degrees, and reattach the battery. If it comes back on, repeat this procedure.

Resources and Going Further


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

DigitalSandbox PicoBoard

$
0
0

DigitalSandbox PicoBoard a learn.sparkfun.com tutorial

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

Introduction

alt textalt textalt text

The Digital Sandbox (DS) is a creation that came about as a combination between the best features of the PicoBoard, DangerShield, and the Lilypad Protosnap Development Board. We combined the best of these three great introductory learning platforms to create a single board that has several commonly used peripheral devices – LEDs, RGB, slider, button, and a variety of sensors.

alt textalt textalt text

Each of the sensors that are currently on the PicoBoard (slider, button, light, and sound) are also on this board. We thought it would be great to replicate the PicoBoard firmware to work on this device.

Suggested Reading

Uploading Firmware

First, we need to upload firmware to the digital sandbox so that it mimics the same packet information as on the PicoBoard. The original C code for the PicoBoard is available on GitHub, but this code does not work directly in the Arduino programming IDE.

We ported this code base over and made a few adjustments based on the difference of pin configurations on the digital sandbox.

This code reads all of the sensors on the Digital Sandbox, creates data “packets” emulating the PicoBoard, and sends this over to your computer – to be read in by Scratch.

PicoBoard Arduino Code

Copy-paste this code into your Arduino IDE. Select either Lilypad w/ ATMega328 as your board type or Digital Sandbox (if you’ve used our version of Arduino).

Using Scratch

Scratch is an amazing platform for teaching an introduction to programming. It uses simple color-coded blocks that snap together to create programs or “scripts.” It is designed with kids in mind, but the features and functionality of Scratch are extensive enough for you to create your own data-logging dashboards, arcade-style games, or full-length animations. Once you’ve uploaded the “Picoboard Arduino Code,” the Digital Sandbox will work identically to the PicoBoard in Scratch.


As of the writing of this tutorial, Scratch 2.0 does not fully support the PicoBoard. We suggest using Scratch 1.4 until the full PicoBoard extensions are implemented, tested, and rolled out with Scratch 2.0.


To use the PicoBoard Sensor Blocks, click on the blue Sensing Palette:

alt text

At the very bottom of the list, there are two blocks that we can use. One is (slider sensor value) and the other one is a boolean/logic block < sensor button pressed ? > All of the sensors on the PicoBoard (Digital Sandbox) return a value from 0 to 100. It is a scaled value where 0 V ==> 0 and 5 V ==> 100 in the Scratch environment.

alt text

To help us get started, I like to just make a real quick and simple test script using just these four blocks:

alt text

Connect / assemble these blocks into a simple program like this:

alt text

Test it out!

Click the green flag and see what happens. The color of Scratch the cat should change as you move the slider back and forth. You should see the cat change from Orange –> Yellow –> Green –> Blue.

It seems like we’re missing some of the colors. A little digging into the documentation on Scratch shows that the set color effect block operates on a scale of 0 - 200. So, to get the full range, we need to multiply the sensor value by 2. Grab a multiply block from the math operators:

alt text

Then, re-assemble the blocks so that it looks like this:

alt text

Click the green flag and try it again! How many colors does Scratch go through now?

alt text

Play around with other effect options and features. You can tie these to any of the sensors on the PicoBoard (Digital Sandbox) – Slider, Light, or Sound. We tied the temperature to the Resistance-A sensor - which is also a range of values from 0 to 100.

alt text

Reporting Temperature

Using the temperature scale on the Digital Sandbox is pretty simple - it does require a little math, though. Looking at the datasheet on the temperature sensor on this board TMP36 can be daunting, but what we care about is this:


“The TMP36 is specified from −40°C to +125°C, provides a 750 mV output at 25°C, and operates to 125°C from a single 2.7 V supply.” and “Both the TMP35 and TMP36 have an output scale factor of 10 mV/°C.”


Translation

The TMP36 outputs a voltage that varies linearly with the temperature. Because it is linear, we can start with our favorite equation from Algebra I– the general equation for a line:

y = mx + b

Temp = (slope) * (voltage) + b

The proportionality (ratio) between voltage and temperature is 10 mV/°C, but we want our slope in units of °C/mV. So, if we take the reciprocal of 10 mV/°C, this is 0.1 °C/mV. It’s the same proportion, and it has the correct units. That’s our slope!

The intercept point requires a little math. Using the information that says “provides a 750 mV output at 25°C,” we can find the intercept point.

25 °C = (0.1 °C/mV)(750 mV) + b

25 °C = 75 °C + b

-50 °C = b

Final Equation

Temp (°C) = (0.1 °C/mV) * (voltage in mV) - 50 °C

In Scratch

In Scratch, the voltage is scaled from 0 to 100. So – let’s see how this works:

Temp = (0.1 °C/mV) * (voltage in Scratch/100)*(5000 mV) - 50 °C

Looking at this, I see a lot of decimals, multiplication by 1000’s and divide by 100s. It seems like we should be able to simplify this. First, let’s simplify the divide by 100 and multiply by 5000.

Temp = (0.1 °C/mV) * (voltage in Scratch*(50 mV) - 50 °C

Next, multiply the 0.1 by the 50 and simplify to:

Temp = (voltage in Scratch*(5 °C) - 50 °C

And, in Scratch – this looks like:

alt text

Sample Scratch Script

We created a little sample script to show all of the features all in one example. Feel free to use this, take parts of it, or re-mix it into your own new program. It changes the sprite based on the light input, the slider value, and the sound level.

The sprite will also walks back and forth if you flip the slide switch to the ON (1) position and will change color (and play a sound) when you push the button. Play around with this example. We’re sure you’ll come up with other fun ideas too!

alt text

Click here to download a copy of the file to run on your own computer.

Going Further

The DigitalSandbox Picoboard is a great start to programming and interacting with sensors, but it only allows you to read input values into Scratch and it does not allow for us to control actuators or affect OUTPUTS.

If you’re interested in extending this to more than just reading sensors, try Scratch4Arduino or ArduBlock. We have an entire series of activities and experiments built around Ardublock using the Digital Sandbox here.

Other Resources


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

SparkPunk Sequencer Theory and Applications Guide

$
0
0

SparkPunk Sequencer Theory and Applications Guide a learn.sparkfun.com tutorial

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

Introduction

SparkPunk and Sequencer

The SparkPunk Sequencer is a musical control voltage sequencer designed to control the SparkPunk Sound Generator. With the pair, you can create ten-step musical motifs, but there are hidden opportunities in the sequencer: it can be modified and connected to external hardware in clever and interesting ways.

We will start by explaining the internals of the sequencer in more detail. We’ll step through the major functional blocks of the schematic, learn how they interrelate, and examine the important signals that connect those blocks. Then we’ll step into some simple modifications that change the behavior of the sequencer. From there, we’ll look at how we can add more hardware to make increasingly sophisticated systems.

This document picks up where the Hookup Guide left off. If you haven’t yet built your sequencer, start there, then come back.

Theory Of Operations

In order to modify the sequencer, it is useful to understand some of its internal workings. We’re going to step through the functional blocks on the schematic, and discuss how each works in more detail. If you’d like a better look at the schematic or PCB artwork, you can download the Eagle files from Github.

The sequencer was designed in simulation before the prototype hardware was constructed. Also in the Github repo are Spice simulation files, which run in the free LTSpice environment. The simulations proved to be very valuable, especially in getting the variable-width gate circuit working.

The SparkPunk Sequencer is a mixed-signal circuit – it consists of a digital section for the clocking and play logic, and an analog section to generate the control voltage and gate.


Digital Section

We’ll start with the digital portions of the circuit. These are mostly implemented using CD4000-series CMOS logic chips. These chips are rated for a wide range of supply voltage – unlike some newer, more sensitive logic chips, they’re prefectly happy being powered by a 9V battery.


Run Button

The RUN pushbutton on the sequencer is a momentary-contact type switch. To use it in a toggling application (push once to turn on, push again to turn off), it’s connected to one section of a CD4013 flip-flop. The switch is connected to the clock input on the flip-flop, and the inverted logic output is looped back to the data input.

button circuit

Every time the button is pushed, the flip-flop output changes state.

The flip-flop has two outputs, called Q and Q, and their functions can be described as:

  • Q is called “Stop.” It is asserted when the sequencer is stopped.
  • Q is called “Run.” It is asserted when the sequencer is running.

The run and stop signals are used in other portions of the circuit – other circuitry needs to react appropriately when the sequencer is started or stopped, and these signals allow for those actions.

The flip-flop also has data preset inputs (the Set and Reset pins). When power is applied, the capacitor on the Set input holds it high for a moment, causing the flip-flop to initialize in the Set state, so the sequencer is stopped by default.

The Run signal is connected to the LED in the button, so it illuminates while the sequencer is playing.


Tempo Clock and Divider

The next functional block of the circuit is the tempo clock. It consists of two stages: the clock oscillator, and a divider.

The oscillator portion is is based around a 7555, which is a low-power CMOS version of the venerable 555 timer IC. The basic circuit configures the timer in astable (free-running) mode, with the timing set by a potentiometer.

Clock and Divider Schematic

When the sequencer is running, the clock is enabled by the Run signal from the button circuit. The 7555 does not run when the sequencer is stopped.

The output from the 7555 is not used directly by the rest of the sequencer. The 7555 output is further conditioned using a divide-by-two circuit, using the other flip-flop in the CD4013. This is done for several reasons:

  • First, the clock generated by the 7555 isn’t perfectly symmetrical - the pulse width changes with frequency. This made the short/long switching hard to achieve, and also made the tempo LED hard to discern - wide pulses meant it was almost always illuminated.
  • Second, by dividing the clock down, we can achieve a useful range of tempos with smaller timing capacitors. The division in half has the same effect as doubling the capacitor value.
  • The divided-down clock has a pulse width of 50%, which is then used as an input to the system the generates the short (half-step long) gates.
  • Finally, there was an otherwise unused flip-flop in the CD4013.

The Q output of the flip-flop is the clock signal used by the rest of the circuit. It also drives the RATE indicator LED.


CD4017

The CD4017 is essentially a sequencer on a chip. It’s the heart of this kit, and the rest of the circuit serves in a role to support its basic functionality. Internally, it has a binary ripple counter and a demultiplexer. It receives pluses on pin 14, which causes the counter to increment. The value of the counter is decoded so that one of the ten output pins (labeled Q0 through Q9) is active at a time. Each clock pulse causes the next output pin to be selected, and the selection starts over at Q0 after Q9 has been reached.

CD4017 Timing

The timing of the CD4017 can be seen in the diagram above. The clock is the bottom trace, and the ten outputs are the traces above that. On each rising edge of the clock, the high logic level progresses to the next successive output.

Heart of Sequencer

The CD4017 also has a reset pin, which restarts the output selection from Q0 when it is asserted. This allows us to implement some more subtle behavior:

  • When the sequencer is not playing, it sits at the first step. This is done by connecting the stop signal to the reset pin on the CD4017.
  • When the sequence starts playing, the reset line is held high for a brief moment by capacitor C10. This means that the CD4017 effectively ignores the first clock pulse, and that the sequence starts on the first step. Without this cap, the clock starts as soon as the run button is pressed, and the sequence immediately advances to the second step.
  • By feeding the selection pulse from one of the step outputs back to the reset pin, we can constrain the pattern to fewer than ten steps.

Analog Circuitry

The Steps

The ten outputs from the CD4017 are fed to the ten step circuits. Each step is a copy of the same circuit.

Step Schematic

The CD4017 outputs are only rated to supply a couple of milliamps, so the step circuit starts with a transistor configured as an emitter follower, allowing for more output current to illuminate the LED. The step selection voltage is also fed to the slider, which is wired as a voltage divider. When the step is selected, the wiper of the slider travels between ground and about 8.3V. The gate switch on each step selects between the selection voltage, and ground.

The slider wipers and switches are coupled to common buses, POTSUM and GATESUM respectively, using diodes. This configuration implements the selection of the maximum voltage. Since only one step is selected at a time, that means all but one input to the max function will be zero, allowing the selected step to dominate.


Slider Voltage Processing

To understand how the slider voltage is manipulated, we need to step back and look a little more closely at the device it is feeding. The SparkPunk Sound Generator uses a 7556 dual timer IC as its main tone source. The 7556 has control voltage inputs, but they behave in a somewhat counterintuitive manner – a higher voltage on the CV pin results in a lower frequency – an inverse relationship. It also works best in the middle of the range between ground and the power supply voltage – leaving that range causes the 7556 to stutter or stall.

The LM358 amplifier IC is also constrained. The datasheet states that the maximum input level is 1.5V below the positive supply rail.

The sequencer manages the voltages coming from the slider wipers accordingly, inverting and scaling the voltage into a usable range.

CV circuit

Follwing the signal through the circuit, first we find a divider, to drop the level into the LM358’s allowable range. That signal is buffered with an opamp stage, then fed to the variable lowpass filter that implements the slide. As the resistance of RV2 is increased, it takes C3 longer to charge. The filter is buffered with another opamp stage. Finally, the third opamp inverts and offsets the control voltage into a range suitable for the 7556.


Switch Voltage Processing

The gate behavior of the sequencer can be changed between short gates, which are each one-half step in duration, and long gates, which are a complete step long. Additionally, the gate is only driven when the sequencer is running, so it sits quietly when stopped. The logic behind the gate can be expressed by the following equations:

Long gate = running && step switch
Short gate = running && step switch && clock pulse

This logic is implemented using analog processing.

Gate Circuit

The running, clock, and switch signals are scaled and added together, resulting in a stair-step shaped waveform. Each of those signals contributes a portion to the overall sum, as denoted by the colored rectangles below.

Gate Voltage-Staircase

Notice that when a clock pulse overlaps a step switch that is turned on, they add up to the highest step shown, and the step switch by itself is the second highest step. A clock pulse that doesn’t overlap the switch being set is lower still. We use an op-amp comparator circuit to apply thresholds to discern those first two stairstep levels.

The actual circuit uses an inverting op-amp stage to do the summing, so the result is upside down compared to that shown above. This is corrected by the comparator stage that generates the gate, which is also inverts.

The threshold voltage on the comparator determines the length of the gate pulses. Short gates are generated when the threshold voltage is tripped by the sum of the clock and switch signals.

Short Gate Waveforms

Short Gate Pulse Generation

The clock is shown in red, and the inverted stairstep waveform in green. The comparator threshold is shown in light blue, superimposed over the stairstep. When the stairstep falls below the threshold, the comparator output, in dark blue, switches high.

Long gates use the same processing, but the threshold voltage is adjusted so that only the switch voltage is required to trip the comparator.

Long Gate Waveforms

Long Gate Pulse Generation

Strong Foundation

With the understanding of the internal details described above, we’re how ready to look at some ways that those details can be leveraged into modifications and more sophisticated deployments.

Simple Modifications

With the knowledge of the sequencer internals from the previous section, we can explore some modifications and more advanced uses of the sequencer.

We’ll start with some simple modifications that don’t require much effort, or very much external hardware.

Sequence Length Adjustment

The CD4017 IC at the heart of the Sequencer has ten outputs. While ten is the basis for decimal counting, it’s not always the obvious choice for musical composition - four, six or eight steps are much more common musical time signatures. As we mentioned in the hookup guide, the length of the sequence can be constrained to shorten the sequence.

The CD4017 has a pin that resets the internal counter. By feeding one of the step voltages back to that pin, we can constrain the sequence to a shorter range.

The Sequencer PCB has ten pairs of pads across the lower right edge. The step voltage from each step is present on the top pad, and the bottom pad is the counter reset. If you connect the top pad to the bottom pad, it causes the sequence to reset when that step is selected. For instance, if you short the Step Out 9 pad to the adjacent Seq Reset pad, when step 9 is selected, it will cause the sequence to reset to the first step, effectively limiting the sequence to 8 steps.

Last Step With Shunts

You can make the connection between the pads a number of different ways. If you wanted the constraint to be permanent, you could solder in a short piece of wire. For a manually adjustable limit, snap breakaway headers off into 2-pin pairings, and solder them into each pair of pads. Then you can use jumper shunts to bridge them.


One-Shot Sequence Playback

Similar to the reset pin on the CD4017, there is an asynchronous set pin on the flip-flop that latches the play button (recall that the Q output from the flip-flop is the source of the “stop” signal). If we route a step voltage to that pin, we can cause the sequence to stop itself when that step is reached.

This is easy do do using the pads near the CD4013, marked ONCE. Again, you can use a 2-pin header or a switch to make the connection.

One Shot Setting

This works in conjunction with the “last step” setting described above – a last step is selected, and the sequence will run once, halting when it reaches that step. Because the flip-flop requires a pulse to set it, there is no easy way to do this with a full set of ten steps, as there is no additional pluse to indicate it has moved beyond the tenth step.


Component Values

Tempo Clock

The tempo clock is based around the parallel combination of C2 and C4. By changing those caps, we can change the rate of sequence playback. The equation that governs the frequency is stated in the 7555 datassheet, as

7555 frequency = 1/(1.4 * R * C)

Where R is the series combination of R1 and RV1, adjustable between 470 &ohm; and 10,470 &ohm;, and C is 20 µF, the parallel combination of C2 and C4

Because we’re dividing the 7555 clock in half, the actual tempo clock is half that

clock frequency = (7555 frequency/2)

This results in a range of about 1.5 Hz at the lowest, to 35 Hz at the highest.

To make the clock run slower, increase the capacitance. Lowering the capacitance will raise the frequency.

Slide Time

Similarly, we can change the maximum slide time by adjusting cap C3. Again, larger values will take longer to charge, lengthening the slide. Reducing the time with smaller values is probably not terribly useful, as we can already adjust the time downwards with potentiometer RV2.


Colored LEDs

If red is not to you liking, you can switch out the LEDs for other colors. The board was fits regular 5mm (AKA T-1 ¾) LEDs. We offer them in many colors, including red, yellow, blue, and green. You may need to substitute different resistors for the series 2.2K &ohm;, to adjust the brightness.

Interfacing With More Hardware

Heads Up!

We’re working our way into more advanced territory. The sections below are a more adventurous than anything we’ve touched on yet, and involve desoldering, modifications to the PCB, and more detailed troubleshooting skills. Some of the descriptions are purposefully vague, as an exercise for more knowledgable users.

Synchronizing Multiple Sequencers

Twins

If you were following the theory of operations carefully, you probably noticed that when the text described the signals run, stop, clock, and button, the signals in the schematic were actually marked “out” and “in,” with a jumper connecting them. These signals are intended to be broken up that way so they can be easily routed between multiple sequencers.

alt text

Synchronization Interface

Those signals are all present in the synchronization interface, on the left edge between the run button and tempo knob. The following table denotes the behavior of each of those signals exhibits.

SignalAs OutputAs Input
CLKPulses at tempo generated by clock systemCauses CD4017 counter to increment
STOPIndicates sequencer is stoppedResets CD4017
Holds clock divider in reset
RUNIndicates sequence is playingAllows 7555 to run
BTNIndicates button has been pushedPulses cause play/stop to toggle

In paticular, notice that for the sequencer to advance, the stop line must be low, run line must be high, and clock pulses need to come in on the clock line.

The most obvious way to use this port is to synchronize multiple sequencers. One acts as the master clock, with other sequencers following (or “chasing”) that clock.

Modifications

If you have two sequencers, it’s not hard to modify them to use the synchronization port. Select one to be the the master clock, and the other to follow that clock.

  1. First, on the slave sequencer, cut the copper traces that run between the columns of the synch port.

    Cutting Traces

  2. Then run wires from the pads in the “O” (output) column on the master sequencer to the “I” (input) column on the slave. We’re using snappable headers and 4-pin jumper wires, so we can easily disconnect the units later.

    Synch Cable

  3. You’ll also need to join the grounds of both sequencers together. It’s easiest to tack-solder a short length of wire to the “GND” pin of the 9V battery box on one sequencer, and run it to the same point on the other.

    Power Jumpers

    You can also connect the nearby 9V terminals, so that you only need a single battery to power the whole conglomeration, but it will eat batteries twice as fast.

  4. Now, when you press play on the master, both sequencers will start and run together.

alt text

One clock master can drive multiple slaves, if you connect the slave synch input ports in parallel with each other.

To make a sequencer that can convert between being a master and slave, you can use normalled jacks, or install two pins from a snappable header and use jumper shunts to reconnect the pins.

Power

As you start to stack up multiple SparkPunks and Sequencers, you start to wind up against the limits of what a 9V battery can reliably power. The first symptom of insufficient power is that the long/short gate feature stops working reliably.

If you’d like to avoid batteries altogether, you can substitute a 9V wall adapter. Each Sequencer & SparkPunk pair draw a maximum of about 20 mA, so that adapter should be good for many, many pairs. The best way to connect it is using a star topology, with each sequencer having a dedicated power and ground cables back to the power supply, rather than daisy-chaining power to multiple sequencers.

Other Synthesizers

One last modification worth mentioning is to use the Sequencer with other synthesizers.

As we reviewed in the description of the control voltage interface, the main control voltage output is inverted - a higher voltage results in a lower frequency from the Sound Generator. This is counter-intuitive, and also the opposite of the convention used by most other synthesizers. Regular analog synthesizers with control voltage inputs produce higher frequencies for higher control voltages. This voltage is present inside the Sequencer, and is found on the solder pad marked RAW CV OUT. This is the stage after the slide has been applied, but before the amplifier that inverts it for the SparkPunk.

Pads Closeup

Before you try this, you should check the specification of the synthesizer you intend to control – additional circuitry may be needed to get the raw CV scaled into a suitable range. Some synths are limited to a gate of only 5V – you can use a divider or Zener diode clamp to attenuate the 9V gate into that range.

Tempo CV Input

The eagle eyed reader will have also spotted the TEMPO CV IN pad in the photo above. It is similar to the CV inputs on the Sound Generator – voltages between &frac13; Vcc and &frac23; Vcc adjust the tempo over about a 2-to-1 range. The response is inverted – higher voltage results in lower frequency. Exceeding the &frac13; to &frac23; window can cause the 7555 to stutter or stall.

We don’t have any specific mods for the Tempo CV, but it is worth mentioning as an option, so someone will sure dream up a use for it!

Resources and Going Further

Resources

In this tutorial, we used the following parts

Going Further

  • Raymond Scott is largely recognized as the inventor of the step sequencer, which he called the “circle machine.” You can hear some examples of it in these videos, and learn more about the man and his music at his website.
  • We’ve also got a tutorial for a similar digital device, the Auduino Step Sequencer.
  • Nic Collins' Handmade Electronic Music book is a good introduction to musical circuits, with a number of breadboard projects you can build from scratch.

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

SparkPunk Sequencer Hookup Guide

$
0
0

SparkPunk Sequencer Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The SparkPunk Sequencer kit is an analog control voltage sequencer designed to drive the SparkPunk Sound Generator.

SparkPunk and Sequencer

SparkPunk and Sequencer, fully assembled

An Abbreviated History Of Sequencers

In general, a sequencer is a device that produces timed control signals in a particular order. These signals are used for many purposes - for instance, the electronic module that operates a set of traffic signals is one type sequencer, the control system that runs an elevator is another. Both have to produce the correct signals, in the proper order, with the right timing (such as stopping east-west traffic when north-south traffic is moving, then making sure the yellow light is illuminated for the correct period when the light changes).

Musical sequencers are used to control musical instruments. They generate signals to control performance parameters such as pitch and timbre, with specific rhythmic timing. The original sequencers, such as Raymond Scott’s circle machine, were capable of generating short, repeating musical phrases. More recently, sequencers have evolved into large software packages running on computers, generating MIDI and audio events, capable of creating complete musical compositions.

The SparkPunk Sequencer is reminiscent of its analog forebears. It cycles among ten steps, reading the slider and switch for each, producing corresponding analog voltages on the output pins. It offers hands-on control, with its array of knobs, sliders, and switches. It seamlessly integrates with the SparkPunk Sound Generator for your creative musical enjoyment.

This tutorial will guide you through the assembly and testing of the SparkPunk Sequencer.

Before We Begin

The SparkPunk Sequencer is more complex than most SparkFun soldering kits. It has a greater variety of components, mounted on a larger board. If you’re new to soldering kits, or need some practice with component identification, we can recommend a number of simplerkits to help you get up to speed.

The sequencer is intended to control the SparkPunk Sound Generator. If you have purchased both kits together, we recommend that you start by assembling and testing the sound generator, then build the sequencer. In later steps, we’ll be using the sound generator to test the sequencer, and that process will be smoother if you’re confident that the sound generator is functional.

Necessary Tools

Additional Tools and Supplies

Suggested Reading

Kit Contents

Let’s begin by taking inventory of the parts in the kit. You can organize parts in the groupings shown below, which will make them easier to locate as you assemble the kit.

Circuit Board

SparkPunk Sequencer PCB

  • One SparkPunk Sequencer PCB

Diodes

Diodes

  • Twenty-one 1N5819 Schottky diodes
  • Two 1N4148 Silicon diodes

Resistors

Resistors

  • Six 100k Ohm 1/4W Resistors (Brown - Black - Yellow - Gold)
  • Three 47K Ohm 1/4W Resistors (Yellow - Violet - Orange - Gold)
  • Four 1K Ohm 1/4W Resistors (Brown - Black - Red - Gold)
  • One 33K Ohm 1/4W Resistor (Orange - Orange - Orange - Gold)
  • One 470 Ohm 1/4W Resistor (Yellow - Violet - Brown - Gold)
  • One 47 Ohm 1/4W Resistor (Yellow - Violet - Black - Gold)
  • Twelve 2.2K Ohm 1/4W Resistors (Red - Red - Red - Gold)
  • Seven 10k Ohm 1/4W Resistors (Brown - Black - Orange - Gold)
  • Three 22K Ohm 1/4W Resistors (Red - Red - Orange - Gold)

Capacitors

Capacitors

You may need a magnifying glass to read the markings on the ceramic capacitors.

  • One 1000uF 25V Electrolytic Capacitor
  • Three 10uF 25V Electrolytic Capacitor
  • Six 0.1uF Ceramic Capacitor (marked 104)
  • One 1nF Ceramic Capacitor (marked 102)

Integrated Circuits

Chips

  • Three LM358N dual operational amplifiers
  • One CD4017BE one-of-ten counter/demultiplexer
  • One CD4013BE dual flip-flop
  • One ICM 7555

Semiconductors

Semiconductors

  • Eleven red LEDs
  • Ten 2n3904 NPN transistors

Potentiometers

Pots

  • Ten 10K Ohm linear slide potentiometers
  • Two 10K Ohm rotary potentiometers

Switches

Switches

  • Twelve Mini single pole, dual throw (SPDT) Switches
  • One Red LED Tactile Button

Mechanical Components

Mechanical Components

  • One 9 Volt Alkaline Battery
  • One 9V Battery Holder
  • One 5-pin right angle male header
  • One 5-pin right angle female header
  • One 3/8" long 2-56 Phillips head machine screw
  • One 2-56 nut

If you come up short, please contact customer service, and they can set you up with replacement parts.

Electronic Assembly I - Diodes

With a PCB like this, it’s usually easiest to assemble if you start with the shortest components, and work up to the tallest ones. That way, you don’t have work around the bulk of the larger components.

Diodes

The silicon diodes are the shortest components, so we’ll start with them. Find the Silicon diodes in the kit - they have a small orange body that looks like a glass bead, with a black stripe near one end.

The silicon diodes are installed side-by-side in the locations marked below. It doesn’t really matter which one you start with.

Silicon Diode Location

These diodes are polarized. The glass body has a black stripe on one end, which matches up with the white stripe on the PCB silkscreen.

Diode Orientation

Align the stripe on the diode with the stripe on the PCB

The diode gets mounted on the top the the PCB, the side with the silkscreen outline. Bend the leads so they fit through the holes, and push them through until the body sits on top of the PCB. You can bend the legs outward slightly to hold the diode while you work.

Bend leads to hold diode

Turn the board over, and solder the diode in place. Take care to make good solder joints, with just the right amount of solder. The solder should flow evenly between the board the the lead, making a small, smooth dome or cone shape. If you’re not sure about your fillets, refer to the diagram in our soldering tutorial.

Solder Fillets

Once it’s soldered, trim the excess leads near the fillet.

Snip!

Install the other diode next to it. Again, it should be inserted with the stripes on both the body and PCB aligned, which faces the opposite direction of the first diode.


After both silicon diodes are in place, let’s install the Schottky diodes. (Okay, they’re a tiny bit larger than the resistors, but not so large that it will interfere with later steps).

The Schottky diodes are black cylinders with a gray or white stripe on one end. There are a lot of them on the board - the first towards the upper left corner, and the others placed in pairs across the bottom-right edge of the board.

Schottky Diode Locations

Like the silicon diodes, The Schottkies are polarized. Match the stripe on the body with the stripe on the PCB. Take care that the ones across the bottom edge of the board are oriented correctly - they alternate in polarity, with every other one being the opposite of it’s neighbor.

Schottky Polarity

Solder them in, and trim the excess leads.

With all the diodes installed, your PCB should look like this (click picture to enlarge):

Diode Waypoint

Before proceeding, take a moment to verify that you have the stripes on all the diodes oriented correctly. They will be harder to fix when all of the other components have been installed.


Lather, Rinse, Repeat

The pattern we’ve established here (insert, solder, trim) will be repeated for each of the other components on the PCB.

Electronic Assembly II - Resistors

Resistors are not polarized - they can be installed in either orientation. We’ll install the resistors in order of increasing resistance value. For each resistor value, we’ll insert, solder, and trim the excess leads just as you did with the diodes.

There are quite a few resistors on this board. We’ll install all of them in the following steps. To keep the process organized, we’ll start with the lowest value, and work up the the highest. The resistor values are indicated by the colored stripes on the resistor body. The color codes are noted in the photo captions below, but if you’d like a more thorough explanation of how the codes work, you can find that in our Resistor Markings Tutorial. You can also verify ther resistor values using a multimeter.

The resistor locations on the PCB are marked with silkscreened numbers inside the outline of each resistor. Once you’ve deciphered the markings, you can find the corresponding value written on the board, and install the resistor there. This may sound daunting, but we’ve got helpful pictures with each value highlighted in the following steps.


47 &ohm;

The lowest value resistor is the 47 &ohm; resistor. It is located near the left edge of the PCB, as seen below:

47 &ohm; Location

47 &ohm; Resistor (Yellow - Violet - Black - Gold)


470 &ohm;

The next resistor is the 470 &ohm;. It’s located on the left, near the center of the board, shown here:

470 &ohm; Location

470 &ohm; Resistor (Yellow - Violet - Brown - Gold)


2.2K &ohm;

There are a bunch of 2.2K resistors on the board - twelve to be precise. Two are on the left hand side, and the other ten are across the top right edge of the board, highlighted below:

2.2K &ohm; Location

2.2K &ohm; Resistors (Red - Red - Red - Gold)


1K &ohm;

There are four 1K &ohm; resistors. Two of them are placed as a pair near the left edge, and the other two are paired near the center of the board. They’re all circled in this photo:

1K &ohm; Location

1K &ohm; Resistors (Brown - Black - Red - Gold)


10K &ohm;

There are seven 10K &ohm; resistors, spread across the left side of the board.

10K &ohm; Location

10K &ohm; Resistors (Brown - Black - Orange - Gold)


22K &ohm;

There are three 22K &ohm; resistors, two near the top center, and one towards the top left corner.

2K &ohm; Location

22K &ohm; (Red - Red - Orange - Gold)


33K &ohm;

The single 33K &ohm; resistor is located here:

33K &ohm; Location

33K &ohm; 1/4W Resistor (Orange - Orange - Orange - Gold)


47K &ohm;

The three 47k &ohm; resistors are spread across the upper left of the board, as depicted below.

47K &ohm; Location

47K &ohm; Resistors (Yellow - Violet - Orange - Gold)


100K &ohm;

Finally, we reach the 100K &ohm; resistors. There are six of them, distributed around the left side of the PCB.

100K &ohm; Location

100K Ohm 1/4W Resistors (Brown - Black - Yellow - Gold)


At this point, all of the diodes and resistors have been installed. Your board should look like this (again, click on the picture for a higher resolution version):

Resistor Waypoint

Take a moment to look around your work area for loose resistors or diodes that you might have missed. All of the resistors and diodes should be mounted on the PCB

Electronic Assembly III - Capacitors

Capacitors

With the resistors complete, we’ll move on to the capacitors (also known as “caps” for short). The shortest caps are the ceramic ones - the ones in this kit are little orange/yellow blobs, each with two leads.

Capacitor assortment

Electrolytic capacitors (top), ceramic capacitors (bottom).

Like the resistors, the ceramic caps are not polarized - they can be installed facing either direction.


0.1µF Ceramic Capacitors

There are six 0.1µF caps. The caps themselves are marked 104. The values are printed on the side of the caps, but in very tiny print - in some cases, it might be so small as to be nearly invisible. A magnifying glass can help. Be careful with these caps as there is also a 1nF cap. It’s almost the same size as the 0.1µF caps, but it is marked 102.

The 0.1µF capacitors should be located as shown below:

0.1µF Cap Locations

0.1 µF Ceramic Caps

You’ll notice that the lower left cap is missing the value marking on the silkscreen - it is indeed a 0.1 μF cap.

The procedure for these caps is similar to the components we’ve already installed. Insert, solder, then trim.


1nF Ceramic Capacitor

There is one 1nF (sometimes also known as 1000 pF) cap. It’s marked 102, and it is located here:

1nF Cap Location

1nF Ceramic Cap


Electrolytic Caps

Electrolytic Capacitors are the small cylinders that look like tiny soda cans. They are polarized, having a positive and a negative lead. The positive lead is usually longer than the negative, and the negative side is usually marked by a stripe on the body of the capacitor itself. The pads on the PCB are marked with both “+” and “-” symbols. Be sure to line up the “-” on the body with the “-” on the PCB.

Electrolytic Polarity

Electrolytic Capacitor Orientation

There are three of the 10 µF Capacitors on the board, found in these locations

10µf locations

10µf, 25V Electrolytic caps


Check Your Progress

At this point, all of the smaller passive electronic components have been installed. Your board should look like this:

Cap Waypoint

Odd Man Out

There is still one cap remaining, the large 1000 μF electrolytic. It gets mounted on the back of the board, but we’ll hold off on that for the moment, as having it on the back makes the board rather cumbersome. We’ll revisit it in the electromechanical section.

Electronic Assembly IV - Integrated Circuits and Semiconductors

ICs

The chips, or integrated circuits (IC’s) on this PCB are all in through-hole Dual Inline Packages (DIP). The IC’s are polarized, and need to be installed in the proper orientation.

The IC polarity is indicated on the body of the IC - usually with a notch embossed in one end, though sometimes with a small dimple in one corner. These indications line up with the silkscreen markings on the PCB, which are rectangles with a small half-moon cut out of one end, and a nearby dot. Line the notch on the IC up with the half-moon in the silkscreen, as you can see below.

IC Polarity

Align The Notch On The Chip With The notch In The Silkscreen

Inserting ICs into the board should be fairly straightforward. Sometimes the legs in the ICs have been bent such that they don’t fit right in. If so, carefully straighten them to match the holes.

To solder an IC down, it can help to quickly solder down legs on opposite corners, which helps hold the chip in place while you solder the remaining legs. Take care that you don’t overheat the chip, or create solder bridges between adjacent legs. It can help to work in a zig-zag pattern, back and forth between the rows of legs.


7555

The first chip to go on is the 7555 timer. There are several similarly sized chips in the kit, so take care to read the markings on the ICs.

The 7555 is located here:

7555 location

7555 IC Location


CD4013BE

Now that we’ve warmed up with a small IC, we’ll move on the the larger ones.

Find the CD4013BE dual flip-flop, and install it here:

CD4013BE location

CD4013BE IC Location


CD4017BE

Next is the CD4017BE decade counter.

CD4017BE location

CD4017BE IC Location


LM358

Rounding out the ICs are the three LM358 dual operational amplifiers. They are located towards the top left corner of the board, as shown here:

LM358 Locations

LM358 IC Location


Semiconductors

After the ICs are down, we move on to the other semiconductors.

Transistors

There are ten transistors, all 2n3904’s. They each have three legs, and a cylindrical body with a flat on one side.

The transistors are installed across the top-right edge of the board.

Transistors

Transistor Location

Align the transistors by matching the flat side of the body with the flat of the silkscreen mark. You may need to bend the leads apart a bit so they fit into the board.


LEDs

The eleven LEDs are located as follows:

LED Locations

LED Location

The LEDs are also polarized. The polarity is indicated two ways on each LED - the positive leg (the anode) is longer than the negative leg (the cathode). There is also a small flat spot in the base of the LED to denote the negative lead. Both of these are indicated in the PCB silkscreen. As you can see below, the longer lead is going through the hole marked +, which leaves the flattened side aligned with the flat edge in the silkscreen.

LED Polarity


Almost Done

The SparkPunk Sequencer is nearly complete. There are only a few more components to be installed.

Before moving on, check you work against the photo below.

Semiconductors installed

Assembly V - Electromechanical

Controls

Tactile Switch

The first control is the tactile switch, which is located in the lower left corner of the PCB.

Button Location

Tact Switch Location

Unlike regular tact switches, this one has an LED in it, so that it can light up when the sequencer is playing. Therefore, the switch is polarized. There is a small “+” sign embossed in one of the white plastic tabs. This matches up with the “+” on the board, as seen in the photo below.

Tact Switch Polarity

Tact Switch Polarity

The tact switch legs are already formed so that it will lock in place while you solder, but it can take extra effort to get those legs into the PCB holes. Apply gentle pressure until they snap through, and the body of the switch sits squarely on the PCB. Then solder it in place.


Slide switches

There are twelve small single-pole, double-throw (SPDT) slide switches on the SparkPunk Sequencer. The first two are near the top left corner, and the other ten are arrayed across the lower right edge of the board.

Slide Switch Locations

Slide Switch Location


Slide Pots

The ten slide potentiometers are the largest components on the board. They are located in a row across the right side of the PCB.

Slider Locations

Slide Pot Location

If you take a close look, they only fit in the board one way - one end has a single contact, while the other end has two, which matches the hole pattern on the PCB.

Because they are so large, they can be difficult to keep aligned while soldering. A piece of removable tape can help hold them in place while you work. We had blue painter’s tape handy, so we used that.

taped down

Tape a single slider in place, then solder it down. You can work your way across the board, taping each slider down and soldering it in turn.


Pots

The rotary potentiometers are the tallest component, so they mark the end of the components on the top of the board.

They’re not polarized, but they’ll only fit on the board one way.

It takes some care to get them into the board. If the leads or tabs have been bent in transit, they will need to be straightened out to fit the PCB. To insert the pot, start by lining up the smaller electrical legs, then push the two large tabs into the holes. The tabs are a tight fit - gently rocking the pot from side to side can help. When inserted correctly, the posts on the back of the pot will sit flush on the top of the PCB.

When you solder them in, first solder down the large tabs for stability, taking care that the pot stays flat on the board. Then solder the other connections.

There are two rotary pots on the PCB, both 10K linear taper (marked “M-B-10K” on the back). They go as follows:

Rotary Pot Locations


Top Side Completion

We’re reaching the home stretch, but before we move on to the power components, let’s check that all of the parts we’ve covered thus far are in the correct place. Take a few minutes to compare your board to the photo below. Check that no components have been omitted, and that all of the polarized components (diodes, ICs, LEDs, and electrolytic capacitors) are facing the proper direction.

Topside Complete

The reason for checking at this point is that we’re about to mount components to the back of the board, which will make it harder to rework anything you may have missed.


Power

Battery Box

The battery box is mounted on the back of the PCB. It has two contacts that go through the board.

Battery Box and Bolt

Battery Box Location

It is secured with a small nut and bolt. The bolt should be inserted from the inside of the battery compartment, and secured with the nut on the front side of the board.

Battery bolt and nut

Nut and Bolt Detail

Tighten the bolt, then solder the two leads to the front of the PCB.


1000μF Capacitor

Now it’s time for the capacitor we skipped a couple sections ago. It also goes on the back of the PCB. Like the smaller electrolytics, it is polarized, and needs to be oriented correctly, by matching the lead near the “-” sign on the body up with the PCB pad marked “-”, as shown below:

Big Capacitor

1000µF Capacitor Orientation

Like the battery box, the 1000 µF cap is soldered to the front of the board.


Connectors

The last set of components are the connectors, a pair of 5-pin right angle headers, one male, and one female. This is the connection that joins the Sequencer to the SparkPunk Sound Generator. It needs to be aligned correctly so that the two can easily plug together.

To get the proper alignment on the connectors, we will use one connector as a jig to hold the other in place. Plug the connectors together, face-to-face. Then place the connector on the back of the sequencer, and tape it in place, as shown below. As you can see, the male side of the connector is on the Sequencer, leaving the female side for the Sound Generator.

Connector Alignment

Solder the connector to the top of the PCB.

Then remove the female side of of the connector, and solder it onto the Sound Generator. As with the sequencer, it goes on the back of the PCB, soldered to the front. You can use tape to hold it on place while you solder.

5-pin connector

5-pin connector on the Sound Generator


Check Your Work

This marks the end of the soldering portion of this kit. You can verify your progress against the picture below.

Final Waypoint

The only remaining component should be the 9V Battery.

If everything checks out, we are now ready to move on to testing the sequencer.

Testing/Troubleshooting

We will test the sequencer in several progressive stages.

SparkPunk Sequencer

You’ll notice that as the board got assembled, a lot of the text and legends in the silkscreen got covered up by the components. The remaining text explains the function of the nearby controls. We’ll denote those labels using text in boxes like this.

Sequencer Alone

We’ll begin by testing the sequencer by itself.

The first test is a smoke test. Install the battery in the battery compartment. There are a small “+” and “-” embossed in the box that will match the corresponding marks on the battery. The battery should slide into the holder, and be held in place by the tab at the back end. If it doesn’t fit easily, make sure that you’ve got it aligned properly.

Turn on the power switch. The first step LED, above the first slider, should light up solidly (not blinking or flickering).

Feel the ICs - none of them should be warm to the touch.

Press the RUN button. The button should illuminate, the RATE led should start to flash, and the step LEDs should start chasing from left to right.

Turn the TEMPO pot. It should vary the rate of the chasing and flashing - slower when counterclockwise, and faster when clockwise.

Stop playback by pressing the RUN switch again. The button LED should go out, and the chasing and flashing should stop. The LED over the first step should be lit steadily again.

If you have a voltmeter handy, you can use it to test the output port. Set the meter to measure volts DC, in the 1 to 10 V range. Place the black lead on the GND pin, and the red lead on the CV1 pin. While the sequencer is stopped, adjust the slider on the first step. You should see the voltage vary between approximately 7.5 V at the bottom of it’s travel and .7 V at the top.

Checking Output Voltage

If any of these tests are failing, check out the troubleshooting suggestions below.


Integrated System Test

Once the basic tests above indicate that the sequencer is functional in isolation, we’re ready to test it in conjunction with the Sound Generator.

First lets connect everything:

  • Plug the Sound Generator into the Sequencer by joining the 5-pin headers.
  • Put a 9V battery in the sequencer - it will power the Sound Generator.
  • Plug speakers or headphones into the Sound Generator.

Turn on the sequencer. It should power up as it did before.

Verify that the sound generator is set to make audible sounds by pressing its TRIGGER button. The button should light up, and you should be able to hear the sound. If it’s silent, revisit the testing section of the SparkPunk Hookup guide.

Next, set the sequencer controls as follows:

  • Turn on all ten of the step switches, near the 1 to 10 labels across the lower right edge of the board.
  • Pull all of the sliders to the bottom of their travel.
  • Set the LONG/SHORT switch to LONG.
  • Turn the TEMPO control fully counterclockwise.

Press play. The step LEDs should chase, and the RATE LED should blink. You should hear a continuous sound.

While it is playing, set the LONG/SHORT switch to SHORT. The continuous sound should now be broken into shorter bursts that correspond to the illumination of the RATE LED. With the TEMPO control fully counterclockwise, the pulses should be about ¼ second long, repeating every ½ second.

While it continues to play, turn the SLIDE control all the way down, and start adjusting the sliders. You should be able to hear the effect that the sliders have on pitch. When a step is indicated by the step LED, the slider for that step controls the pitch from the sound generator. Eventually, you’ll want to wind up with sliders alternating between all the way up, and all the way down, as shown below.

Slider Test Config

Turn the LONG/SHORT switch back to LONG, and experiment with adjusting the slide time. You should be able to hear the notes gliding from pitch to pitch.

Next, turn the step switches off one by one, and listen as holes of silence open up in the audio output.

Finally, press RUN to stop the playback.

We will describe exactly what these controls are doing in more detail in the next section.


Troubleshooting

The first thing to check is the control settings on both units - if they’re set to generate silence, you won’t hear anything! You can check that the sound generator portion is working by pressing its TRIGGER button. If the sequencer plays, but you aren’t hearing anything, check the volume control, sound generator waveform switches and the sequencer step trigger switches.

If you’re still having trouble with the above tests, you can start troubleshooting by following this checklist.

  • All solder connections should have neat fillets - small cones or domes of solder that smoothly join the component leads to the PCB.
  • Verify battery orientation & freshness.
  • Check that all polarized components are installed correctly. These include:
    • The electrolytic capacitors
    • The diodes
    • The ICs
    • The Battery
  • Verify the volume is turned up
  • Verify that output is connected

If things still aren’t working, try contacting Sparkfun’s friendly technical support team.

Usage

We skimmed through the basic functionality of the sequencer while we were testing - you probably already have a good idea what the controls do. But if you’d like to understand it in more detail, then keep reading.

The Controls

The following picture denotes the controls on the sequencer.

Control Locations

  1. Power Switch - Turns the the sequencer on and off.
  2. Sound Generator interface connector - 5-pin header that connects to the SparkPunk Sound Generator. It provides power, pitch, and trigger signals to the attached SparkPunk.
  3. Long/Short Switch - Determines the length of notes triggered by the sequencer. LONG notes sound for the full length of the step, and SHORT notes are half the step length. We’ll illustrate this in more detail below.
  4. Tempo Knob - Controls the clock, determing the rate at which the sequencer advances from step to step.
  5. Rate LED - Blinks to display the clock rate.
  6. Slide knob - Controls the time it takes for the sequencer to slide from note to note. See the diagram below for a more detailed description.
  7. Run switch - Starts the clock, which in turn causes the sequence to advance between steps. It also contains an LED that lights up while the sequencer is running.
  8. 10 steps - Each step has several controls.
    • Step indicator LED - Denoting the active step of the sequence.
    • Pitch slider - The pitch control voltage is determined by the slider setting on the active step.
    • Trigger switch - When this switch is on, the note for this step will sound, with the length determined the the SHORT/LONG switch. If the trigger is off, this step of the sequence will be silent.

An analog sequencer like this is intended to be a hands-on, interactive musical tool. Having physical controls makes it easy and fun to experiment with compositional ideas.

Sound Generator Interface

The heart of the sequencer is the interface to the Sparkpunk Sound Generator. The sound generator was designed so that it could simply plug into the sequencer.

All of the controls on the Sound Generator still function when connected to the sequencer. The knobs and switches control the sonic parameters, and the trigger switch triggers sounds. At the same time, the sequencer controls the sound generator using two signals, the pitch control voltage and the gate. As the sequence plays, the circuit selects one column of controls at a time, and analog voltages that correspond to the control settings are driven to the output port.

Pitch Control Voltage

The sliders on the sequencer control the pitch of the sound generator. The following diagram illustrates how slider positions are translated to the control voltage output:

Sliders and Voltages

Slider Settings translated to Control Voltage

By comparing the slider positions to the green trace, you can see how they are converted into voltages. Each slider is selected in turn when a rising edge is seen on the clock, the red signal.

Slide

You’ll notice that the control voltage above changes very quickly when a clock pulse is received - the rise and fall segments are nearly vertical, with the result looking like a series of rectangles. By turning the SLIDE control up, we can slow down those transitions, causing the edges to become rounded, as you see here:

Slide Control Effect

Control Voltage With Slide

The red plot is the same control voltage pattern we saw above, and the blue is the result of turning up the SLIDE control. The more slide you add, the longer it takes to transition from one pitch to the next. The result of this is a musical effect known as portamento or glissando, which is commonly used by instruments like the trombone or slide guitar.

The slide is generally more audible in the LONG setting than SHORT. To understand why, let’s take a look at the gate signal.

Gate

In electronic terms, a “gate” or “gating function” is a DC signal that corresponds to the presence of another signal. It can be generated as an output by a circuit (such as the gate output from the Sound Detector), or as an input to a circuit. In electronic music, a gate signal controls whether a tone generator is running.

The switch on each step of the sequencer allows you to control the gate signal when that step is active. When the switch is off, the gate signal is not driven, and the sound generator will be silent. However, when the gate switch is on, there are two possible results, as determined by the SHORT/LONG switch.

Long Gates

Long Gates

When the switch is set to LONG and the step switch is on, the gate for a step lasts the entire step. In the diagram above, the clock is in green at the bottom, and the gate is in blue at the top. If adjacent steps are on, the gate is continuous - a legato articulation, as shown by the long plateau in the gate signal.

short Gates

Short Gates

In contrast, a short gate is only half a step long. Even if adjacent steps are on, there will be a half-clock duration of silence between them. In the diagram above, the step switches are set the same as the previous example, but the length switch is set to SHORT. The long plateau has been chopped into a number of small chunks.

Power Sharing

One final item worth noting: both the Sequencer and Sound Generator have battery holders and power switches. The units have a common power bus that allows either device to power the other. Only one battery needs to be installed, and the power switch on the unit with the battery will switch the pair on and off. The bus uses diode protection to keep the batteries from charging each other if both are present.

Diving Deeper

At this point, we’ve covered the assembly of the SparkPunk Sequencer, and basic usage with the Sound Generator. Like the Sound Generator, the sequencer in intended to be adapted, modified and customized. One of those modifications is both easy and very useful.

A lot of western music built around rhythmic groupings of 4, 6 or 8, so builders might find that the 10-step sequence length is hard to use. Therefore, we’ll cover a quick modification, which allows you to shorten the sequence to fewer steps.

Across the lower right edge of the PCB are pairs of solder pads - simply bridge the pair of pads to cause the sequence to reset when that step is reached.

Last Step Mod

Constraining the sequence to 8 steps

You’ll bridge the pads that are one step beyond what you want as the last step - as shown above, a wire on step nine shortens the sequence to 8 steps. If you don’t want to make a permanent connection, you can install snappable headers, then use jumper shunts to make the sequence length adjustable.

Resources and Going Further

Resources

If you’re interested in parts that complement the SparkPunk Sequencer, take a look at these:

Going Further

  • Raymond Scott is largely recognized as the inventor of the step sequencer, which he called the “circle machine.” You can hear some examples of it in these videos, and learn more about the man and his music at his website.
  • We’ve also got a tutorial for a similar digital device, the Auduino Step Sequencer.
  • Nic Collins' Handmade Electronic Music book is a good introduction to musical circuits, with a number of breadboard projects you can build from scratch.

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

Installing a Bootloader on the MicroView

$
0
0

Installing a Bootloader on the MicroView a learn.sparkfun.com tutorial

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

Introduction

The MicroView. Such a cool concept! An Arduino, with a built-in display, fully enclosed in a beautiful, ergonomic case. Use it to create small video games, wearable electronics, or to simply explore electronics and programming. But as cool as the MicroView is, if you can’t reprogram it, it’s not much more than an annoyingly repetitive demo.

MicroView Product Shot

In August 2014, we (unknowingly at the time) sent out nearly 2000 MicroViews without bootloaders. Void of a bootloader, the MicroView is essentially un-programmable – that exciting Arduino platform becomes a glorified paperweight.

A bootloader is a small piece of firmware, living inside a microcontroller's memory, which can write to the remaining program memory of that microcontroller. Bootloaders usually allow for easier, less expensive means for updating the program memory on a processor. Instead of specialized tools to program the device, more generic, commonly available components can be used.

One of the reasons Arduinos, like the MicroView, are so popular is because they all have a serial bootloader built into them. Instead of using an external piece of specialized hardware – in this case an AVR ISP (in-system programmer)– to program the processor, a more commonly available serial port can be used. In the case of the MicroView, that's the MicroView USB Programmer, which converts the ubiquitously available USB to serial.

If you’ve received a defective unit, first of all: we’re so sorry! We’re shipping replacements as fast as we can build them, you’ll be getting one soon. In the mean time, this is a great opportunity to learn a new skill.

In this tutorial, we’ll walk you through every step involved in loading a bootloader onto the MicroView: disassembling the enclosure, wiring up an assortment of programmers in a variety of ways, programming the bootloader, and testing it out.

Gathering the Tools

Before you get going, there are a few tools you’ll need to gather:

An Opener

A thin, flat, rigid-ish tool is required to separate the MicroView’s shell from the lens covering it. This can be a spudger, hobby knife, or a thin flathead screwdriver (the smallest bit in our Pocket Screwdriver works).


Pocket Screwdriver Set

In stock TOL-12891

What should every hacker have available to them? That's right, a screwdriver (you have to get into those cases somehow). What…

3.95

Hobby Knife

In stock TOL-09200

It's like an Xacto knife, only better. We use these extensively when working with PCBs. These small knives work well for cutt…

1.95

The knife has a lower potential for scratching your MicroView’s shell, but the tip will also probably break on your first pry attempt. Use a more veteran, dulled blade if you can. Or, better yet, sacrifice a blade and break the sharp end of the tip off.

A Programmer

There are a multitude of tools that can perform the task of reprogramming a MicroView over ISP. There are boards built for the task, like the Tiny AVR Programmer, STK500 USB Programmer, or the AVR Pocket Programmer.


Tiny AVR Programmer

In stock PGM-11801

The ATtiny45 and 85 are a couple of really cool little MCUs but did you know you can program them in Arduino? That's right, n…

19.95

STK500 Compatible USB Programmer

In stock PGM-08702

AVR-ISP500 is a fast and reliable USB AVR programmer, and works directly with AVR Studio. It is recognized as a STK500 progra…

47.95

Pocket AVR Programmer

In stock PGM-09825

This new version uses an SMD 5x2 header. This is a simple to use USB AVR programmer. It is low cost, easy to use, works great…

14.95

Even if you don’t have a dedicated AVR programmer, you might have a programmer and not even know it! Most Arduino’s can be programmed to replicate an AVR Programmer. If you have an Arduino Uno, RedBoard, Pro, or, really, any ATmega328P-based Arduino, you’re already good-to-go.


Arduino Pro 328 - 5V/16MHz

In stock DEV-10915

It's blue! It's skinny! It's the Arduino Pro! SparkFun's minimal design approach to Arduino. This is a 5V Arduino running the…

14.95

RedBoard - Programmed with Arduino

In stock 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

In stock DEV-11021

This is the new Arduino Uno R3. In addition to all the features of the previous board, the Uno now uses an ATmega16U2 instead…

24.95

By loading the ArduinoISP sketch onto your Arduino, it’ll transform into a USB AVR programmer. Arduinos programming Arduinos: madness!

Jumper Wires

To connect between your Programmer and the MicroView, you’ll need six, individual male-to-male jumper wires. Most M/M jumpers will do, including the standard or premium sets.


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

Jumper Wires Premium 6" M/M Pack of 10

In stock PRT-08431

This is a SparkFun exclusive! These are 155mm long jumpers with male connectors on both ends. Use these to jumper from any fe…

3.95

Hook-Up Wire - Assortment (Solid Core, 22 AWG)

In stock PRT-11367

An assortment of colored wires: you know it's a beautiful thing. Six different colors of solid core wire in a cardboard dispe…

16.95

You can even use solid-core wire if you’d like.

The Arduino IDE

There are a handful of software tools that can be used to reprogram AVRs. The easiest program, and the one we recommend, is the good ol' Arduino IDE. Arduino has a built-in tool, which allows you to burn a bootloader into any of its many boards, it makes programming a bootloader as easy as two clicks.

Burn bootlaoder in Arduino

(Optional, Recommended) Solder Tools or Thin-Gauge PTH Resistors

The hardest part of this whole process is connecting your programmer to three of the MicroView’s tiny ISP pins. Due to space restrictions they’re broken out to a trio of small, exposed vias.

MV exposed vias

After lifting the cover off your MicroView, you’ll need to connect to those vias labeled “11”, “12”, and “13”.

If you apply enough steady pressure, you can complete those three connections without soldering or connecting anything else. Be warned, though, that it’ll take a few tries to get right; if you’re low on patience, frustration might brew.

If you’d like to avoid soldering to your MicroView, one trick is to plug through-hole, 0Ω (or, at least, very low resistance) resistors into the MicroView’s three ISP vias. The trick is finding resistors with thin enough leads. The 0Ω resistors on our Resistor Kit work perfectly for this task, but watch out, many other resistors – especially those rated for ¼W and above – have too-thick leads.

Instead of jamming resistors into the vias, if you have soldering tools handy, you can make the programming process a lot smoother by temporarily soldering a jumper wire to the test pin – creating a reliable electrical connection between MicroView and programmer. A simple iron, and some solder is all you should need.


Solder Lead Free - 15-gram Tube

In stock TOL-09163

This is your basic tube of unleaded (Pb-free) solder with a 60/40 no clean, water soluble resin core. 0.031" gauge and 15 gra…

3.5

Soldering Iron - 30W (EU, 230VAC)

In stock TOL-11650

This is a very simple fixed temp, quick heating, 30W 230VAC soldering iron. We really enjoy using the more expensive irons, b…

9.95

Soldering Iron - 30W (US, 110V)

In stock TOL-09507

This is a very simple fixed temp, quick heating, 30W 110/120 VAC soldering iron. We really enjoy using the more expensive iro…

9.95

Solder Wick #2 5ft. - Generic

In stock TOL-09327

Solder wick, coffee, and paper towels keep SparkFun running. You can steal someone's diagonal cutters for a minute, but you'd…

2.49

Solder wick might help when you get to disconnecting the wires and cleaning up.

Identifying a Defective MV

Before we trip into the rabbit hole, we should at least make sure your MicroView is actually missing its bootloader. If you haven’t already, follow along with the MicroView Getting Started Guide. That will walk you through driver installation, and plugging in the MicroView.

Testing With Codebender

Our friends at Codebender have written a quick in-browser test to check for faulty MicroViews. If you’re running Chrome or Firefox, and have the Codebender plugin installed, visit the Codebender MicroView Test Page.

Visit the Codebender MicroView Test Page

Scroll down to the bottom, select your MicroView USB Programmer’s port, then click “Start Test.” You should see the yellow, “RX” LED on your USB Programmer begin to blink.

If you get a “Your MicroView seems to be faulty” message, you can probably take it for its word and continue on to the next section. Click “Stop Test” once you’ve determined your MicroView’s fate.

Testing With Arduino

Alternatively, you can try uploading a sketch in the Arduino IDE. Load up any of the examples included with the MicroView Library. Double-check that your Serial Port is set correctly, and the Board is set to “Arduino Uno”. Then click Upload.

During the upload, you should see the yellow “RX” LED on your MicroView USB Programmer blink. If all you see is three quick blinks, that’s an early warning sign that the bootloader is missing. After waiting a few more seconds, an error should be produced in the Arduino IDE’s console. If you get something like this:

Upload error console notification

…or any of these errors:

avrdude: stk500_recv(): programmer is not responding

avrdude: ser_recv(): programmer is not responding

avrdude: stk500_getsync(): not in sync: resp=0x00

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

…your MicroView probably doesn’t have a bootloader. Time for surgery.

(Carefully) Opening the Case

The AVR ISP programming interface requires six pins: VCC, GND, RST, MOSI, MISO, and SCK. VCC (power), GND (ground), and RST (reset) are all broken somewhere along the MicroView’s readily available pair of 8-pin headers. Unfortunately, the three SPI signals are not broken out to the headers, they’re tucked away, inside the enclosure, broken out to three unmasked vias. To expose these pins, you’ll have to remove the Microview’s covering lens and lift the display up.

Grab your spudger, hobby knife or small, flathead screwdriver. And find a flat, steady surface to do the deed.

The opener and the MicroView

If you’re using a sharp-edged hobby knife, you may want to grab a pair of pliers and snap off a small chunk of the tip to get a more blunt, flat edge.

Knife edge snapped blunt

The lens cover is held in place by two securing notches on the left and right sides of the enclosure. Try to expose as much of a gap on one side as you can, by sliding the lens to either the left or right. You may be able to see one of the securing notches.

MV retaining notch

Insert your opener somewhere between that notch and the bottom of the cover. You should be able to push it in about 2mm, before a beveled edge inside the enclosure gets in the way. Be gentle, but try to push in as far as you can to get more leverage.

Inserting the knife

Then pry up the cover by tilting the opener towards the outside of the MicroView.

Prying the top off

Once the edge of the screen has popped off, grab it with your fingers and pull it off.

Cover removed

The exposed pins for MISO, MOSI, and SCK are just under the display. To access them, very carefully pry the OLED up. The OLED is connected to the PCB via a thin, black connector; it’s fragile, take great care not to place any extra stress on it.

Display lifted off PCB

Those three, small unmasked vias, labeled “11”, “12”, and “13”, are what we’re after!

Wiring the Programmer

As evidenced by our list of devices in the “Programmer” part of the “Gathering the Tools” section, there is no shortage of boards that can program a bootloader. In this section we’ll demonstrate how to hook up a few of the most common programming tools.

For each, we’ll have to wire up six signals: VCC, GND, Reset, MOSI, MISO, and SCK. We’ll use the following color coded wires for the six signals:

Signal NameMicroView PinWire Color
VCC5VRed
GNDGNDBlack
ResetRSTOrange
MOSI11Green
MISO12Blue
SCK13Yellow

We will repeat the hookup for each programmer, click below if you want to skip to a particular device:

Connecting to an AVR ISP 2x3 Cable

Before connecting the programmer to your MicroView, you may need to install drivers. If you’re using the AVR Pocket Programmer, follow along with our Pocket AVR Programmer Hookup Guide for guidance.

Most AVR development boards, like the Arduino Uno, break out a 2x3 header specifically geared towards (re)programming via ISP. This header matches up to a standardized 2x3 ISP footprint (or a larger 2x5 variant) with the following pinout:

AVR ISP Pinouts

Those pinouts are a top-view of the connector as it would be on the PCB. If you’re plugging wires into the cable, you need to flip that image over the horizontal. Here’s how those signals are routed on the cable connector:

How to wire the 2x3 connector

Note that the notch in the cable indicates the pin-1 side of the footprint.

Unfortunately, the MicroView PCB wasn’t big enough to fit the whole standardized ISP header, but, once you’ve removed the cover, all of the pins you need are exposed in one way or another.

Plug your six jumper cables straight into the 2x3 connector. Use color-coded wires if you can. Here’s where each ISP pin goes (note the notch, indicating the pin 1 side):

2x3 cable wired

Then skip to the Wiring to the MicroView section to complete the wiring.

Connecting to the Tiny AVR Programmer

The Tiny AVR Programmer is a tool built for programming ATtiny85’s, but it’s more multi-purpose than that! It can program any AVR. If you’re approaching this task with the Tiny AVR Programmer, make sure you’ve read through our Tiny AVR Programmer Hookup Guide– at least through the driver installation section.

The Tiny AVR Programmer doesn’t mate to a standard 2x3 connector, the pins we’ll need are all broken out to both the 8-pin DIP socket and the two 4-pin machine-pin connectors. Here’s what’s what:

Tiny programmer pins labeled

Insert your wires. Color code them if you can.

ATtiny Wired

Then proceed to the Wiring to the MicroView section.

Connecting to an ArduinoISP

Just about any, old Arduino can be turned into an AVR ISP. All you need is the right sketch: ArduinoISP, which is included by default with the Arduino IDE. Open the sketch by going to File>Examples>ArduinoISP.

Open Arduino ISP

Then upload it to your Arduino, which fortunately already has a bootloader!

The ArduinoISP sketch uses Arduino pins 10, 11, 12, and 13 as RST, MOSI, MISO, and SCK, respectively. Use some color-coded jumpers to wire it up, like this:

Arduino wired

Then proceed to the next section, to wire it up to the MicroView.

Wiring the MicroView

You’ve wired up to the programmer, that’s (the easier) half of the wiring. Now to wire up the MicroView. To begin, plug your MicroView into the USB Programmer, then plug the Programmer into a breadboard.

MV plugged into breadboard

The breadboard will be useful as both a wire tie-in point and as a steadying tool.

Power and Reset

The VCC, GND, and RST pins are, fortunately, all broken out on the Microview.

VCC, GND and RST locations

Wiring those to your programmer is as simple as plugging some wires into a breadboard.

RST, VCC and GND wired

This is a good time to think about how you’re going to power the MicroView as it’s being programmed. Some programmers – including the ArduinoISP, Tiny AVR Programmer, and AVR Pocket Programmer – can power the MicroView by themselves. Other programmers (like more official Atmel AVR ISPs) require the MicroView be powered externally. If you need to externally power the MicroView, plug the USB Programmer into your computer. But, if you’re going to power the MicroView from your AVR programmer, leave your MicroView’s USB Programmer unplugged.

Connecting to MOSI, MISO, and SCK (11, 12, and 13)

Now the hard part. We need to connect the three SPI lines as follows:

Programmer PinMicroView Pin
MOSI (D11)11
MISO (D12)12
SCK (D13)13

Having gone through this process more than a few times, here are three possible methods we’ve gotten to work. Click to skip to the respective section:

  • Soldering wires to vias– With soldering tools and a careful hand, you can solder jumper wires directly to the vias. This is the most reliable method, but also requires the most tools – not recommended for a beginning solderer.
  • Inserting 0Ω Resistors– If you have 0Ω “jumper” resistors (like those in our Resistor Kit), and their legs are skinny enough, you can plug them into the MicroView’s vias. This is a relatively reliable, temporary solution.
  • Holding wires in place– Short of any other option, you can try holding all three wires in place, as you burn the bootloader. This method works, but requires some patience and steady hands.

Soldering the Wires

If you have a soldering iron handy, we recommend connecting the jumper wires to the vias with a small dab of solder. If you’re taking a soldering iron to your MV, you may want to lift the entire board out of the enclosure to avoid burning the edges. Press down on the MicroView’s enclosure, using the table to push the header pins up, it’ll take a steady amount of force to unseat the PCB from its retaining clips.

Apply a dab of solder to the vias.

making solder dabs

Then heat the solder dab back up and fuse an end of the jumper wire to it. Repeat that process for each of the three vias.

soldering the wires

After the wire is soldered, take care to not to let it pull on the MicroView too hard. You’ll risk lifting the via and its copper of the board entirely (then you’ll be left to soldering to the ATmega328P’s pins).

Plug those wires into the correct port of your programmer:

alt text

Then skip to the next section.

Connecting via 0Ω Resistors (Or Thin Solid Wires)

If you’re lacking for soldering tools, or just want to avoid altering your MicroView, see if you can grab three 0Ω (or at the very least very small, <50Ω) resistors. Those included in our Resistor Kit work perfectly. You may have to dig around to find a resistor with thin enough terminations, they’ll need to be less than about 0.015" to fit in the MicroView’s vias.

Plug each of the resistors into a different via on the MicroView, then plug the other end of the resistor into a unique row on the breadboard.

making connections with resistors

See, 0Ω resistors aren’t useless!

Then route each of the programmer’s SPI pins to the appropriate row in the breadboard. You may need to just slightly bend the resistor at the point that it hits the via – just enough for it to make an electrical contact.

AVR Pocket programmer and resistor-ed MicroView

We’re teetering on the edge of reliability here, but this option is still worlds better than the next…

“Push-Connecting” the Wires

If you don’t have either soldering tools or low-impedance resistors, you better have dexterity, a steady hand, and patience. You can “poke” each of the three jumper wires into their respective vias, creating just enough of an electrical connection. We really recommend asking a buddy to help you out here, because while one hand is busy holding the wires in place, the other will have to be on your computer mouse, clicking through menus.

Before actually pushing the wires into place, click over to the next page and get fully prepared to program your bootloader. Once your mouse cursor is hovering over “Burn Bootloder” in the Arduino IDE, then you can start fussing with push-connecting your jumper wires.

There are no real tricks to this. Begin by pushing a wire into pin 13. Once that’s steady continue on to pin 12, holding both jumpers between thumb and forefinger. Finally add pin 11.

Holding wires in place

Then quickly start programming! You’ll have to hold them in place for about 30 seconds.

Burning the Bootloader

One of the little-used but most powerful features of the Arduino IDE is its ability to burn a bootloader. We’ll show you how to use that in this section. For more advanced users, we’ll also lay out how the bootloader can be programmed using AVRDUDE from the command line.

Burning the Bootloader in Arduino

Open up Arduino, then go up to Tools>Programmer. Select the programmer that matches what you’re planning on using. For the programmers we’ve discussed in this tutorial, that will either be USBTinyISP or Arduino as ISP.

Tools>Programmer>USBTinyISP or Arduino as ISP

If you’re using an Arduino as the ISP, make sure the Serial Port is set to that Arduino’s port number. If you’ve recently uploaded the ArduinoISP sketch to your Arduino, it’s probably set correctly, but check!

Finally, make sure the board is correctly set. This will determine which bootloader gets programmed onto your MicroView. It should be set to Arduino Uno.

Tools>Board>Arduino Uno

That’s all for the settings. Now, make sure your programmer is correctly connected to your MicroView, and go to Tools>Burn Bootloader, and enjoy the light show.

Tools>Burn Bootloader

The bootloader burn process usually takes around 30 seconds. If your holding the jumper wires in place, hold steady! After the bootloader has been programmed, you should see a surprisingly brief “Done burning bootloader” message above the console.

alt text

If you get an error, like avrdude: initialization failed, rc=-1, there’s either an incorrect or missing connection. Double-check to make sure everything is connected correctly.

If you’ve gotten good news, continue on to the Testing and Closing section. The MicroView screen will be blank – during bootloader upload, the program that was on the MicroView was erased.

Programming via AVRDUDE and Command Line

Behind the scenes, Arduino uses AVRDUDE to communicate with and command your programmer. Instead of using Arduino as a front end, you can invoke AVRDUDE from the command line. You’ll need to have AVRDUDE installed or existing on your computer somewhere (download AVRDUDE here).

You’ll also need the (working) MicroView HEX file, click here to download the MicroView bootloader hex file, “MicroView_combined_8-19-14.hex”. To make the example commands easier, we’ll assume the hex file is in the same location as AVRDUDE.

If you have an AVR Pocket Programmer or Tiny AVR Programmer, a command like this will upload the bootloader to your Arduino.

avrdude -c usbtiny -p atmega328p -U flash:w:MicroView_combined_8-19-14.hex.hex -U lock:w:0x0F:m

If you’re using an Arduino as an ISP, use a command like below. You’ll need to put your Arduino’s COM port # in place of our placeholders (COMN for Windows or /dev/tty.usbmodemNNNN for Mac/Unix):

Windows: avrdude -p atmega328p -c avrisp -P COMN -b 19200 -v -e -U flash:w:MicroView_combined_8-19-14.hex.hex -U lock:w:0x0F:m

Mac: avrdude -p atmega328p -c avrisp -P /dev/tty.usbmodemNNNN -b 19200 -v -e -U flash:w:MicroView_combined_8-19-14.hex.hex -U lock:w:0x0F:m

After sending the command, your terminal will be swamped with writes, reads, and other messages until the entire bootloader has been programmed.

Example command line respons

After AVRDUDE says it’s done, the bootloader should be programmed. As an added bonus, this HEX file includes the MicroView demo – once it’s been programmed the display should light up and start cycling through patterns.

Testing and Closing

We’re just about back to square one. Before closing the MicroView back up, it’d be best to test it out and make sure it’s bootloader-programmable.

Disconnect your AVR programmer from the MicroView, plug the MicroView into your the MicroView USB Programmer (if it wasn’t already), and plug your programmer into the computer.

Then repeat the Arduino programming process from the “Identifying” section. Load up an example from the MicroView library, make sure the Serial Port and Board (“Arduino Uno”) are set correctly in the Arduino IDE, and program away!

Done Uploading!

If you’re greeted with a “Done uploading.” message above the console, you’ve succeeded in reprogramming your MicroView! The MicroView Demo you’ve loaded should also start running. Program it again to make extra sure…

Closing the MicroView

If you soldered to any of the MicroView’s vias, you’ll first need to remove those jumpers from the board. Heat each joint up, and remove the wire one-by-one.

If you removed the MicroView PCB from the enclosure, put it back in. The MicroView PCB is keyed, so it should only go in one way, make sure the pairs of notches on the top and bottom of the board match up to the notches in the enclosure. Don’t press down on the screen, lift it up and push the MicroView PCB into the enclosure. You should hear a snap as it clicks in, under two small clips on each side of the enclosure, which secure the PCB in place.

Next, fold the OLED back on top of the PCB. There are guides in the enclosure to hold the display in place. It should be seated just about flush with the enclosure notches on the sides and top of the display.

Replacing the OLED

Before closing it up, gently wipe off the OLED to remove any fingerprints. You may also need to wipe off the bottom side of the enclosure lens as well.

Finally, close it up! Slot in one edge of the enclosure lens, then press down on the opposite side to snap it in.

Closing the MicroView

No one will ever know the difference!

A disassembled MicroView put back together

Resources & Going Further

Now it’s time for the fun part! Hopefully you’re not already sick of the MicroView before you’ve gotten to play with it.

To get started with the MicroView, we recommend reading through the tutorials on learn.microview.io.

If you have the MicroView Learning Kit, head over to kit.microview.io to get started with the experiments there.

To really take advantage of the MicroView, we recommend familiarizing yourself with the powerful MicroView Arduino Library. With it, you can draw anything from simple shapes – pixels, lines, circles, and squares – to text and bitmaps. This tutorial will help you get started with the Library.


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

Viewing all 1114 articles
Browse latest View live




Latest Images