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

SparkFun USB to serial UART Boards Hookup Guide

$
0
0

SparkFun USB to serial UART Boards Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

SparkFun has a line of USB to serial UART bridge products designed to allow a user to communicate with a serial UART through a common USB port. It is harder to find computers with serial UART ports on them these days, but super common to find serial devices. Many of the official Arduino and clones share a common interface. This interface is essentially the 6 pin Single-In-Line (SIL), 0.1” pitch version of FTDI’s TTL-232R cables.

SmartBasic Hero Pic

The key change from the FTDI cables to our Arduino compatible boards is that we swapped pin 6 from RTS to DTR. This change was required to match Arduino’s method of resetting the ATmega328P using the DTR signal.

FTDI Pinout

Arduino compatible pinout is slightly different from the FTDI cable (pin 6)

Note The signal difference on pin 6 may cause these devices to not be 100% compatible with devices designed for use with the FTDI TTL-232R cables.

Advantages

Having a detachable USB to UART bridge comes with several advantages over boards like the Arduino Uno.

  • Removing the computer interface makes the board smaller.
  • You only need to buy the circuit once and can program many Arduinos.
  • The bridge circuitry draws power (up to 500 mW) that’s not needed in many installed applications. Removing this parasitic drain makes your project more power efficient & your batteries last longer.

Suggested Reading

Before we get started, you might want to review this other tutorial:

Hardware Tour

The interface to this line of boards is simple. One side has a TTL-232R cable compatible 6 pin SIL, 0.1” pitch female header. This side connects to the Arduino (TTL serial UART) board. We often use right angle headers on the Arduino Pro Mini to make connecting a serial bridge trivial. Our boards have silkscreen labels of where the black and green wires of the FTDI TTL-232R cables would be.

Beefy 3 connected to an Arduino Pro Mini

Fritzing diagram showing the connection between a USB to UART bridge and a Pro Mini

6 pin SIL, 0.1” pitch

6 pin SIL, 0.1” pitch header at top of PCBA

The other side has a USB mini-B or USB micro-B jack. A standard USB cable is used to connect this jack to a host computer.

This line of products comes in a few forms. Here is a table comparing the most common options.

NameVoltageCurrent LimitConnector
SparkFun FTDI Basic Breakout - 5V5.0 VN/A1 USB Mini-B
SparkFun FTDI Basic Breakout - 3.3V3.3 V< 50 mAUSB Mini-B
Beefy 3 3.3 V < 600 mA2 USB Micro-B
LilyPad FTDI Basic Breakout - 5V5.0 VN/A1USB Mini-B

Table 1. Comparison of common SparkFun offerings

Warning: These boards are for prototyping ONLY. Unlike commercial devices, power negotiation and suspend mode do not occur, and it is possible to overload the USB host. Exercise caution when connecting a load, and never connect a load that draws too much current.

1. [5V is taken directly from VBUS and is only limited by the USB host controller.]
2. [This 3.3V regulator is powered directly from VBUS and is only limited by the USB host controller.]

Connecting the USB to Serial UART Boards

These bridges have two connections. On one end there is a USB device connection. See table 1 for more details on the exact connector for the specific product. This interface is USB 1.1 / USB 2.0 full-speed compatible. A standard USB A to some sort of B cable is used to connect the bridge to the computer.

The other connection is a 0.1" pitch female header designed to connect to the microcontroller. Many of our products come with a compatible row of plated-through holes. These are designed to have 0.1" male headers soldered in. Some cases will best be served with straight headers, other with right-angle headers. The desired connection varies from design to design as discussed here. Some products come prepopulated with these headers.

FTDI header prepopulated

Prepopulated FTDI header example

Resources and Going Further

Serial Communication

Asynchronous serial communication concepts: packets, signal levels, baud rates, UARTs and more!

How to Install FTDI Drivers

How to install drivers for the FTDI Basic on Windows, Mac OS X, and Linux.

Using the Arduino Pro Mini 3.3V

This tutorial is your guide to all things Arduino Pro Mini. It explains what it is, what it's not, and how to get started using it.

Serial Terminal Basics

This tutorial will show you how to communicate with your serial devices using a variety of terminal emulator applications.

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


PicoBuck Hookup Guide V12

$
0
0

PicoBuck Hookup Guide V12 a learn.sparkfun.com tutorial

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

Introduction

Please note that this tutorial is for the newest version of the PicoBuck, V12. If you have an older version of the PicoBuck, please refer to this tutorial.


Developed in collaboration with Ethan Zonca of protofusion, the PicoBuck is a small-size, triple-output, constant current LED driver. By default, each channel is driven at 330mA; that current can be reduced by either presenting an analog voltage or a PWM signal to the board. Version 12 of the board adds a solderable jumper that can be closed to increase the maximum current to 660mA. It also increased the voltage rating on the various components on the board, allowing the board to be used up to the full 36V rating of the AL8805 part.

PicoBuck

Suggested Reading

Here are some topics you should know before using the PicoBuck. Have a look if you need more information.

PicoBuck Overview

Since the PicoBuck is a constant current driver, the current drawn from the supply will drop as supply voltage rises. At 12V, the PicoBuck drives the three LEDs on our Rebel Triple Play board at 350mA per LED while drawing less than 350mA total from the power supply.

Three signal inputs are provided for dimming control. You can use the PWM signal from an Arduino or your favorite microcontroller to dim each channel individually, or you can tie them all to the same PWM for simultaneous dimming. A separate ground pin (labeled GND) is provided to reference against the controlling module for accuracy. The pin spacing for the two pairs of pins is 0.1", but the two pairs are slightly 0.2" apart, to allow for a 2.54mm pitch screw terminal pair to be used, or for a five-position standard 0.1" header with the middle pin removed. Dimming can be done by an analog voltage (20%-100% of max current by varying voltage from .5V-2.5V) or by PWM (so long as PWM minimum voltage is less than .4V and maximum voltage is more than 2.4V) for a full 0-100% range.

Signal Inputs

Signal Inputs

The power supply pads are sized for 3.5mm screw terminals, as are the output pads. Each output is independent from the other two.

Power Input

Power Input

Output Pads

Output Pads

Note: The PicoBuck cannot be used to drive a common anode or common cathode LED or LED string, and the individual channel +/- pads must not be connected to one another.

A small jumper is provided for each channel to allow you to increase the drive strength from 330mA to 660mA. More information on this can be found below.

Solder Jumpers

Solder Jumpers

Two mounting holes for 4-40 or M3 screws are provided on either side of the board. They are perforated so they can be easily snapped off with a pair of pliers, if a smaller footprint is desired.

Mounting Holes

Mounting Holes

It is possible to increase the maximum current of the PicoBuck board up to 1A per channel; to do so, replace the three current sense resistors with smaller values. To calculate the new value for the resistor, use this formula:

ILED = 0.1 / Rset

Thus, for a 1A current, you’d want a 0.1Ω resistor. Don’t forget to be wary of current ratings. At 1A, the sense resistor will be dissipating 1/10W, so you probably want a resistor of at least 1/8W rating. The package is a standard 0805.

Current Set Resistors

Current Set Resistors

Closing the Current Setting Jumpers

Demonstration of closed jumpers

As you can see from the image above, the solder jumper doesn’t need to be closed particularly neatly. All of the pads in its vicinity are connected to it anyway, so if you glob a little extra solder on, it’s no big deal. Just be careful not to actually short the resistors, as in the rightmost circuit!

Dimming with a Microcontroller

As mentioned earlier, the PicoBuck’s three channels can be individually dimmed by either varying the input voltage of the channel from 0-2.5V or using a PWM signal. The PWM signal from an Arduino board is perfectly suited for this.

Connecting one LED per channel

Here’s a diagram showing how to connect the PicoBuck to an Arduino.

Arduino connection with one LED per channel

Note: Despite using an external supply for the PicoBuck, the grounds of the two boards must be connected! If the power supply is 12V or less, the Arduino can be powered from it as well, but do not attempt to power the PicoBuck from the Arduino!

Also note that each channel must be independently connected to the + and - connections of the LED it is to drive! Do not connect the + or - connections of any two channels together.

More than one LED per channel

Arduino connection with four LEDs per channel

Multiple LEDs can be connected in series, as shown, and the supply voltage should be at least 2-3V higher than the sum of the forward voltages of the LEDs.

Multiple LEDs can be connected per channel; they should be connected in series, as shown above, and the power supply voltage must be at least 1-2V higher that the sum of the forward voltages of the LEDs.

For instance, our blue 3W LEDs have a forward voltage of 3.2V to 3.8V. To be on the safe side, use the highest voltage in the range. If you want to connect four of them, you’d need a power supply of ~17V or greater (3.8V + 3.8V + 3.8V + 3.8V = 15.2V; add 2V of “head room”).

Since 17V is greater than the Arduino can tolerate on its input, we have to provide an external supply for the Arduino as well. This can be the standard 5V USB supply.

It’s perfectly acceptable to mix colors either between channels or on one channel, so long as all of the LEDs can handle the current (330mA or 660mA, depending on the jumper setting). Just make sure that the power supply voltage is high enough to handle the sum voltages of the highest voltage string. There is also no requirement that the three strings of LEDs have the same forward voltage of LEDs across them; you could have one white LED on channel 1, two red LEDs on channel 2, and four green LEDs on channel 3.

Code example

Code for controlling this device is trivial; simply use the analogWrite() function to adjust the brightness via PWM.

Resources and Going Further

Thanks for reading. Below are all the documents and links you’ll need to learn even more about the PicoBuck.

For more LED fun, check out these other SparkFun tutorials:

Touch Potentiometer Hookup Guide

Learn how to use the SparkFun Touch Potentiometer to control lighting, volume or other inputs in your daily life.

How LEDs are Made

We take a tour of a LED manufacturer and learn how PTH 5mm LEDs are made for SparkFun.

FemtoBuck Constant Current LED Driver Hookup Guide V12

The FemtoBuck board is a high-efficiency, single-channel constant-current LED driver.

Button Pad Hookup Guide

An introduction to matrix scanning, using the SparkFun 4x4 Button Pad.

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

LED Cloud-Connected Cloud

$
0
0

LED Cloud-Connected Cloud a learn.sparkfun.com tutorial

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

Introduction

Make a rainbow colored cloud light that you can control from your phone. You can even have it change color based on the weather outside.

Rainbow colored LED Clouds

These are the clouds from episode 3 The Fellowship of the Things, which you can watch below if you haven’t already.

Required Materials:

To follow along with this tutorial, you’ll need the following materials.

Cloud Cloud required electronics materials


Other parts you will need:

Other Cloud Cloud materials

  • long hook-up wire for cloud power (I used stereo wire)
  • Paper lanterns (white)
  • Pillow filling (I used polyfil)
  • Lots of hot glue and a hot glue gun
  • Fishing wire
  • A wooden dowel for support
  • A power source; you will need something that can put out at least 5V and 4A, but for the best results you can get a pricier 6V 8A power source.

alt text

Optional part included: Thing dev board (in the wishlist, but only needed if you want to hook up to your phone and/or weather info)

Suggested Reading:

If any of these subjects sound unfamiliar, considering reading the following tutorials before continuing on.

Physical Cloud Making

We will begin by assembling the clouds.

Start with an open white paper lantern, and glue on pieces of polyfil in small sections until you have covered the whole lantern.

Gluing polyfil onto the paper lantern to make the clouds

Some tricks for making the cloud look cool when it is lit up is to swirl the polyfil before you glue it on or do other fun crazy shapes.

Twisting polyfil into fun shapes

When you have covered it fully (don’t worry about the top and bottom holes right now), you may want to take a flashlight, and check to see what the lantern looks like when lit up. Cover any bare spots you see.

Flashlight lighting up polyfil covered paper lantern

Flashlight lighting up polyfil covered paper lantern.

Repeat this process for as many lanterns as you would like. The more lanterns, the larger your clouds will be. Just keep in mind you’ll need a power supply that can handle all the LEDs in each lantern. Paper lanterns of different sizes can create a cloud that looks more realistic.

The 5m RGB LED strips fill about five lanterns, so if you want to make your cloud larger or have more than one cloud, you are going to want more RGB LED strips and power sources (you can use the same Pro Mini and ESP8266 Thing Dev Board to power multiple clouds and RGB LED strips).

5 polyfil covered paper lanterns

Once you have the all of your lanterns covered in polyfil, you can tie them together with the fishing wire. This was accomplished by picking a lantern that I wanted to be the highest point of the cloud and tying the tops of the other lanterns to the top of the one I chose. This will give you room for the cloud to look like it is “bobbing” and “shifting”, but if you want it to be more secure, you can tie the lanterns more tightly to each other and even tie the bottoms together as well.

Tieing paper lanterns together

All the paper lanterns tied together

Now that your lanterns are tied together, you can secure them to a wooden dowel so that the cloud is easier to transport and hang.

Lanterns tied together to a wooden dowel

At this point, set your cloud up near your workstation so that you can easily install the lights and see what the cloud looks like lit up. Take this opportunity to add or take away polyfil as you see fit.

Electronics Assembly Part 1

This section will cover building the Pro Mini Circuit. We will add the Internet-connected portion in Part 2.

Connect the components as follows:

Fritzing diagram of Pro Mini and LED strip layout

Please note that we are soldering all these components to a solderable breadboard. Feel free to build the circuit on a breadboard first to test everything out.

Click the image for a closer look.

ComponentBreadboard
Buttonj17 (To Pro Mini Pin 3)g15 (GND)
Resistora22 (Pro Mini Pin 6)Bottom - (LED Strip DIN)
Capacitora27 (Pro Mini GND Pin)Bottom + (LED VCC)
Jumper WireTop - (GND)i29 (Pro Mini GND Pin)
Jumper WireTop + i27 (Pro Mini VCC Pin)
Jumper Wireb25 (Pro Mini Pin 3)f15 (button)
Jumper Wiref13 (button)Top - (GND)
Wireb27 (Pro Mini GND Pin)Ground of barrel jack
WireBottom + (LED VCC)VCC of barrel jack
Wirec27 (Pro Mini/LED power GND Pin)Yellow wire on LED strip (LED GND)
WireBottom - (To Pro Mini Pin 6)Green wire on LED strip (DIN)
WireBottom + (LED power VCC)Red wire on LED strip (LED VCC)

* Pins not listed are not used.


Take a button, and cut off two legs that are diagonal to each other so that it doesn’t cause a short circuit.

Cutting legs off of a breadboard push button

Some things to note here is that I have put a 1000 microfarad capacitor between the LED power and ground. This is good practice, and helps distribute the current better, so that you don’t accidentally blow out your first LED. This should be done on any string of wires as a precautionary measure. I have also placed a 330&ohm; resistor between the DIN of the LEDs and the microcontroller. This is another good measure to protect the addressable LEDs.

The Pro Mini will need to be powered separately from the LEDs, and this can be done through the Mini USB port of an FTDI Basic. (If you don’t want it to run off your computer you can get this USB wall charger). You can also solder wires directly to the Pro Mini’s VIN pin.

Pro Mini with headers soldered on

Code Part 1

The following code allows you to run the lights off of the Pro Mini so that you can scroll through the different pre-programmed lighting sequences.

Codebender Examples: For these examples, we're hosting the code on codebender, which not only features code-sharing, but also allows anyone to upload and debug Arduino sketches from within a web browser. Plus, it works on lower-tech machines, like Chromebooks!

There are codebender plugins for Chrome, Chromium, and Firefox. Visit the codebender plugin page for help installing the codebender plugin.

If the codebender embeds don't work for you, we'll also provide a download link to the example code.

Plug in the Pro Mini, choose Pro Mini as your device, select the corresponding COM port, and then press the “Run on Arduino” button.

If the codebender embed doesn’t load for you, you can download the example code from our GitHub repository.

Once you have tested that your code works with your soldering job, you may want to take some hot glue and cover the wires leading to your barrel jack, just to make sure nothing shorts and to create a stronger connection.

alt text

Hot gluing power barrel jack for protection

Electronics Assembly Part 2

This section will cover adding a SparkFun thing to your project so that it can connect to the Internet.

You can keep all the soldering done in part 1, but just add a SparkFun Thing board to allow for use with your phone as well as to pull weather data.

Connect the components as follows:

Fritzing diagram of Pro Mini, SparkFun's ESP8266 Thing Dev Board and WS2812 LED Strip layout

Click the image for a closer look.

ComponentBreadboard
Resistora22 (Pro Mini Pin 6)Bottom - (LED Strip DIN)
Capacitora27 (Pro Mini GND Pin)Bottom + (LED VCC)
Jumper WireTop - (GND)i29 (Pro Mini GND Pin)
Jumper WireTop + (Board VCC)i27 (Pro Mini VCC Pin)
Jumper Wireb25 (Pro Mini Pin 3)f15 (button)
Jumper Wiref13 (button)Top - (GND)
Jumper Wirea20 (Pro Mini Pin 8)j7 (SparkFun Thing Pin TX)
Jumper Wirej10 (SparkFun Thing GND Pin)Top - (GND)
Jumper Wirea2 (SparkFun Thing VIN Pin)Top + (Board VCC)
Wireb27 (Pro Mini GND Pin)Ground of barrel jack
WireBottom + (LED VCC)VCC of barrel jack
Wirec27 (Pro Mini/LED power GND Pin)Yellow wire on LED strip (LED GND)
WireBottom - (To Pro Mini Pin 6)Green wire on LED strip (DIN)
WireBottom + (LED power VCC)Red wire on LED strip (LED VCC)

* Pins not listed are not used.


Again, same notes as part 1: adding a capacitor and resistor, and powering the Pro Mini and Thing from the wall (read part 1 for all the details).

One additional note, for ease of programming both the Pro Mini and the SparkFun Thing board, you may want to solder in female headers where the Thing board will sit and male headers to the Thing board, so that you can easily take it out to program both.

Cloud project with female headers for the SparkFun Thing board to go into

SparkFun ESP8266 Thing Dev Board

Finished layout of connected cloud cloud hardware project

Code Part 2

Since you have two boards with microcontrollers, you will have to program each one separately.

Pro Mini Code:

Remember, put “Arduino Pro or Pro Mini (5V 16 MHz) w/ ATmega328” as your device, select the COM port that it is plugged into your computer on, and hit the “Run on Arduino” button to program.

If the codebender embed doesn’t load for you, you can download the example code from our GitHub repository.

To hook up the Thing board to the Internet, we will be using the Blynk app. To get the code we need to program the Thing board with you will need to download the Blynk app onto your phone.

Once you have the app, create an account (if you don’t have one already), and go to “create new project”. There you can name your project, set your hardware to “ESP8266” and you can email or just copy that authentication token, which we will need to paste in the SparkFun Thing code.

In your project that you just created, you are going to want to put three LED light widgets, three button widgets, a ZERGBA widget, and an LCD widget.

To get these things onto your project board, touch the screen and the left side should show things that you can place. Drag them over to wherever you’d like. Once they are placed on your board, you can click on them to assign them pins. All of ours are going to be assigned to virtual pins in the table below. There is also a step by step photo setup to help you:

ModulePin
Weather ButtonV0
Weather Indicator LEDV1
RGB ButtonV2
RGB Indicator LEDV3
Disco ButtonV4
Disco Indicator LEDV5
ZERGBRAV8
LCD ScreenV9

Blynk app Photo Setup Walkthrough:

alt text

alt text

alt text

(remember to email yourself the Auth Tolken or you can come back to this page after you to get it.)

alt text

alt text

Swipe to the left to get the widget box menu, to pick new modules:

alt text

Once you have selected a module, it will appear on your project board. To attach it to a pin and change its setting, click on it:

alt text

Repeat those steps for all the modules attached to the pins you will need (as seen below):

alt text

alt text

alt text

alt text

alt text

alt text

alt text

After you have created all the LEDs, Buttons, the ZERGBA, and the LCD and assigned them to the correct virtual pins, you can arrange your modules to look like this:

alt text

And now your blynk project is ready!

SparkFun Thing Code:

To program the SparkFun ESP8266 Thing, we have to get a little more complex. Since it is a newer board, it is yet to be supported on Codebender, but they are working on it! We will update this tutorial once such an option is available.

Thus, to program this board you will need to have the Arduino IDE on your computer. You will need a special add on to be able to choose the ESP8266 board, and you can get the instructions for that in this tutorial. You will also need to download the github libraries for Blynk, Adafruit’s Neo-Pixel Libraries, and lastly add the github libraries for this project. If you have never worked with the Arduino IDE or need a refresher on how to install github libraries I would take a look at our tutorials on them:

Once you have done all of that, you can open the Thing code in the cloudcloud project, change the wifi and password to your network, add your Auth token from the Blynk app, and upload it to your SparkFun Thing to your computer. If you want weather for a city other than Niwot (which you probably do) you can change that in the code as well.

When uploading the code, remember to choose “SparkFun ESP8266 Thing” as your board under the Tools tab. Also check that you have the “Upload using: serial”, “CPU frequency: 80 MHz”, and “Upload speed: 115200” chosen under the Tools tab as well. Make sure you Thing board switch is ‘ON’. Then choose the COM port that your Thing board is hooked up to, and press the Upload button.

(*If you are having errors when you try to upload of undefined libraries, make sure that you have added the file states.h to your project. If after that you are still having issues, it might be the version of the Adruino IDE that you are running, we wrote this on version 1.6.5 and recommend running it on that version.)

Once that is finished uploading, unplug the Thing board from your computer, hook it back up to the circuit, power your Pro Mini (that is also powering the Thing board), and your LED strip. Make sure your Thing board switch is turned on, and wait 30-60 secs. Open up your Blynk app, and run the project you created by pressing play in the top right corner. You should be all hooked up and able to control your lights from the app.

Phew, that was a lot of stuff, but we got through it! Now you can power your lights and your Pro Mini (that is also powering the Thing board) and power up your Blynk app and control your clouds!

Installing the Lights in the Clouds

Now that we have the lights up and running, we can place them into the cloud and test out how it looks.

Evenly distribute the lights between all the paper lanterns and look at the light distribution, and adjust accordingly.

Putting WS2812 LED strip inside of paper lanterns

Putting WS2812 LED strip inside of paper lanterns

WS2812 LED Strip inside of paper lantern

After I felt good about the distribution, I tied the LED strip to the top of each paper lantern. Note that the LED strip isn’t very secured in the lantern. The reason for this is that I didn’t see a difference if I secured them or not. Since they will always be hanging in the same way, they aren’t going to shift very much, so just securing a part to the lantern seemed sufficient to me.

Tieing the WS2812 LED Strip to the paper lanterns

After the LED strip was in the cloud, I looked around and filled any bald spots on the lantern with more polyfil that I could now see due to the lights. I also covered any exposed LED strip with polyfil that I rolled to be more dense.

Cloud on with exposed strip

Filling bald spots on paper lanterns

Rolling polyfil

Gluing polyfil to exposed WS2812 LED strips

You can glue the polyfil on while the Cloud is lit to get a better idea of what it looks like.

After you have filled in all the uneven spots of the cloud with polyfil, you can install your cloud where you like and enjoy it’s colorful awesomeness!

Resorces and Going Further

Thanks for reading! Here are the links to all the resources used in this tutorial.

Github Libraries:

Codebender Libraries:

Interested in some more crafty electronics projects? Take a look at some of our other tutorials:

Origami Paper Circuits

A quick tutorial to get you started in the world of light up origami flowers.

LED Butterfly Pop Up Card

Craft an illuminated butterfly pop up card with copper tape, two LEDs, and a battery.

Light Up Pennant with E-Textiles

Show your school spirit, geek pride, or fandom with a light up pennant using the LilyTwinkle or LilyPad Arduino.
New!

Interactive Smart Mirror

Build a smart mirror that displays weather data using the Intel® Edison.

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

MicroSD Breakout With Level Shifter Hookup Guide

$
0
0

MicroSD Breakout With Level Shifter Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The MicroSD Breakout With Level Shifter makes it easy to add mass storage to your project, whether you’re working with a 3.3V system or a 5V system.

Shifting microSD breakout board

Figure 1. Shifting µSD Breakout Board

Required Materials

To follow along with this hookup guide, you will need the following:

Suggested Reading

If any of these subjects sound unfamiliar, considering reading the following tutorials before continuing on.

Hardware Overview

The SparkFun Shifting µSD Breakout is quite similar to the SparkFun microSD Transflash Breakout, but with the additional feature of being 3.0V to 5.0V tolerant for ease of use. No more discrete level shifting is required. That also makes it great for direct use with a single cell LiPo battery or similar.

One thing that makes this product stand out is that it is SPI_FULL_SPEED stable. Some errors were seen in our testing with other products, but none have been caught using this board. We didn’t have NIST do our testing. We can’t rule out the influence of environmental factors or the host processor used, but if we were looking for stability and reliability at high speed, we’d use this board.

If your processor is capable of it, this board supports the use of even the fastest UHS µSD cards. We only tested to 25MHz, but it should be good to two to four times that. Today most Arduino type µControllers are only capable of SPI_HALF_SPEED (6Mbps). Consider this board if you want a little future proofing or have a faster setup. The Arduino SD library is capable of SPI_FULL_SPEED (25Mbps).

The SparkFun Shifting µSD is also a bit unique from its competitors in that it level translates all of its outputs back to the level of the hardware it’s connected to. Other parts make the fairly safe assumption that the inputs on the processor will read 3.3V as a high. This may not always be the case, and isn’t an assumption this board relies on, so you don’t have to bother worrying about it.

Assembly

There are numerous ways to wire up an equivalent circuit to the one used in this guide. That will all depend on the type of Arduino you are using, the availability of a breadboard, or the types of wires you have laying around. The required materials list above assumes you have access to one of the most popular Adrduino form factors and you will wire it directly to the Shifting µSD board with jumper wires. No breadboard required, and only minimal soldering to get a connection to the µSD board.

Here is how you would wire up the Shifting µSD to a RedBoard or Arduino Uno. From the Ardino SPI library: Warning: if the SS pin ever becomes a LOW INPUT then SPI automatically switches to Slave, so the data direction of the SS pin MUST be kept as OUTPUT. This is pin 10, so be careful.

Shifting microSD connected to RedBoard

Shifting µSD board wired to 5V RedBoard

Code Example

The example code for this product is a simple file logger that allows the user to write to a file on the µSD card using the Arduino IDE Serial Monitor (57600 baud). When the board boots you should see the following in the Serial Monitor:

Initializing SD card...Initialization done.
demoFile.txt doesn't exist. Creating.
Opening file: demoFile.txt
Enter text to be written to file. 'EOF' will terminate writing.

The last line of that bock of text is important to note. Your work is written to the µSD card every 20 characters, but to make sure everything is written append EOF to your writing. Doing so writes everything remaining in the buffer to the file and reads back the contents of the file.

EOF

demoFile.txt:
Test line of text.
Bacon ipsum dolor amet beef picanha drumstick alcatra brisket, short ribs sirloiBacon ipsum dolor amet beef picanha drumstick alcatra brisket, short ribs sirloin.

One thing to note is that the UART buffer on the Arduino might limit the number of characters entered on a single line. In one test I noticed that my Arduino only accepted 164 bytes before loosing data, but I’ve seen that vary a bit.

language:c
#include <SPI.h>
#include <SD.h>

File fd;
const uint8_t BUFFER_SIZE = 20;
char fileName[] = "demoFile.txt"; // SD library only supports up to 8.3 names
char buff[BUFFER_SIZE+2] = "";  // Added two to allow a 2 char peek for EOF state
uint8_t index = 0;

const uint8_t chipSelect = 8;
const uint8_t cardDetect = 9;

enum states: uint8_t { NORMAL, E, EO };
uint8_t state = NORMAL;

bool alreadyBegan = false;  // SD.begin() misbehaves if not first call



void setup()
{
  Serial.begin(57600);
  while (!Serial);  // Wait for serial port to connect (ATmega32U4 type PCBAs)

  // Note: To satisfy the AVR SPI gods the SD library takes care of setting
  // SS_PIN as an output. We don't need to.
  pinMode(cardDetect, INPUT);

  initializeCard();
}



void loop()
{
  // Make sure the card is still present
  if (!digitalRead(cardDetect))
  {
    initializeCard();
  }

  if (Serial.available() > 0)
  {
    readByte();

    if (index == BUFFER_SIZE)
    {
      flushBuffer();  // Write full buffer to µSD card
    }
  }
}



// Do everything from detecting card through opening the demo file
void initializeCard(void)
{
...

Troubleshooting

Arduino has troubleshooting tips on their Notes on the Arduino SD Card Library page, including instructions for formatting new cards (if needed) and using the library with other Arduino boards.

Resources and Going Further

Now that you know how to add more storage to your Arduino projects, it’s time to get out there and create something amazing. Need some inspiration? Check out these other SparkFun tutorials.

  • SD cards are a great way to add more storage to Internet of Things projects. You can add a microSD Shield to a WiFly Shield to serve up larger web pages or hold more data. You can also use the CC3000 Shield, which has a microSD card slot built in.
  • Need more power than your Arduino can provide? Check out the Edison, which also has a microSD card Block to add more storage to larger projects.
  • Logging data is a common use for SD cards. Take your logging project to the next level with the Logomatic.

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

Photon Remote Temperature Sensor

$
0
0

Photon Remote Temperature Sensor a learn.sparkfun.com tutorial

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

Introduction

The scientific method allows us to examine the universe and its natural phenomena. Through collection and analysis of data, we discover historical trends to make predictions about future events. One such phenomenon that greatly impacts our daily, and long-term, lives is temperature. This tutorial shows you how to build your own remote temperature sensor that automatically uploads data to the data.sparkfun.com web service. This is a perfect, hands-on project for teaching, or learning, the difference between daily temperature fluctuations and average temperature over time, a particularly crucial distinction when discussing climate change.

This system uses the Particle Photon as the control device, a handy lil' microcontroller that easily connects to WiFi. The Photon reads in temperature data from the SparkFun TMP102 digital temperature sensor, then uploads the data to a web server for remote data acquisition and, if desired, subsequent analysis and plotting.

finished system enclosed

For all you visual learners, check out a video of the project below:

First, A Note About Temperature!

In our macroscopic world, temperature is a seemingly simple concept – we intrinsically understand fundamental differences between hot objects and cold objects. Often we can estimate temperature just by looking at the object; if our stove burner is glowing red, we know that it is likely very hot and we should avoid touching it.

The standard definition of temperature is a measure of the average amount of heat, or thermal energy, of the particles in a substance. Since temperature is an average measurement, typically the size of the sample is irrelevant. For example, a small pot of boiling water will be at the same temperature as a large pot of boiling water (as long as you’re at the same altitude!).

On the microscopic scale, temperature is a fairly complex phenomenon that corresponds to the molecular speed of individual atoms. In other words, temperature is a measure of the kinetic energy of the atoms that make up a particular substance. In general, for a given substance, the solid phase will have the lowest temperature because the atoms are mostly rigid, followed by the liquid phase in which atoms have more kinetic energy, and then the gaseous phase with the most energetic atoms. However, since mass is also a form of energy, less massive molecules need to have more kinetic energy to be at the same temperature as more massive molecules. This is why all three phases can exist at the same average temperature (e.g. gaseous oxygen, liquid water, solid metal).

Want to learn more about temperature? Check out this great resource.

Materials

To follow along with this project at home, you’ll need the following:

Electronics

Here’s a wish list of most of the parts mentioned above for your convenience.

Casing and Installation

  • For electronics: Project box or waterproof tupperwear

    There are tons of options for cases, just be sure it is durable, waterproof, and not made of metal (will block the WiFi signal).

  • Stand for solar panel (e.g. metal post, garden sign, plant holder, tripod, etc.)

    While a stand is somewhat optional, it allows you to point the panel towards the sun and adjust it throughout the year to obtain maximum incident solar radiation. Check out your local thriftstore for inexpensive items to use as a stand. Be sure the stand and attached panel will withstand the elements (including wind). Alternatively, you can attach the solar panel directly to the temperature sensor case.

Tools

Recommended Reading

The goal of this tutorial is to give you enough information to get your remote temperature sensor up and running as quickly as possible, regardless of your background and experience with the components used in this project. As such, this tutorial provides only a brief mention of the underlying hardware and software elements. Check out the guides below for more in-depth information, including the I2C communication protocol used by the TMP102 sensor and the Phant library used by the data.sparkfun.com web service.

Hardware

Software

Build It!

Let’s begin assembling our circuit.

  1. Set up the Particle Photon.

    Go to the Photon set up page and follow the instructions to set up your Photon for WiFi. The Photon LED will slowly pulse (aka breathe) light blue (cyan) when it is successfully connected to WiFi. Run through a practice program to check that the Photon is working as expected. The classic Blink sketch is always a good choice.

    To program the Photon, we used the Particle Build Web IDE (Integrated Development Environment). Visit the Particle website to guide you through this process.

  2. Locate your specific Photon “Device ID” and the “Access Token”. Store in a convenient, and secure, location.

    The device ID can be found in Particle Build by clicking the ‘>’ next to your device name.

    Particle Device ID

    Find your Device ID under the “Devices” tab, by clicking the carrot next to your Photon.

    Your access token can be found under the “Settings” tab.

    Access Token

    Find your access token under the “Settings” tab.
  3. Solder header pins to the SparkFun temperature sensor (TMP102).

    alt text
  4. Solder the DC barrel jack onto the bottom of the Photon Battery Shield.

    SMD barrel jack soldered on bottom
  5. Plug the Photon into the Photon Battery Shield. Be sure that the rounded edges of the Photon line up with the rounded lines on the battery shield. Connect the battery and solar panel to the respective connectors. Check that the Photon powers on and connects to WiFi.

    Charging with USB

    Charging with barrel jack solar panel
  6. Connect the TMP102 temperature sensor to Photon battery shield pins with the breadboard jumper wires (or stranded 22 gauge insulated wire).

    schematic

    The green wire corresponds to the SDA pins, yellow wire to the SCL pins.

    This project only needs four (4) of the six (6) pins on the TMP102: VCC, GND, SDA and SCL. If you want to connect multiple temperature sensors using the I2C lines, you can use the ADDR0 pin to changes the device address for each sensor (See the I2C communication tutorial for help with this).

    Connect TMP102 VCC pin to the Photon 3.3V source and GND to a Photon GND pin. Connect the TMP102 SDA pin to the Photon D0 pin and the SCL pin to the Photon D1 pin.

    You can keep the final system on a breadboard or transfer it to a PCB board.

Program It!

Read in the TMP102 Temperature Sensor

The program provided below is designed to function essentially as-is, with only a few minor changes necessary to get the system up and running. Unless you want to add more sensors, or use different sensors, you do not need to change the program code to read in the TMP102 temperature data. That said, if you are new to electronics, or I2C communication, it is still helpful to understand the basics of how the TMP102 sends data, particularly when debugging.

Quick Overview of TMP102 Data Signal

The TMP102 temperature sensor uses I2C communication, a two-wire serial interface. The two lines are SDA (Data) and SCL (Clock). The corresponding Photon pins are D0 (SDA) and D1 (SCL). The program below uses the default address of 72 (code variable TEMP102_ADDRESS) for the TMP102 sensor.

The TMP102 sensor outputs two bytes in binary (code variable BYTES_TO_READ). The first byte is the most significant byte (MSB), and the second byte is the least significant byte (LSB). The first 12 bits (out of 16) are used to indicate temperature, where one LSB is 0.0625 °C. The program is commented where these operations occur.

Review the TMP102 data sheet for more information.

Set up a Data Host

This system uses the data.sparkfun.com web service to log the TMP102 temperature data. You can remotely access the temperature data using the public URL generated when you create your data stream. To use the program provided in the next section, follow the procedure below to set up a data stream on the data.sparkfun.com server.

  1. Create a data stream on the data.sparkfun.com service by clicking the Create button.

    alt text
  2. Fill in your desired title and description.

  3. For the fields section, input “temp” and “unit”. It is imperative to use these exact field names (all lower case) or the data will not upload unless you change the respective field names in the program.

  4. Save the data stream. This will redirect you to the stream’s key page. Copy all of this information and store in a secure location.

    A quick overview of the keys:

    Public Key– This is a long hash that is used to identify your stream and provide a unique URL. This key is publicly visible, meaning that anyone who visits your stream’s URL will be able to see this hash.

    Private Key– The private key is necessary to post data to the stream. Only you should know this key.

    Delete Key– This key deletes the stream, so normally you’ll want to avoid this key. Only use this key if you need to fix the field names or if you truly want to delete the data stream.

    Fields– In our program, our fields are “temp”, which corresponds to the temperature reading in degrees Celsius, and “unit”, to let us know that our reading is in degrees Celsius. These fields set specific values and create a new log of data.

  5. The timestamp generated is given in the UTC (Universal Time Coordinate) timezone. The easiest way to handle this timezone is to convert it to your local timezone once you’ve downloaded the data.

  6. To monitor the Photon output, use the Particle driver download as described in the“Connecting Your Device” Photon tutorial.

    To view the particle serial monitor, in the command prompt type particle serial monitor. This is extremely helpful for debugging and checking to be sure the Photon is posting data to your host. The program provided in the next section includes print statements that indicate the status of the data acquisition and upload process to help facilitate the setup process. You can also use any of the serial terminals mentioned in our Serial Terminal Baiscs tutorial to view serial data from your Photon.

System Code

What you need to change in the program:

  1. Copy and paste your data stream public key to the array called publicKey[].

    const char publicKey[] = "INSERT_PUBLIC_KEY_HERE";

  2. Copy and paste your data stream private key to the array called privateKey[].

    const char privateKey[] = "INSERT_PRIVATE_KEY_HERE";

What you may want to change in the program:

  1. The posting rate (code variable postingRate) sets how often the temperature data is uploaded to the data stream. The current post rate is ~ 20s (20000 ms). You can set a different value in line 23 of the program, reproduced below. The maximum post rate allowed by the data.sparkfun.com host is about one data point every 10 seconds (100 posts every 15 minutes).

    const unsigned long postingRate = 20000; //post rate to data.sparkfun.com (time in milliseconds)

  2. The temperature unit (currently in °C).

    To upload data in °F, multiply temp (line 47) by 1.8 and add 32, as shown below.

    int temp = (((( MSB << 8) | LSB) >> 4) * 0.0625)*1.8 + 32;

    Be sure to update the output unit from “C” to “F” in line 51:

    postToPhant(temp, 'F');

  3. If you are comfortable with code, feel free to change anything else you want!

Photon Remote Temperature Sensor Program

You can grab the code from below, or you can get the most up to date files from the GitHub repository.

Photon Remote Temp Sensor GitHub Repository


language:c
//This code was written by Ace Levenberg <acelevenberg@gmail.com> and Jennifer Fox <jenfoxbot@gmail.com>
/*
 * ----------------------------------------------------------------------------
 * "THE BEER-WARE LICENSE" (Revision 42):
 * <jenfoxbot@gmail.com> and <acelevenberg@gmail.com> wrote this file.  As long as you retain this notice you
 * can do whatever you want with this stuff. If we meet some day, and you think
 * this stuff is worth it, you can buy me a beer in return.
 * ----------------------------------------------------------------------------
 */


// This #include statement was automatically added by the Particle IDE.
//This library is used to push data to the data.sparkfun.com server.
#include "SparkFunPhant/SparkFunPhant.h"

const char server[] = "data.sparkfun.com"; // Phant destination server
const char publicKey[] = "INSERT_PUBLIC_KEY_HERE"; // Phant public key
const char privateKey[] = "INSERT_PRIVATE_KEY_HERE"; // Phant private key

Phant phant(server, publicKey, privateKey); // Create a Phant object


const unsigned long postingRate = 20000; //Post rate to data.sparkfun.com (time in milliseconds)
unsigned long lastPost = millis();

const int TEMP102_ADDRESS = 72; //Address of TMP102
const int BYTES_TO_READ = 2; //Number of bytes to read in from TMP102 (should always be 2)

void setup() {
    Wire.begin(); //Initialize serial communication library
    Serial.begin(9600);
}

void loop() {
    if (Wire.isEnabled()) //Check if receiving a signal from I2C pins
    {
        if (lastPost + postingRate < millis()) //Wait to post until ~ 20s has lapsed
        {
            Serial.print("Requesting from :");
            Serial.println(TEMP102_ADDRESS);
            Wire.requestFrom(TEMP102_ADDRESS, BYTES_TO_READ);
            if (Wire.available() == BYTES_TO_READ)
            {
                Serial.println("Reading!");
                byte MSB = Wire.read();
                byte LSB = Wire.read();
                int temp = ((( MSB << 8) | LSB) >> 4) * 0.0625; //Remove 4 empty bits from 2nd byte (see datasheet),
                //combine 1st byte and 2nd byte then use conversion factor to get temp in deg. C (see datasheet)
                Serial.print("Temp is :");
                Serial.println(temp);
                postToPhant(temp, 'C'); //Post temperature data and unit (deg C) to your data stream at data.sparkfun.com (See lines 68 and on)
                lastPost = millis();
            }
            else
            {
                Serial.println("Unable to read the temperature"); //Used for debugging TMP102 output
            }
        }
    }
    else
    {
        Serial.println("Wire is not enabled make sure to call Wire.begin()"); //Used for debugging I2C protocol
    }
}

//Thanks Jim Lindblom <jim@sparkfun.com> for the sample code and Phant library.
int postToPhant(int temp, char unit){

    phant.add("temp", temp); //Data stream field name "temp"
    phant.add("unit", unit); //Data stream field name "unit"
    TCPClient client;
    char response[512];
    int i = 0;
    int retVal = 0;

    if (client.connect(server, 80)) // Connect to the server
    {
        // Post message to indicate connect success
        Serial.println("Posting!");

        // phant.post() will return a string formatted as an HTTP POST.
        // It'll include all of the field/data values we added before.
        // Use client.print() to send that string to the server.
        client.print(phant.post());
        delay(1000);
        // Now we'll do some simple checking to see what (if any) response
        // the server gives us.
        while (client.available())
        {
            char c = client.read();
            Serial.print(c);    // Print the response for debugging help.
            if (i < 512)
                response[i++] = c; // Add character to response string
        }
        // Search the response string for "200 OK", if that's found the post
        // succeeded.
        if (strstr(response, "200 OK"))
        {
            Serial.println("Post success!");
            retVal = 1;
        }
        else if (strstr(response, "400 Bad Request"))
        {   // "400 Bad Request" means the Phant POST was formatted incorrectly.
            // This most commonly ocurrs because a field is either missing,
            // duplicated, or misspelled.
            Serial.println("Bad request");
            retVal = -1;
        }
        else
        {
            // Otherwise we got a response we weren't looking for.
            retVal = -2;
        }
    }
    else
    {   // If the connection failed, print a message:
        Serial.println("connection failed");
        retVal = -3;
    }
    client.stop();  // Close the connection to server.
    return retVal;  // Return error (or success) code.
}

Test, Encase and Install

  1. Plug battery and solar panel into Photon battery shield. Check that the Photon successfully powers on, connects to WiFi (the Photon LED will be breathing cyan), and sends temperature data to your data stream (accessible via the public URL).

  2. Coat electrical connections in epoxy or other (ideally waterproof) adhesive.

    Please note that epoxy is very permanent. If you intend to modify the project or use the components for another project in the future, use an adhesive method that is removable, like hot glue.

  3. Place electronics (except solar panel) in project case. Determine where the solar panel cable will enter the case. Use waterproofing electrical tape to seal area around solar panel cable or a drill hole in the case for the solar panel cable (coat exterior in waterproofing tape or epoxy). If you place the temperature sensor inside the case, ensure that there is sufficient air ventilation to avoid turning the project case into a sauna.

    alt text

    Be sure that the wires are not stretched or bent much as this will cause breakage over time.

  4. Seal any remaining holes or other air gaps with waterproofing electrical tape or epoxy. If you are sealing the project case lid, it is highly recommended to use a removable sealant like the waterproofing electrical tape to access the electronics in the future.

    alt text
  5. Connect solar panel to stand.

    alt text

    The stand in this example is a towel rack found at a local thrift store. This was perfect for my needs because 1) it was very inexpensive and 2) the rings are adjustable, which allows me to change the orientation of the solar panel to point it towards the maximum incident solar radiation (aka sunlight) depending on where it is installed outdoors and the current season (since the sun’s path changes depending on the seasons).

    alt text

    There are tons of options for a stand! Peruse your garage/basement/attic/cupboards/closets or check out the outdoor section of a local thrift store or hardware store. Look for objects that can withstand nature’s elements, will maintain ridigity, and can support the solar panel weight.

  6. Once the case and stand are complete, connect the battery and solar panel to the Photon battery shield. Check that the Photon is adequately powered, connected to WiFi (pulsing light blue), and is uploading data to your data.sparkfun.com data stream.

    alt text

    The battery used in this tutorial has a capacity of 6Ah (Amp-hours), which means it can provide 6A for 1 hour. The Photon microcontroller average power consumption is between 80 - 100 mA. Assuming maximum current draw of 0.1A, this means that the battery can power the system for ~60 hours (2.5 days) without any charge from the solar panel. This is ideal/necessary for cloudy locations (like Seattle where this project was designed and built) or for remote sites that are difficult to access on a daily basis.

    If you use a different battery, calculate the total number of hours the battery can power the Photon, without being charged by the solar panel. Do this by dividing the battery capacity (given in Amp-hours) by the Photon maximum current draw (0.1A). Since the sun hides behind the other side of the planet at night, be sure that your battery can provide power for at least 10-12 hours.

  7. Install the system within reach of the WiFi signal for which it is configured – the Photon will flash green if it is not connected to WiFi.

    Be sure to place the temperature sensor in a shady location, avoiding direct sunlight, as incident solar radiation will increase the temperature measurement.

  8. Place the solar panel in the sunniest spot available at your chosen location. Determine the optimum solar angle for your panel, and point the solar panel in that direction. You’ll want to change this angle over the course of the year as the sun’s angle changes (higher in the summer, lower in the winter, also highly dependent on location). Here’s a great online calculator to help you determine the optimal solar angle in your particular city.

    alt text

Data Acquisition and Analysis

The data.sparkfun.com service allows you to download your data in a few different formats, so pick the format that is easiest for you to handle. Most common data analysis programs, including Excel, R, and Python, can handle CSV (Comma Separated Values) files.

Below is one method to plot your data using a program written for the R platform, a free statistical software environment.

  1. Download your data in CSV file format (button is located at the top of the data stream).

    alt text
  2. In the R workspace, run the program below to generate a plot and basic analysis of your data. You can also get the most up to date files from the GitHub repository.

Photon Remote Temp Sensor GitHub Repository


#Photon Remote Temperature Sensor Data Plot and Analysis
#Code written by Jennifer Fox 


tempPlot = function(file = ''){
    default = "C:\\test\\*.txt"

    #Load in CSV text file
    if (file == '') file = file.choose()

    #Set data into matrix
    headers = c("Temp_C", "Unit_C", "Timestamp")
    temp_raw = read.table(file, sep = ",", quote = "", skip = 1, fill = TRUE, col.names = headers)

    #Add in degrees Fahrenheit
    tempF = matrix(nrow = length(temp_raw[,1]), ncol = 2, byrow = TRUE)
    tempF[,1] = temp_raw[,1]*1.8+32
    tempF[,2] = "F"
    temp_raw[,c("Temp_F","Unit_F")] = c(as.numeric(tempF[1:length(tempF[,1]),1]), tempF[,2])
    temp = temp_raw[,c(1,2,4,5,3)]

    #Convert UTC timestamp into local (sensor) timezone
    timestamp_raw = temp$Timestamp
    ts_placeholder = gsub("T", "", timestamp_raw)
    timestamp = gsub("Z", "", ts_placeholder)
    UTC_timezone = as.POSIXct(timestamp, tz="UTC")
    my_timezone = format(UTC_timezone, tz = Sys.timezone()) #Sys.timezone() outputs the local timezone

    #Replace temp data with local timezone
    temp$Timestamp = my_timezone

    #Plot temperature data
    plot(as.POSIXct(temp$Timestamp), temp$Temp_C, main = "Temperature (°C) vs. Time", ylab = "Temperature (°C)", xlab = "Time", xaxt = "n", pch = 20)
    axis.POSIXct(1, my_timezone, labels = TRUE) #Use the "format" argument to adjust the axis label (e.g. to print hours use: format = "%H:00" )
    dev.new()
    plot(temp$Timestamp, temp$Temp_F, main = "Temperature (°F) vs. Time", ylab = "Temperature (°F)", xlab = "Time", xaxt = "n", pch = 20)
    axis.POSIXct(1, my_timezone, labels = TRUE)

    #Calculate and output basic statistical analysis
    end_date = temp$Timestamp[1]
    start_date = temp$Timestamp[length(temp$Timestamp)]
    t_F = summary(as.numeric(temp$Temp_F))
    t_C = summary(as.numeric(temp$Temp_C))

    cat("Data Stream Start Date:", as.character(start_date), "\n", "Data Stream End Date:", as.character(end_date), "\n\n")
    cat("Summary of Temperature Data (°C)", "\n", "Average (Mean) Temperature: ", t_C["Mean"] ,"\n", "Minimum Temp: ", t_C["Min."], "\n", "Maximum Temp: ", t_C["Max."], "\n")
    cat("Summary of Temperature Data (°F)", "\n", "Average (Mean) Temp: ", t_F["Mean"] ,"\n", "Minimum Temp: ", t_F["Min."], "\n", "Maximum Temp: ", t_F["Max."], "\n")
}

The following shows the plots from the set of data collected during this project.

alt text

Click image for a closer look.

Education Extension

Building this remote temperature sensor teaches practical, hands-on skills in hardware and software engineering. Beyond direct project-based learning, there are tons of ways to extend this project for classroom and other citizen science activities. Here are a few ways to use this system to teach fundamental scientific concepts.

What is Temperature?

This system measures temperature at a very specific, and known, location, which allows us to combine our direct observations with experimental data. Create your own experiment to change the temperature reading by changing the outside environment, keeping everything else the same.

For example, move the temperature sensor into direct sunlight, and gather data over a specific time interval, then move the temperature sensor back into the shade for the same amount of time. Analyze how the temperature reading changes and compare it to your own observations of outside temperature. Experiment with different ways to change the temperature reading. Be creative*, and see what tests your students think up!

* Avoid water contact unless you’ve thoroughly coated the electrical connections in epoxy or other waterproof adhesive.

Heat Capacity: Comparison of Temperature and Heat

Build the temperature sensor case to be air-tight, then use different material types and/or sizes of enclosures to analyze the difference between temperature and heat. Different materials have different heat capacities, or the amount of heat needed to raise the material’s temperature by one degree. In other words, materials absorb and retain heat at varying rates. This helps us understand that heat is a form of energy, while temperature is a measure of that energy.

For each case, place sensor in direct sunlight and leave overnight. Determine how quickly the temperature sensor reading increases and decreases. A high heat capacity material will slowly increase and decrease in temperature, whereas a low heat capacity material will quickly heat up and cool off. Create plots of the temperature changes for various cases to determine what types of materials, and what sizes, retain heat the most. Find patterns between different material types and use those patterns to determine why certain materials have higher heat capacities.

Analysis of Data Trends: Long-Term vs. Short-Term

The difference between daily temperature and average temperature is a crucial concept in understanding climate change. It also provides a real-world application of the difference between long- and short-term trends. Fortunately, the data.sparkfun.com service makes this analysis simple and straightforward, the hardest part is waiting! It is also suggested to have a back-up battery if you live in a cloudy climate (like Seattle).

For this science lesson, gather data for a minimum of two (2) to three (3) months, ideally through a seasonal change. Download the data and find the average (mean) temperature by day, week, and month. Select a few 24-hour periods to plot temperature, and compare daily fluctuations with your calculated averages. See if you can use the temperature data to pinpoint the changing seasons!

Resources and Going Further

Looking for more weather fun? Check out these other SparkFun tutorials:

HTU21D Humidity Sensor Hookup Guide

The HTU21D humidity sensor is an easy to use, digital, low-cost humidity sensor.

MPL3115A2 Pressure Sensor Hookup Guide

Getting started with this amazing barometric pressure sensor.

SparkFun BME280 Breakout Hookup Guide

A guide for connecting the BEM280 sensor to a microcontroller, and for using the Sparkfun Arduino library.

Photon Weather Shield Hookup Guide

Create Internet-connected weather projects with the SparkFun Weather Shield for the Photon.

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

Bus Pirate v3.6a Hookup Guide

$
0
0

Bus Pirate v3.6a Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The Bus Pirate is an electronics prototyping dream. It’s packed with many of the tools needed when getting a project up and running. The Bus Pirate can perform a variety of test equipment functions such as measuring voltage and frequency as well as generating PWM signals.

bus pirate

Most of the functionality of the Bus Pirate revolves around serial protocols. The Bus Pirate can communicate on 1-wire, 2-wire, 3-wire, UART, I2C, SPI, and HD44780 LCD protocols. It also has a bitbang mode for other or custom options.

This guide is intended to be a quick overview and cover a few things not explicitly covered in the Bus Pirate documentation provided by Dangerous Prototypes.

Suggested Reading

The following concepts will be mentioned in this guide. If you are unfamiliar with any of them, check out the corresponding tutorial.

Board Overview

Bus Pirate with labeled ports

Bus Pirate Ports

The Bus Pirate has 3 ports. This first is the ICSP port for directly programming the PIC microcontroller at the heart of this product. Since there is a bootloader and a reflashing utility, you shouldn’t ever have to use this port.

The second port is a mini-B USB jack. Connect this to a computer with a standard A to mini-B cable. This provides the power to the board and allows you to communicate with Bus Pirate.

The third port is the most interesting. It’s a shrouded 0.1" pitch 2x5 pin header. We sell a handy cable to connect the Bus Pirate to the system you are developing, debugging, or reverse engineering. Here is a graphic that shows maps the IO functions to the colors of the cable.

Pinout

Pin header image based on Dangerous Prototypes (CC BY-SA)

The following table describes in a little more detail the purpose of each pin. It’s sorted in the same order as the conductors on the cable. The power supplies can be switched on or off in software, and each can supply up to 150mA to power your project.

Bus Pirate - IO Pins
Pin Name Description (Bus Pirate is the master)
GND Ground, connect to ground of test circuit
+3.3V +3.3 volt switchable power supply
+5.0V +5 volt switchable power supply
ADC Voltage measurement probe (max 6V)
VPU Voltage input for on-board pull-up resistors (0V to 5V).
AUX Auxiliary IO, frequency probe, pulse-width modulator
CLK Clock signal (I2C, SPI, JTAG, KB)
MOSI Master data out, slave in (SPI, JTAG), Serial data (1-Wire, I2C, KB), TX (UART)
CS Chip select (SPI), TMS (JTAG)
MISO Master data in, slave out (SPI, JTAG) RX (UART)

Using the Bus Pirate

The Bus Pirate has two interface modes, binary scripting mode, and user terminal mode.

Binary Scripting Mode

Binary scripting mode allows applications and/or scripts to control the Bus Pirate. This interface could be used to write a GUI, automated testing, etc. It’s more work to get up and running, but it is more powerful. The following code block is a minimal Python script that can serve as a starting place to use the binary access mode on most platforms. It puts the Bus Pirate into binary mode, sends a command, and then prints out a response. It doesn’t actually ‘do anything’ beyond that though; it’s only a framework.

On my Mac I run a command like: ./binaryModeDemo.py -p /dev/tty.usbserial-AL00ESEJ. The default baud rate for the Bus Pirate is 115200. For help, run python binaryModeDemo.py --help. It should run on any platform running a Python interpreter. Some tweaks might be necessary if running a non-2.7 version of Python.

language:python
#!/usr/bin/env python
# encoding: utf-8"""
Example code to interface the Bus Pirate in binary mode
Brent Wilkins 2015

This code requires pyserial:
    $ sudo pip install pyserial
or:
    $ sudo easy_install -U pyserial
"""
import sys
import serial
import argparse

commands = {
        'BBIO1': '\x00',    # Enter reset binary mode
        'SPI1':  '\x01',    # Enter binary SPI mode
        'I2C1':  '\x02',    # Enter binary I2C mode
        'ART1':  '\x03',    # Enter binary UART mode
        '1W01':  '\x04',    # Enter binary 1-Wire mode
        'RAW1':  '\x05',    # Enter binary raw-wire mode
        'RESET': '\x0F',    # Reset Bus Pirate
        'STEST': '\x10',    # Bus Pirate self-tests
}

def arg_auto_int(x):
    return int(x, 0)

class FatalError(RuntimeError):
    def __init__(self, message):
        RuntimeError.__init__(self, message)

def main():
    parser = argparse.ArgumentParser(description = 'Bus Pirate binary interface demo', prog = 'binaryModeDemo')

    parser.add_argument(
            '--port', '-p',
            help = 'Serial port device',
            default = '/dev/ttyUSB0')

    parser.add_argument(
            '--baud', '-b',
            help = 'Serial port baud rate',
            type = arg_auto_int,
            default = 115200)

    args = parser.parse_args()

    print '\nTrying port: ', args.port, ' at baudrate: ', args.baud

    try:
        port = serial.Serial(args.port, args.baud, timeout=0.1)
    except Exception as e:
        print 'I/O error({0}): {1}'.format(e.errno, e.strerror)
        print 'Port cannot be opened'
    else:
        print 'Ready!'
        print 'Entering binary mode...\n'

        count = 0
        done = False
        while count < 20 and not done:
            count += 1
            port.write(commands.get('BBIO1'))
            got = port.read(5)  # Read up to 5 bytes
            if got == 'BBIO1':
                done = True
        if not done:
            port.close()
            raise FatalError('Buspirate failed to enter binary mode')

        # Now that the Buspirate is in binary mode, choose a BP mode
        port.write(commands.get('RESET'))
        while True:
            got = port.readline()
            if not got:
                break
            print(got),

        """
        port.write(commands.get('SPI1'))
        got = port.read(4)
        if got == 'SPI1':
            print 'Entered binary SPI mode'
        else:
            raise FatalError('Buspirate failed to enter new mode')"""

        port.close()


if __name__ == '__main__':
    try:
        main()
    except FatalError as e:
        print '\nA fatal error occurred: %s' % e
        sys.exit(2)

User Terminal Mode

Terminal mode is likely the interface of choice for most users, at least to start. It provides an interactive menu system for configuring the Bus Pirate. All one needs to use it is a terminal emulator.

The first thing to note is how to get help or list all of the commands. At the prompt enter ?.

Help:

HiZ>?
General                                 Protocol interaction
---------------------------------------------------------------------------
?       This help                       (0)     List current macros
=X/|X   Converts X/reverse X            (x)     Macro x
~       Selftest                        [       Start
#       Reset                           ]       Stop
$       Jump to bootloader              {       Start with read&/%     Delay 1 us/ms                   }       Stop
a/A/@   AUXPIN (low/HI/READ)            "abc"   Send string
b       Set baudrate                    123
c/C     AUX assignment (aux/CS)         0x123
d/D     Measure ADC (once/CONT.)        0b110   Send value
f       Measure frequency               r       Read
g/S     Generate PWM/Servo              /       CLK hi
h       Commandhistory                  \       CLK lo
i       Versioninfo/statusinfo          ^       CLK tick
l/L     Bitorder (msb/LSB)              -       DAT hi
m       Change mode                     _       DAT lo
o       Set output type                 .       DAT read
p/P     Pullup resistors (off/ON)       !       Bit read
s       Script engine                   :       Repeat e.g. r:10
v       Show volts/states               .       Bits to read/write e.g. 0x55.2
w/W     PSU (off/ON)            <x>/<x= >/<0>   Usermacro x/assign x/list all
HiZ>

Example

Here is a quick example of reading a register from a device on the I2C bus. I had an LSM303C Breakout laying on my desk, so I’ll use it. Any I2C device will work a similar way. Here is a picture of all of the connections required to get the breakout board powered an communicating. This board runs on 3.3V, so we will power it with the red wire.

Note: By default VDD & VDD_IO on the LSM303C breakout are connected and either could have been used to power the board.

Bus Pirate fritzing example

Fritzing diagram of Bus Pirate connected to LSM303C

Bus Pirate cable to LSM303C connection

Bus Pirate cable attached to the LSM303C Breakout

On Mac or Linux, I typically run picocom. You can use about any terminal emulator you like. I connect with a command such as picocom -b115200 /dev/tty.usbserial-AL00ESEO. The default baudrate of the Bus Pirate is 115200 baud, and the hardware I have in hand shows up at /dev/tty.usbserial-AL00ESEO. The first step is to select the correct mode. We say above from the help that m is the ‘Change mode’ command. This will show the 9 mode options.

HiZ>m
1. HiZ
2. 1-WIRE
3. UART
4. I2C
5. SPI
6. 2WIRE
7. 3WIRE
8. LCD
9. DIO
x. exit(without change)

We want I2C, so we will enter 4:

(1)>4
Set speed:
 1. ~5KHz
 2. ~50KHz
 3. ~100KHz
 4. ~400KHz

Let’s select 400KHz mode, because we can, so why not?

(1)>4
Ready

To power the board we need to enable the power regulators with ‘W’ (‘w’ will disable):

I2C>W
Power supplies ON

At this point you might also want to enable pull-up resistors. To do so you need to connect the VPU pin to the correct voltage supply. Then ‘P’ will connect the resistors. The LSM303C Breakout already has pull-up resistors, so we can skip this step. We are ready to start communicating with the IC.

Let’s take a look at the LSM303C datasheet to see what it expects to see on the I2C bus:

alt text

It looks like as the master we need to send a start condition then a slave address with the read/write bit clear for a write. The LSM303C should then acknowledge receipt (ACK). Next we need to send the address of the register or interest. The slave/LSM303C should ACK. Next we need to send a repeated start condition (same thing as a normal start condition), followed by the slave address with the r/w bit set to do a read. The LSM303C should respond, and we as the master don’t acknowledge. The sequence ends with a stop condition.

Looks like we need more details such as the addresses. The LSM303C datasheet gives the 7-bit slave address to be 0011101b (0x1D) for the accelerometer and 0011110b (0x1E) for the magnetometer.

I2C Slave Addresses

I2C Slave Addresses

To use these addresses we need to append the read/write bit to the end. In our case if we want to read from the accelerometer we need to shift 0b0011101 left once and or that with 0x01 to indicate a read. The shift yields 0b0111010 and OR-ing that result with 1 results in 0b0111011 (0x3B). If we had OR-ed with 0x00 for a write we would have got 0b0111010 (0x3A) for the write address. Let’s use a Bus Pirate macro to see if those addresses exist on the bus:

I2C>(1)
Searching I2C address space. Found devices at:
0x3A(0x1D W) 0x3B(0x1D R) 0x3C(0x1E W) 0x3D(0x1E R)

Sure enough, we can see a write address at 0x3A, and a read address at 0x3B! Now we need to know the address of a register to read from. The WHO_AM_I_A (0x0F) register always contains 0x41, so that makes an easy read to verify.

who am i register

Who Am I Register Details

Let’s put all of those addresses into Bus Pirate syntax and in the format that the LSM303C will respond to. Start condition [, write address 0x3A, register address 0x0F, repeated start condition [, read address with read command 0x3B r, and end it all with a stop condition ]. Here is how the Bus Pirate responds to that input:

I2C>[0x3a 0x0f [0x3b r]
I2C START BIT
WRITE: 0x3A ACK
WRITE: 0x0F ACK
I2C START BIT
WRITE: 0x3B ACK
READ: 0x41
NACK
I2C STOP BIT
I2C>

The Bus Pirate read 0x41, which is what that register is supposed to contain!

Other Commands

There are a lot of other commands available via the user terminal mode. Here is a quick reference to them and how they respond.

Convert base of one byte (=X)

DIO>=0x7E
0x7E = 126 = 0b01111110

Reverse one byte (|X)

DIO>|0b100110
0x64 = 100 = 0b01100100

Self-test (~) - Runs in HiZ mode only

HiZ>~
Disconnect any devices
Connect (Vpu to +5V) and (ADC to +3.3V)
Space to continue
Ctrl
AUX OK
MODE LED OK
PULLUP H OK
PULLUP L OK
VREG OK
ADC and supply
5V(5.01) OK
VPU(5.00) OK
3.3V(3.35) OK
ADC(3.43) OK
Bus high
MOSI OK
CLK OK
MISO OK
CS OK
Bus Hi-Z 0
MOSI OK
CLK OK
MISO OK
CS OK
Bus Hi-Z 1
MOSI OK
CLK OK
MISO OK
CS OK
MODE and VREG LEDs should be on!
Any key to exit
Found 0 errors.

Reset (#)

HiZ>#
RESET

Bus Pirate v3a
Firmware v5.10 (r559)  Bootloader v4.4
DEVID:0x0447 REVID:0x3046 (24FJ64GA002 B8)
http://dangerousprototypes.com

Jump to bootloader ($)

HiZ>$
Are you sure? y
BOOTLOADER

Delay (&/%)

HiZ>&
DELAY 1us
HiZ>%
DELAY 1ms

Auxiliary Pin (a/A/@)

DIO>a
AUX LOW
DIO>A
AUX HIGH
DIO>@
AUX INPUT/HI-Z, READ: 1

Set baudrate (b)

HiZ>b
Set serial port speed: (bps)
 1. 300
 2. 1200
 3. 2400
 4. 4800
 5. 9600
 6. 19200
 7. 38400
 8. 57600
 9. 115200
10. BRG raw value

(9)>9
Adjust your terminal
Space to continue

Auxiliary assignment (c/C)

HiZ>c
a/A/@ controls AUX pin
HiZ>C
a/A/@ controls CS pin

Measure ADC (d/D)

once:

1-WIRE>d
VOLTAGE PROBE: 3.33V

continuous:

DIO>D
VOLTMETER MODE
Any key to exit
VOLTAGE PROBE: 0.00V

g - 3.3V PWM on auxpin (blue wire)

DIO>g
PWM disabled
DIO>g
1KHz-4,000KHz PWM
Frequency in KHz
(50)>
Duty cycle in %
(50)>
PWM active

HiZ>=0x1010
0x10 = 16 = 0b00010000

HiZ>o
 1. HEX
 2. DEC
 3. BIN
 4. RAW

Modes:

HiZ>m
1. HiZ
2. 1-WIRE
3. UART
4. I2C
5. SPI
6. 2WIRE
7. 3WIRE
8. LCD
9. DIO
x. exit(without change)

(1)>

Resources and Going Further

Now that you have had a brief overview of the Bus Pirate, take a look at the official documentation and the Dangerous Prototypes SVN repository.

Serial Communication

Asynchronous serial communication concepts: packets, signal levels, baud rates, UARTs and more!

Serial Peripheral Interface (SPI)

SPI is commonly used to connect microcontrollers to peripherals such as sensors, shift registers, and SD cards.

I2C

An introduction to I2C, one of the main embedded communications protocols in use today.

Serial Terminal Basics

This tutorial will show you how to communicate with your serial devices using a variety of terminal emulator applications.

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

SparkFun LED Array (8x7) Hookup Guide

$
0
0

SparkFun LED Array (8x7) Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The LED Array (8x7) is a set of 56 LEDs arranged in a nice 8x7 grid. It relies on Charlieplexing to control individual LEDs, which means less GPIO pins are used (as opposed to a traditional grid format). This guide will walk you through connecting the LED array and using some code examples to make those LEDs light up. We even wrote a library to help you display some simple graphics and scrolling text!

IMPORTANT: For the time being, the library for this board only supports ATmega 168 and 328-based Arduinos (e.g. UNO, RedBoard, Pro, Pro Mini, etc.). You can still use the LED Array board with other platforms, just not the library.

Charlieplexed 8x7 LED Array

Required Materials

To follow along with this guide, you will need the following additional parts:

Suggested Reading

If any of these subjects sound unfamiliar, considering reading the following tutorials before continuing on.

Board Overview

How Charlieplexing Works

To understand how the LED Array (8x7) works, we need to first learn a little about Charlieplexing. The name came from Charlie Allen at Maxim Integrated, who proposed the solution in 1995 for controlling multiple LEDs with less pins from a microcontroller.

The technique relies on using the ability for microcontroller pins to enter into a high impedance state (tri-state) and thus prevent current from entering or leaving that pin. Let’s take a 3-pin example. With Charlieplexing, we can have 6 LEDs attached to 3 pins: n x (n - 1) = 3 x (3 - 1) = 6.

Charlieplexing 6 LEDs

We need to use the microcontroller’s ability to tri-state pins to make this work. If we make pin 1 an output and high, pin 2 output and low, and pin 3 high impedance (“Hi-Z”), then D1 will light up.

Lighting up first LED with Charlieplexing

If we switch it and make pin 2 high and pin 1 low, then D3 will light up.

Lighting up D3 with Charlieplexing

And if we make pin 3 high, pin 2 low, and pin 1 Hi-Z, D6 will light up.

Lighting up D6 with Charlieplexing

This works because we can make the unused pins high impedance from the microcontroller. High impedance mode looks like an open circuit, so current does not flow into or out from the Hi-Z pins.

If we cycle through all 6 permutations quickly enough, we can trick our eyes into thinking that all the LEDs are on. If we leave selected LEDs off, we can create simple images with our LED array!

Shape on LED Array

The LED Array 8x7

Top of LED Array 8x7

The 8x7 LED array takes our 6-LED example and expands it out to 56 LEDs and 8 pins. We can cycle through all 56 permutations of the pins to turn each LED on individually, and if we cycle fast enough, we can create simple images and text (at least according to our eyes).

Hardware Setup

The LED Array can be connected many ways so long as you have 8 pins available on your Arduino. For this example, we are going to use a RedBoard and pins 2-9. Solder 8 male header pins facing away from the LEDs:

Male header pins on the LED Array

Attach the LED Array to a breadboard and connect pins 2-9 on the RedBoard to pins A-H, respectively:

LED Array Fritzing diagram

Note that you can also solder right-angle headers to the LED Array and RedStick or Pro Mini (again, pins A-H attached to pins 2-9) to achieve a seamless look:

LED Array on the RedStick

Codebender Example

Now that we have the LED Array connected to our Arduino, we can run a simple test to make sure it is working. This example doesn’t require any additional libraries. Simply plug the shield into your Arduino, and upload the example code. Should you want to read how to install the libraries manually with Arduino, skip to the next section.

NOTE: For this example, we're hosting the code on codebender, which not only features code-sharing, but also allows anyone to upload and debug Arduino sketches from within a web browser. Plus, it works on lower-tech machines, like Chromebooks!

There are codebender plugins for Chrome, Chromium, and Firefox. Visit the codebender plugin page for help installing the codebender plugin.

If the codebender embeds don't work for you, we'll also provide a download link to the example code.

Plug your RedBoard, UNO, Pro Mini, RedStick, or other 168/328-based Arduino into an available USB port. Make sure the correct board and the associated COM port are selected in the Codebender box below. Click “Run on Arduino”.

Your LED Array should scroll “Hello World.”

Hello World on the LED Array

Arduino Library

If the Codebender example did not work, you can also manually download the LED Array 8x7 Arduino library. To start, we’ll need the Chaplex library:

Download the Chaplex library

Additionally, we need the LED Array 8x7 Arduino library, which you can download as a ZIP file from GitHub or directly from this link:

Download the SparkFun LED Array 8x7 Arduino library

Once you have both libraries downloaded, follow this guide to install them in Arduino.

Open the Arduino IDE, and select File > Examples > SparkFun LED Array 8x7 > Demo. Select your Arduino and serial port, and upload the program.

LED Array Arduino demo

You should see the LED array scroll through some example text and graphics.

SparkFun logo on the LED Array

Resources and Going Further

Here are a few resources you may find useful as you use your LED Array:

For some inspiration on how to use your LED Array, check out these tutorials:

New!

BadgerHack: Gaming Add-On Kit

Make a Breakout clone with the BadgerHack Gaming Add-On Kit.
New!

BadgerHack: Sensor Add-On Kit

Turn your Badger or Redstick into a temperature and soil moisture sensing display with the BadgerHack Sensor Add-On Kit
New!

BadgerHack: Synth Add-On Kit

Make a tiny synth with BadgerStick.

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

ESP8266 Powered Propane Poofer

$
0
0

ESP8266 Powered Propane Poofer a learn.sparkfun.com tutorial

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

Introduction

Is there anything more fun to look at than a big (controlled) fire? For most of history, pyrotechnic effects have been adding an edge to everything from the Olympic games to the KISS Reunion Tour (surely, these are defining moments in the history of man) But while the ancient Greeks preferred to light their fires with an exhausted, torch-bearing athlete, I’m much more interested in lighting fires from the comfort of my sofa. Enter: The ESP8266 Thing Dev Board. Now we’re cookin' with gas…

Nick using a flamethrower and looking majestic

This could be us but you haven’t built a flame-thrower.

Required Materials

Along with all the components necessary to build the propane poofer (discussed later), you will also need the following electronics to replicate this project:

Suggested Reading

If you have not worked with the ESP8266 before this project, we highly recommend reading our ESP8266 Thing Dev Board Hookup Guide before tackling this project.

ESP8266 Thing Development Board Hookup Guide

November 5, 2015

An overview of SparkFun's ESP8266 Thing Development Board - a development board for the Internet of...Things. This tutorial explains the circuitry driving the board, and how to get it up and running in an Arduino environment.

Flame Throwing 101

Propane poofers are a comprehensively solved engineering problem. A quick Google search reveals more designs for propane-powered flame effects than you can shake a stick at. It also becomes apparent, in short order, that the Burning Man festival attracts quite the collection of semi-professional pyros. Browsing these designs, I’ve found that while there are a lot of variations, the basic structure of a propane poofer stays fairly constant:

diagram of a propane cannon

This is the go-to design for propane flame-cannons, the so-called “accumulator cannon”. In an accumulator cannon, a fuel source is regulated to a relatively low pressure and fed into accumulator tanks (often, they’re modified propane cylinders). These accumulators allow several cannons to be fed from one large gas source. Each cannon has a pilot on a low pressure regulator which burns constantly to provide a source of ignition when it’s time to make a fireball. When the time comes, the solenoid valve at the end of the accumulator is opened, allowing the accumulator to empty through the barrel and be ignited by the pilot. Because the accumulator was allowed to pressurize, you can fire multiple accumulator cannons on the same tank simultaneously without worrying about a big pressure drop in the system.

Because I was building a single portable cannon, I decided to modify this design a little bit. Here’s what I came up with:

diagram of my cannon design

My fuel source would be a pair of disposable propane cylinders, like the kind used in camping stoves and torches. These are small, lightweight and inexpensive… plus, I could buy them by the armful at my local hardware supply. Two such tanks would feed my cannon. Once I had decided on the gist of my design, I started shopping for parts…

Building the Poofer

Between Amazon and the hardware store, I was able to put together the following parts list:

From the hardware store plumbing section

  • 2"x12" Threaded Pipe Nipple
  • 2" Coupler (x2)
  • 2"x1" Bushing (x2)
  • 1" Threaded Pipe Nipple (x2)
  • 1"x1/2" Reducer
  • ½" Threaded Pipe Nipple
  • ½"x1/4" Reducer
  • ¼" Threaded Pipe Nipple
  • 1 ¼" Reducer
  • ¼" Threaded Plug

From various Amazon sellers

  • ¼" FFF Brass Tee
  • ¼" MMM Brass Tee
  • ¼" Solenoid Valve (x2)
  • ¼" Brass Gas Bottle Adapter

With all of the parts collected, it’s time to assemble the cannon! Here are a few exploded diagrams (no pun intended) to detail how everything fits:

detailed diagram of the cannon assembly

Click images for a larger view.

As you can see, I built the expansion chamber by using a series of reducer fittings to connect a foot-long section of 2" pipe to the outlet of the gas bottles. I replaced the pilot with an electrical ignitor, eliminating the need for a low pressure regulator and a separate fuel line. I also decided to move the solenoid valves to the section before the tee junction allowing me to individually open each bottle to the expansion chamber. Let’s have a closer look at this tee junction:

detail of the gas inlet end

You may wonder why I included a female tee between the expander and the male tee only to plug the unused port. Originally, there was a large solenoid valve on the output end of the cannon, allowing the expander to be used as an accumulator. I had a ¼" pressure transducer threaded into that port to monitor the interior pressure of the expansion chamber. It turned out that bringing the expander up to tank pressure and purging it through a 1" solenoid was not only deafeningly loud but generated a stream of uncarborated gas that was nearly impossible to light reliably. When I removed the big solenoid valve, I also removed the pressure transducer (as that section of the cannon became open to atmosphere).

detail of the business end

The nozzle end of the cannon is designed to encourage the escaping gas to spread and mix with the surrounding air. I drilled a hole in the side of the reducer fitting in order to secure the Silicon Nitride Ignitor. The leads for the ignitor run down the side of the expansion chamber where they’re wrapped in heat tape to protect them from the fire.

Because this cannon doesn’t have a pilot, it’s necessary to give a short burst from one tank into the expansion chamber in order to start an open flame at the end of the barrel. As gas slowly leaks from the expander through the nozzle and carborates near the ignitor, it will maintain a low flame. When it’s time to fire a big poof, you simply open both bottles to the chamber for about half a second and whoosh!

Wire it up

If the propane bottles are the heart of this operation then the ESP8266 Thing is definitely the brains. The Thing board will allow us to connect to the flame cannon and fire it from a safe distance. Because the Thing can’t source anywhere near the voltage or current necessary to fire the solenoid valves or light the igniter, we’ll switch them using our Beefcake Relay kits. Our 12VDC power source needs to be portable, rechargable and capable of supplying a decent amount of current so I used a sealed lead-acid battery for a home alarm system. You can pick these up at most home improvement stores.

Here’s what the whole project looks like once it’s wired up:


wiring diagram for the brains of the cannon


I’m using the SLA battery as the power supply for the entire rig. The Thing board is perfectly tolerant of the 12V supply from the battery, but in order to fire the relays, I needed a 5V source as well. I sloppily wired in a 5V regulator which provided plenty of power at 5V to effectively switch the Beefcake Relays. Each relay’s signal line was connected to a GPIO pin on the Thing, I chose 4, 0 and 13 only because they’re side-by-side. Finally, the high side of the 12V line is switched by each relay before reaching the igniter and the two solenoid valves.

In order to recharge the SLA battery, I just throw it on my bench supply at about 14V until it stops drawing current. There are fancier ways to do this, but I’m happy with my system. I didn’t find an external antenna necessary for the Thing to work at significant range thanks to the on-board trace antenna. If you want extra range, however, you can cut the antenna trace, add a U.fl to RP-SMA pigtail and screw on one of our big rubber duck antennas.

To keep the electronics safe and dry, I put them in a plastic ammunition box that I picked up at the hardware store. A bundle of cables comes through a hole in the side of the box and connects to the cannon. The whole unit doesn’t weigh too much, and you can lean the cannon against the box to stabilize it.

Programming the Thing

The firmware that we’re using for the Thing board is based on the AP Web Server example code. This example code sets the Thing board up as a wireless access-point and serves a simple webpage to any connected client. Most of the magic is in the ESP8266WiFi library, so the sketch itself isn’t very long at all. Let’s take a look at it:

language:c

#include <ESP8266WiFi.h>

//////////////////////
// WiFi Definitions //
//////////////////////
const char WiFiAPPSK[] = "sparkfun";

/////////////////////
// Pin Definitions //
/////////////////////
const int VENT1_PIN = 4; //
const int VENT2_PIN = 0; //
const int IGNITION_PIN = 13; //

WiFiServer server(80);

void setup()
{
  initHardware();
  setupWiFi();
  server.begin();
}

void loop()
{
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  // Read the first line of the request
  String req = client.readStringUntil('\r');
  Serial.println(req);
  client.flush();

  // Match the request
  int val = -1;
  if (req.indexOf("/vent1/1") != -1)
    val = 0;
  else if (req.indexOf("/vent2/1") != -1)
    val = 2;
  else if (req.indexOf("/vent_all/1") != -1)
    val = 3;
  else if (req.indexOf("/ignition/1") != -1)
    val = 4;
  else if (req.indexOf("/ignition/0") != -1)
    val = 5;

  // Set GPIO according to the request

  if (val == 0){
    digitalWrite(VENT1_PIN, 1);
    delay(500);
    digitalWrite(VENT1_PIN, 0);}

  else if (val == 2){
    digitalWrite(VENT2_PIN, 1);
    delay(500);
    digitalWrite(VENT2_PIN, 0);}

  else if (val == 3){
    digitalWrite(VENT1_PIN, 1);
    digitalWrite(VENT2_PIN, 1);
    delay(500);
    digitalWrite(VENT1_PIN, 0);
    digitalWrite(VENT2_PIN, 0);}

  else if (val == 4){
    digitalWrite(IGNITION_PIN, 1);}

  else if (val == 5){
    digitalWrite(IGNITION_PIN, 0);}

  client.flush();

  // Prepare the response. Start with the common header:
  String s = "HTTP/1.1 200 OK\r\n";
  s += "Content-Type: text/html\r\n\r\n";
  s += "<!DOCTYPE HTML>\r\n<html>\r\n";

  if ( digitalRead(IGNITION_PIN) == 0 ){
  s += "Ignitior is currently turned OFF.";}
  else{
  s += "Ignitior is currently turned ON.";}
  s += "<br><br>\r\n"; // Go to the next line.

  s += "<a href = \"/ignition/1\">Glow Ingition On</a><br>\r\n";
  s += "<a href = \"/ignition/0\">Glow Ingition Off</a><br>\r\n";
  s += "<a href = \"/vent1/1\">Vent Tank 1 (500ms)</a><br>\r\n";
  s += "<a href = \"/vent2/1\">Vent Tank 2 (500ms)</a><br>\r\n";
  s += "<a href = \"/vent_all/1\">Vent Both Tanks (500ms)</a><br>\r\n";

  s += "</html>\n";

  // Send the response to the client
  client.print(s);
  delay(1);
  Serial.println("Client disonnected");

  // The client will actually be disconnected
  // when the function returns and 'client' object is detroyed
}

void setupWiFi()
{
  WiFi.mode(WIFI_AP);

  // Do a little work to get a unique-ish name. Append the
  // last two bytes of the MAC (HEX'd) to "Thing-":
  uint8_t mac[WL_MAC_ADDR_LENGTH];
  WiFi.softAPmacAddress(mac);
  String macID = String(mac[WL_MAC_ADDR_LENGTH - 2], HEX) +
                 String(mac[WL_MAC_ADDR_LENGTH - 1], HEX);
  macID.toUpperCase();
  String AP_NameString = "ESP8266 Flame Cannon " + macID;

  char AP_NameChar[AP_NameString.length() + 1];
  memset(AP_NameChar, 0, AP_NameString.length() + 1);

  for (int i=0; i<AP_NameString.length(); i++)
    AP_NameChar[i] = AP_NameString.charAt(i);

  WiFi.softAP(AP_NameChar, WiFiAPPSK);
}

void initHardware()
{
  Serial.begin(115200);
  pinMode(VENT1_PIN, OUTPUT);
  digitalWrite(VENT1_PIN, LOW);
  pinMode(VENT2_PIN, OUTPUT);
  digitalWrite(VENT2_PIN, LOW);
  pinMode(IGNITION_PIN, OUTPUT);
  digitalWrite(IGNITION_PIN, LOW);

}

Because this code is essentially an expanded version of the example code, I won’t dive into it too deeply here. That being said, let’s look at what’s changed:

Matching Requests

While the example code was only looking for 3 possible valid requests, we’ll be looking for any of 5: Ignition On, Ignition Off, Vent Tank 1, Vent Tank 2 and Vent All. We handle these requests by assigning a value to each like this:

language:c
  if (req.indexOf("/vent1/1") != -1)
    val = 0;
  else if (req.indexOf("/vent2/1") != -1)
    val = 2;
  else if (req.indexOf("/vent_all/1") != -1)
    val = 3;
  else if (req.indexOf("/ignition/1") != -1)
    val = 4;
  else if (req.indexOf("/ignition/0") != -1)
    val = 5;

When we send our response, we’ll include hyperlinks for each of these requests.

Setting the GPIO

language:c
 if (val == 0){ // Vent Tank 1
    digitalWrite(VENT1_PIN, 1);
    delay(500);
    digitalWrite(VENT1_PIN, 0);}

  else if (val == 2){ // Vent Tank 2
    digitalWrite(VENT2_PIN, 1);
    delay(500);
    digitalWrite(VENT2_PIN, 0);}

  else if (val == 3){ // Vent All
    digitalWrite(VENT1_PIN, 1);
    digitalWrite(VENT2_PIN, 1);
    delay(500);
    digitalWrite(VENT1_PIN, 0);
    digitalWrite(VENT2_PIN, 0);}

  else if (val == 4){ // Ignition On
    digitalWrite(IGNITION_PIN, 1);}

  else if (val == 5){ // Ignition Off
    digitalWrite(IGNITION_PIN, 0);}

Each valid request has an associated GPIO call to open or close a relay. The “Vent Tank” requests simply close the relay for half a second, and then release it. Requests made to the ignitor set it to either the on or off position until further notice.

Formulating a Reply

Our server’s reply will always be a list of hyperlinks that make it easy to quickly fire valid requests. At the top of the list, we’ll add an indicator to let us know whether we have the ignitor turned on. Each line of the html response is appended to a string object and sent to the server library to be relayed to the client. The html reponse, without the weird formatting, looks like this:

  HTTP/1.1 200 OK
  Content-Type: text/html<!DOCTYPE HTML><html>

  Ignitior is currently turned ON.<br><a href = "/ignition/1">Glow Ingition On</a><br><a href = "/ignition/0">Glow Ingition Off</a><br><a href = "/vent1/1">Vent Tank 1 (500ms)</a><br><a href = "/vent2/1">Vent Tank 2 (500ms)</a><br><a href = "/vent_all/1">Vent Both Tanks (500ms)</a><br></html>

Make Fire!

This thing is ready to breathe fire! But first, a checklist:

  • Make sure your propane bottles are securely connected.
  • Listen for possible leaks.
  • Connect the battery leads to power up the system.
  • Get a safe distance away.
  • Connect to the flamethrower’s WiFi network on your phone or laptop.
  • Navigate to 192.168.4.1/ignition/0
  • Press “Glow Ignition On”
  • Give the igniter a few seconds to heat up.
  • Press “Vent Tank 1 (500ms)”
  • Wait for a flame to start

The cannon is now lit and ready to fire. Clear the area and press “Vent All” for an awesome fireball! Be sure to give the cannon some time to rest between firings. Each time you fire the cannon, the solenoid valves are flooded with freezing cold liquid propane, and too much continuous operation can damage the valves, possibly locking them open.

looking majestic again while Sarah fires the cannon behind me

Kudos to Sarah for holding the cannon while I was holding the trigger

Resources and Going Further

There are nearly unlimited resources online for people looking to build fire toys. Thanks to festivals like Burning Man and events like Maker Faire, there are plenty of places people can go to show off their incendiary creations, and that means a big community has grown up around them. Here are a few places worth checking out if you’re interested in building pyro effects:

Going Further

For more information on the Thing board and other connected projects, check out these tutorials!

Pushing Data to Data.SparkFun.com

A grab bag of examples to show off the variety of routes your data can take on its way to a Data.SparkFun.com stream.

ESP8266 Thing Development Board Hookup Guide

An overview of SparkFun's ESP8266 Thing Development Board - a development board for the Internet of...Things. This tutorial explains the circuitry driving the board, and how to get it up and running in an Arduino environment.

Interactive Smart Mirror

Build a smart mirror that displays weather data using the Intel® Edison.
New!

LED Cloud-Connected Cloud

Make a RGB colored cloud light! You can also control it from your phone, or hook up to the weather!

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


MyoWare Muscle Sensor Kit

$
0
0

MyoWare Muscle Sensor Kit a learn.sparkfun.com tutorial

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

Introduction

As announced previously, Advancer Technologies started a Kickstarter campaign to produce an updated version of their Muscle Sensor v3 board. The MyoWare™ Muscle Sensor (AT-04-001) is the latest electromyography (EMG) sensor from Advancer Technologies. Here is an overview of the MyoWare product line and how to use it.

MyoWare Muscle Sensor

Figure 1. MyoWare main sensor board

MyoWare Muscle Sensor

A new version means new features. Here is a breakdown of the new features added to the MyoWare Muscle Sensor Board:

Single-supply— MyoWare won’t need ± voltage power supplies! Unlike the previous sensor, it can now be plugged directly into 3.3V - 5V development boards.

Embedded Electrode Connectors— Electrodes now snap directly to MyoWare, getting rid of those pesky cables and making the MyoWare wearable!

RAW EMG Output— A popular request from grad students, the MyoWare now has a secondary output of the RAW EMG waveform.

Polarity Protected Power Pins— The #1 customer request was to add some protection so the sensor chips don’t burn out when the power is accidentally connected backwards.

ON/OFF Switch— Speaking of burning out the board, Advancer Technologies also added an on-board power switch so you can test your power connections more easily. It’s also handy for saving power.

LED Indicators— Advancer Technologies added two on-board LEDs one to let you know when the MyoWare’s power is on and the other will brighten when your muscle flexes.

For more information, please have a look at the official MyoWare Muscle Sensor datasheet.

What is electromyography (EMG)?

An EMG is used to record (graph) the electrical activity (electro) of muscles (myo).

Embedded Electrode Connectors

The embedded electrode connectors allow you to stick the board right to the target muscle and avoid the hassle of wires.

MyoWare embedded snap connectors

Embedded electrode connectors

The embedded snap connectors mate well with our Biomedical Sensor Pad (10 pack).

Cable Shield

There may still be cases where you want to mount the sensor pads away from the other hardware. For these cases, we sell the MyoWare Cable Shield.

MyoWare Cable Shield

MyoWare Cable Shield

The cable shield provides a jack where you can attach the three electrode cable shown here.

Three electrode cable

Three electrode cable

Instead of attaching the sensor pads to the MyoWare Muscle Sensor, attach them to the end of the cable. Both sets of contacts are connected, so make sure to only use one pad for each (Reference, End, and Middle).

Power Shield

MyoWare Power Shield

MyoWare Power Shield

The MyoWare Power Shield is designed to take two coin cell batteries such as some standard CR2032s. They are connected in parallel for extended capacity at a nominal 3.0V. One thing to note is that due to the size of the batteries, the remote cable header can’t be passed through. If you need access to these connections, this Power Shield must be stacked above the board(s) that need access.

Battery power allows for a cleaner signal and also eliminates the possibility of creating a dangerous current path to the power grid.

Proto Shield

MyoWare prototyping shield

MyoWare prototyping shield

The MyoWare Proto Shield passes all signals to a bit of protoboard. Use this area to solder on whatever custom circuitry you can come up with.

The Cable Shield and the Proto Shield have two rows of 3-pin plated through holes on each end. This allows ‘standard’ 0.1" headers to be used to stack them with other boards. Use the outer rows to connect to the Muscle Sensor, connect these two boards with the inner rows. The outer row on the top can also be used to stack another shield on top for a total of 4 boards in a stack.

Putting it All Together

As mentioned above, there are two ways to attach the sensor pads to a user. They can be attached directly to the sensor board, or to the the end of a cable via the MyoWare Cable Shield.

In the image below, the left most electrode connection should be connected to the muscle being measured. This is equivalent to using the red insulated conductor on the cable. The mid muscle electrode on the right breaks out on the black snap. The reference electrode has continuity with the blue snap on the cable.

MyoWare sensor layout

MyoWare sensor layout

As shown in the image above, there are three rows of three 0.1" spaced plated through holes. On the right is the power supply +Vs, & ground, along with the processed output signal (holes 1, 2, & 3).

Along the long edge near the mid muscle electrode snap are the thru-holes for remote electrode connection (holes 4, 5, & 6).

On the opposite end are three ‘outputs’. Hole 7 is the raw, unprocessed EMG signal. Hole 8 is the switched power. Power goes into the board via hole 1, is switched, and comes back out hole 8 ( if you believe in passive sign convention (PSC) ). Hole 9 is the ground reference for the switched power.

The shields come with assorted support for these pins. Some shields such as the Power Shield don’t support the remote connections. If you need access to these pins the boards that use or can pass them through must go lower in the stack. Both the Cable Shield and the Proto Shield have this connection capability.

MyoWare Power Shield top view

MyoWare Power Shield (top view)

MyoWare Cable Shield bottom view

MyoWare Cable Shield (bottom view)

MyoWare Proto Shield top view

MyoWare Proto Shield (top view)

Take note of the second row of holes on the Cable and Proto shields. This allows for stacking multiple shields using standard 0.1" headers.

Break Away Headers - Straight

PRT-00116
$1.5
19
Female Headers

PRT-00115
$1.5
5

The MyoWare sensor should be populated with female headers. The shield desired to mate with the MyoWare sensor should then have male headers populated on the outer bottom rows to mate with the female headers. The top side of this shield can then be populated with female headers. The next board in the stack will then need male headers on the bottom inside. This shield can have female headers mounted to the outside row on the top side.

To make stacking easier, the MyoWare Muscle Sensor Kit (Coming Soon!) will include 3-pin stackable headers (Coming Soon!). Using these on all of the shields allows for easy stacking in more configurations.

3 pin stackable header

3 pin stackable header

SparkFun will be carrying the 3-pin stackable headers in the near future. This tutorial will be updated as soon as they are available for purchase.

Resources and Going Further

Thanks for reading. For more information on the MyoWare product line, please visit the following links.

Hackers in Residence - Hacking MindWave Mobile

Review, teardown, and hacking tutorial for the MindWave Mobile, a $99 commercial grade EEG sensor.

AD8232 Heart Rate Monitor Hookup Guide

Learn how to create your very own heart rate monitor.
New!

MyoWare Muscle Sensor Kit

Line of products to work with the MyoWare muscle sensor from Advancer Technologies

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

Blynk Board Arduino Development Guide

$
0
0

Blynk Board Arduino Development Guide a learn.sparkfun.com tutorial

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

Introduction

After successfully provisioning a SparkFun Blynk Board, and exhausting all of the examples in the Blynk Board Project Guide, you may be asking yourself: “What’s next?” The answer to that question is: “It’s completely up to you!” Now that you’re a professional Blynker, you have all of the tools necessary to create a Blynk project of your own!

alt text

This tutorial demonstrates how to add Blynk Board support to the Arduino IDE, so you can get started writing and uploading Blynk firmware of your own. If you really liked the BotaniTweet project from the Project Guide, but just wanted to tweak a few things, this tutorial will provide you with the tools necessary to start down that road.

The Blynk Board Tutorial Trilogy

This tutorial is structured as a follow-up to the Blynk Board Project Guide, which is itself a sequel to the Getting Started With the Blynk Board tutorial.

Uploading new code to the Blynk Board will (at least temporarily) remove the pre-loaded Blynk Board projects from the board. It will also remove provisioning functionality.

The firmware is open-source, however. So if you want to get the Blynk Board's default firmware loaded back up, all you have to do is load it back on!

Install FTDI Drivers

The Blynk Board uses a specialized chip called an “FTDI” to convert USB data to a more simple serial interface. It’s over this serial interface that the Blynk Board downloads new code.

If you’ve never used an FTDI-based device before, you’ll probably need to install drivers on your computer. Our How to Install FTDI Drivers tutorial should help get your drivers installed, whether you’re on a Mac, Windows, or Linux machine.

Install FTDI Drivers

Once you’ve installed the drivers, your Blynk Board should show up on your computer as either COM# (if you’re on a Windows machine) or /dev/tty.usbserial-######## (if you’re on a Mac/Linux computer), where the #’s are unique numbers or alphabetic characters.

Install the Blynk Board Arduino Addon

To use the Blynk Board in Arduino, you’ll need to install a few additional files on top of the core Arduino program. Fortunately for us, Arduino’s new Board Manager feature makes that just a few copy/pastes and button-clicks away!

Download, Install Arduino

If you've never used an Arduino Board, or the Arduino IDE before, we apologize in advanced for potentially feeding a new addiction.

Arduino is an open-source development environment for embedded microcontrollers. But, beyond that, it's a simplified programming language, standardized hardware layout, and a helpful community.

Download Arduino!

Head over to Arduino.cc to download the software. It'll run on Windows, Mac, Linux – almost anything you can throw at it!

Install the Blynk Board Addon

We’ll use the Arduino Board Manager feature to help set the IDE up for the Blynk Board. Follow the steps below to instill the IDE with Blynk Board compatibility.

Step 1: Give Arduino the Link

To tell Arduino where to get the board definitions from open the Arduino preferences, which you’ll find under the File>Preferences menu.

Opening arduino preferences

Then copy this URL:

https://raw.githubusercontent.com/sparkfun/Arduino_Boards/master/IDE_Board_Manager/package_sparkfun_index.json

And paste it into the “Additional Board Manager URLs” text box.

Board definition location

Step 2: Install the Definitions

With the link pasted in. Hit OK in the preferences box. Then navigate to Tools>Board>Boards Manager….

Opening the boards manager

In the window that pops open next, search for “Blynk”. The “SparkFun ESP8266 Boards” menu entry should be the only survivor.

alt text

Select that, and click Install. The process may take a couple minutes to download, as the tools are about 100MB.

Step 3: Select the Blynk Board

After the board manager successfully grabs the Blynk Board definitions, look under the Tools>Board menu again – you should see a menu entry for SparkFun Blynk Board.

alt text

Select that, and you’re just about there. Time to load some Blynk code!

Get a Blynk Auth Token

The Blynk Board Arduino addon includes the Blynk Arduino library, so you should have almost everything you need to start Blynking.

Almost…

Every Blynk project is assigned a unique 32-byte string called the “auth token”, which allows your hardware communicate with a specific project in the app. When you upload a new program to the Blynk Board, you need to program the auth token into it on top of any other code you may want to add.

To get a new Blynk auth token, you have two options: use the same project from before, or create a new project.

Option 1: Getting the Code From a Previously Created Blynk Project

Reusing a Blynk project is a great way to save energy, as long as you don’t mind deleting or modifying a few widgets.

To find an existing Blynk project’s auth token, stop the project, then hit the hexagon-shaped nut in the upper right corner to open the project settings.

Opening settings

On the settings page, scroll down a bit to find the “Auth Token” section, where you’ll find a long, incomprehensible 32-character string, and a couple handy buttons. Tap the E-MAIL button, to have the code e-mailed to your Blynk-connected email address.

Email the blynk auth token

Turn your computer towards your inbox, and look for an email from dispatcher@blynk.cc.

alt text

Keep the auth token handy! You can hit “OK” (iOS) or the upper-left back arrow (Android) to exit your project’s settings page.

Option 2: Create a New Blynk Project

If you want to start fresh, with a new Blynk project, begin by backing out to the Blynk project navigator screen – hit the upper-left “back” button if you’re in a project.

Next, scroll as far to the right of the project navigator screen as you can, and find the Create New Project button.

alt text

Clicking that will lead you to the “Project Settings” page. Name your project, and set the Hardware Model to SparkFun Blynk Board.

alt text

Most importantly on this screen, tap E-Mail under the Auth Token to send yourself a copy of the 32-byte string.

Finally, tap Create Project to find yourself on a blank Blynk project.

Set Up the Blynk Project

This example Blynk program only specifies functionality for the RGB LED, but you can use any of the hardware pins regardless of what the firmware specifies.

Configure the Button, LED, and ADC

You can use the button widget to drive the tiny, blue, pin 5 LED. Configure it as either push or pull, just make sure the pin is set to 5.

Configure the Button widget

The Blynk Board’s physical button can trigger a value widget. Set the widget’s pin to 0.

Configure a value widget to read the button

Finally, you can use either a gauge or value widget to display the value of the ADC. Just make sure to set the pin to ADC.

Configure the gauge widget to read the ADC

Configure the zeRGBa

To use the zeRGBa widget, add it, set the switch to Merge and set the pin to V0.

zeRGBa configuration

Your project may look a little something like this when it’s all configured:

Example project layout

Load an Example Program

With the Blynk auth token at hand, and the project set up, you’re armed with all of the information you’ll need to get your board Blynking again.

Configure the Code

Copy and paste this code into your Arduino IDE, but don’t upload it yet!

language:c
#define BLYNK_PRINT Serial    // Comment this out to disable prints and save space
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <Adafruit_NeoPixel.h>

////////////////////
// Blynk Settings //
////////////////////
char BlynkAuth[] = "Your_Auth_Token";
char WiFiNetwork[] = "Your_WiFi_Network";
char WiFiPassword[] = "Your_WiFi_Password";

///////////////////////
// Hardware Settings //
///////////////////////
#define WS2812_PIN 4 // Pin connected to WS2812 LED
#define BUTTON_PIN 0
#define LED_PIN    5
Adafruit_NeoPixel rgb = Adafruit_NeoPixel(1, WS2812_PIN, NEO_GRB + NEO_KHZ800);

BLYNK_WRITE(V0) // Handle RGB from the zeRGBa
{
  if (param.getLength() < 5)
    return;

  byte red = param[0].asInt();
  byte green = param[1].asInt();
  byte blue = param[2].asInt();

  uint32_t rgbColor = rgb.Color(red, green, blue);
  rgb.setPixelColor(0, rgbColor);
  rgb.show();
}

void setup()
{
  // Initialize hardware
  Serial.begin(9600); // Serial
  rgb.begin(); // RGB LED
  pinMode(BUTTON_PIN, INPUT); // Button input
  pinMode(LED_PIN, OUTPUT); // LED output

  // Initialize Blynk
  Blynk.begin(BlynkAuth, WiFiNetwork, WiFiPassword);
}

void loop()
{
  // Execute Blynk.run() as often as possible during the loop
  Blynk.run();
}

Before uploading the code, you’ll need to adjust three variables towards the top of the sketch:

  1. Paste your Blynk auth token over Your_Auth_Token, setting the BlynkAuth variable.
  2. Paste your WiFi network name over Your_WiFi_Network, setting the WiFiNetwork variable.
  3. Paste your WiFi password over Your_WiFi_Password, setting the WiFiPassword variable
    • If the network is open, leave the string empty ("").

Upload the Code

Before uploading, you’ll need to configure the serial port– the “COM#” or “/dev/tty.usbserial-########” number you discovered way back at the FTDI driver-installation phase. Knowing that, navigate to Tools>Port and select your port number.

Serial port selection

We also suggest increasing the upload rate to 921600. You’ll find that setting under the Tools>Upload Speed option.

This is the moment of truth! Once the code has been configured, hit the Upload button (the right-pointing arrow).

Your computer may take a minute-or-so to compile the code, and send it over to the Blynk board. Arduino should inform you if the upload was successful or not. If not – double check the board and port settings, and give it another try. Sometimes that’s all it takes.

Check the Serial Monitor

If the code successfully uploads, open the serial monitor– the magnifying glass icon, in the upper right portion of the Arduino IDE.

This window will pass some handy debug information. It’ll tell you if the Blynk Board successfully connected to your WiFi network and the Blynk server.

alt text

If you see a “Ready” message – you should be good to Blynk! Do some zeRGBa'ing, press some buttons, and adjust some analog inputs! You’re well on your way to making your own Blynk projects.

Resources & Going Further

Now that you have an Arduino-programmable, Blynking Blynk Board, what new amazing IoT project are you going to make? Need some inspiration? Check out some of these tutorials:

If you need general Blynk Board or Blynk App resources, these may help:


If you need any technical assistance with your Blynk Board, don’t hesitate to contact our technical support team via either e-mail, chat, or phone.


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

Blynk Board Project Guide

$
0
0

Blynk Board Project Guide a learn.sparkfun.com tutorial

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

Introduction

So you’ve provisioned your SparkFun Blynk Board– connected it to your Wi-Fi network and started using the zeRGBa to control the RGB LED – now what? Time to build some projects!

BotaniTweet project in action

Project 12 of this guide: creating a sentient, tweeting plant.

This tutorial will walk you through fourteen Blynk projects, which range from blinking an LED with a smartphone to setting up a tweeting, moisture-sensing house plant.

This tutorial follows our "Getting Started with the SparkFun Blynk Board" tutorial, which demonstrates how to provision your Blynk Board and get it connected to a Blynk project.

Have you just powered up your Blynk Board? You need to get your board on Wi-Fi first! Head over to the Getting Started tutorial to learn how.

All of the projects in this guide are pre-loaded into the Blynk Board. That means you don’t have to write any code – just drag and drop some Blynk widgets, configure some settings and play! This tutorial will help familiarize you with both the Blynk Board hardware and the Blynk app, so, once you’re ready, you can jump into customizing the Blynk Board code and creating a project of your own.

Suggested Reading

We'll be (over-)using electrical engineering terms like "voltage", "digital", "analog", and "signal" throughout this tutorial, but that doesn't mean you need to be an electrical engineer to know what they mean.

We pride ourselves on our comprehensive list of conceptual tutorials, which cover topics ranging from basics, like What is Electricity? or Voltage, Current, Resistance, and Ohm's Law to more advanced tutorials, like Logic Levels and I2C.


Voltage, Current, Resistance, and Ohm's Law

The fundamental components of electricity, and the law that rules them all!

What is Electricity?

Not an easy question, but in this tutorial we will shed some light on what is electricity!

Logic Levels

Learn the difference between 3.3 V and 5 V devices.

I2C

An introduction to I2C – one of the main embedded communications protocols in use today.

We'll link to tutorials as we introduce new concepts throughout this tutorial. If you ever feel like you're in too deep, take a detour through some of those first!


Before we really dive into those projects, though, let’s familiarize ourselves with the Blynk Board and all of the components it features. Click the “Next Page” button below to proceed to the Blynk Board Overview section (or click “View as Single Page” to load the entire tutorial in all of its glory).

Blynk Board Overview

You’re probably already familiar with the most important Blynk Board component – the shiny RGB LED – but there’s a whole lot more included with the board. Throughout these projects you’ll explore everything the Blynk Board has to offer, but here’s a quick overview:

Annotated diagram

Meet the Blynk Board Pins

The Blynk Board interfaces with the outside world using input/ouput (I/O) “pins”– tiny “fingers” that can either control real-world objects, like motors or LEDs, or read in values from sensors (for example light or position).

Each of the Blynk Board’s pins are accessible via the large, metal-encircled holes on the edge of the board. These large holes are designed to interface with alligator clip cables– a staple interface cable for beginner and advanced electrical engineers alike.

Alligator clips clamped on the Blynk Board

Alligator clips clipped onto the Blynk Board, interfacing it with the physical world.

Each of the Blynk Board alligator-clippable-pins are labeled with white text towards the center of the board. The Blynk Board pins can be broken down into a few categories: general-purpose (GP), analog input, and power output.

General Purpose Input/Output (GPIO) Pins

There are eight “general-purpose” input/output (GPIO) pins. These are the “worker-bees” to the Blynk Board’s main processor “queen”. You can use them to control outputs – like LEDs or motors – or as inputs, gathering data from buttons, switches, encoders, and more.

Pin LabelNotes
12Input or PWM-capable output.
13Input or PWM-capable output.
15Input or PWM-capable output.
16Input with pull-down resistor.
0Input; connected to on-board button.
5Output; connected to on-board LED.

We recommend against using the RX and TX pins unless you really need them, but the rest are free for interfacing with the rest of the world as you desire!

Analog Input (ADC) Pin

A very special pin labeled “ADC” sports the Blynk Board’s analog-to-digital converter (ADC). This pin translates analog voltages to the digital 1’s and 0’s a computer can understand.

Blynk Board ADC input

This pin is mostly used to read the values of real-world sensors – you can connect it to light sensors, motion sensors, flex sensors, and all sorts of other physical-world-sensing electronic components.

Power Outputs

In addition to the Blynk Board’s I/O pins, the power rails are also broken out to alligator-clip pins. These are the pins labeled “VIN”, “3.3V”, and “GND”.

Blynk Board power outputs

You’ll get very accustomed to using these pins – especially the ground pin. They have all sorts of uses – ranging from powering motors to providing a reference voltage for a potentiometer.

While the Blynk Board includes a variety of inputs and outputs, we could never fit as much onto the board as we’d like. This page lists the handful of wires, sensors, LEDs, and other electronic components that tie-in well with the Blynk Board projects.

If you have the Blynk Board IoT Starter Kit, you’re probably already set up with most of these components. (Everything except the PowerSwitch Tail, in fact.)

Don't worry if your electronics toolbox isn't outfitted with one, or more, of these components yet!

We've designed the projects in this guide to all be do-able regardless of whether-or-not you have external components plugged into the board. (You may just get very tired of using the Blynk Board's temp/humidity sensor input, or RGB LED output.)

Project 1: Blynk Button, Physical LED

Enough reading, time for blinking/Blynking! Our first project explores one of the most fundamental concepts in electronics and programming: digital input and output. A digital signal has a finite number of states – in fact, it usually only has two possible conditions: ON (a.k.a. HIGH, 1) or OFF (a.k.a. LOW, 0).

Blinking LED

💡Blink – the Electronics "Hello, Word"

As simple as this project may look, blinking an LED is the first step towards a long, fruitful journey of electronics tinkering. You'd be surprised at how many other real-world objects you can manipulate with a simple HIGH/LOW digital signal: you can turn a Relay on or off -- which can, in turn, control power to any household electronics. You can use digital signals to spin motors (or at least drive a motor controller). Or you can quickly pulse a digital signal to produce tones in a buzzer.

Blynk project layout

Using Blynk’s Button widget, we can send a digital signal to the Blynk Board. If we attach that input to the right output on the Blynk board, we can use the HIGH/LOW signal to turn an LED on or off.

Blynk Setup

By now you should already have a Blynk project – complete with an LED-controlling zeRGBa – running on your phone. We’re going to continue using this project for our experimenting in this guide.

Don't delete the BlynkMe project! We'll continue using the provisioning-provided Blynk project throughout this tutorial. Later, after coming up with a Blynk project of your own, you can create more projects (or continue using this one).

Make sure you keep the Blynk Board QR-Code Card– although it won't supply your account with more energy, it can be used to re-provision the Blynk Board.

Removing Widgets

Since we’ll be using the same project throughout, you’ll eventually want to make some space for more/bigger widgets. So to begin, let’s clear the project out (don’t worry, the zeRGBa and LCD are coming back soon!).

To delete widgets from your a Blynk project, follow these steps:

  1. If your project is still running, stop it by clicking the square stop button in the upper right-hand corner.
  2. Tap the zeRGBa widget to open its settings.
  3. Scroll down to the bottom of the zeRGBa settings and press the red delete button.
  4. Confirm the deletion – on iOS click Delete Widget, on an Android hit “OK” on the popup dialog.

Deleting a Blynk Widget

Follow the same set of steps to remove the LCD widget from the project.

Adding a Button to Pin 5

Let’s start by adding a simple button widget. Here’s how:

  1. Make sure your project is not running– the upper-right icon should be a triangular play button.
  2. Touch anywhere in the blank, gray project space. A toolbox should open up on the right side with all of your widgets to choose from.

Blynk Widget box

  1. Select the Button widget by tapping it. You'll find it at the top of the "Controllers" list.
  2. Tap and hold the button widget to drag it anywhere within the project space. You've got a lot of room to work with right now.

Positioning the button

  1. Touch the Button Widget to bring up the settings page, and modify these values:
    1. Name: "LED"– While the widget is a button, we'll be using it to control an LED.
    2. Output: 5– in the "Digital" list.
    3. Color: Click the red circle to change the color of the button. Try blue, since we're toggling a blue LED!
    4. Mode: Take your pick. Try them both!

Configuring the Button Settings

  1. Confirm the settings.
    • If you're using an Android, hit the back arrow in the upper-left corner
    • If you're using an iOS device, hit the OK button.

Now that the button is all configured, run the project by tapping the play button in the upper-right corner of the screen.

Blynk Run

Once the project is running, tap your new-blue button widget. When the widget is set to ON, the tiny blue LED should also turn on.

Using the app to control the LED

Button: Push vs. Switch

Try switching the button’s mode between push and switch. Whenever you need to make changes to a widget’s settings tap the upper-right stop button, then tap the widget you’d like to configure. Once you’re done configuring, confirm the changes (“OK” button on iOS, upper-left back-arrow on Android), and set the project back to run mode.

If you have the widget set to PUSH, you’ll have to hold the button down to keep the LED on. SWITCH mode allows you to set it and leave it. Give them both a try and see which you prefer.

Going Further: Adding an Offboard LED

While it’s a useful status indicator, that blue LED is so small it’s barely visible above the shine of the RGB LED. Combining a couple alligator clip cables, with a 330Ω resistor, and an LED of your choice, you can offboard the Blynk Board’s LED control.

LED - Assorted (20 pack)

COM-12062
$2.95
5
Alligator Test Leads - Multicolored (10 Pack)

PRT-12978
$2.95
3
LED Rainbow Pack - 5mm PTH

COM-12903
$2.95
2
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

COM-11507
$0.95
2

First, locate the LED’s positive, anode pin– you’ll be able to identify it by the longer leg.

Identifying LED Polarity

Bend the long leg out 90°, then twist it together with one of the legs of the 330Ω resistor (either end, resistors aren’t polarized).

LED and resistor legs twisted together

Next grab two alligator clip cables– one black, the other green (although the color doesn’t matter, using black for the ground wire is a nice convention to follow). Clamp one end of the black cable to the LED, and clamp one end of the other cable to the resistor.

Alligator clips clamped to legs

Plug the other end of the black cable into the “GND” pin, and the other end of the green cable to the “5” pin.

Alligator clips clamped to board

Now flick the Blynk app’s LED button again. Not only will the blue LED toggle, but your offboard LED should too! If the LED isn’t turning on, try swapping the alligator clip cables around on the LED and resistor legs.

Changing the Digital Pins

Now try driving the offboard LED using pin 12. Move the green alligator clip from the “5” pin to the “12”.

You’ll also need to either add another button widget, or change the settings of the one you’ve already laid down.

Adding a second button to pin 12

Feel free to repeat the same experiment on pins 13 and 15! Avoid pins 0 and 16 for now, they’ll be used as inputs later in this tutorial.

Project 2: Physical Button, Blynk LED

In the previous experiment, we used the button widget to receive a digital input and produce a digital output– pressing a button on the app toggled an LED on the board. Now let’s do the opposite – use a button on the Blynk Board to toggle an “LED” in the app.

Blinking LED Widget

This project introduces the LED widget– a simple tool for indicating the digital status of a Blynk Board input.

Blynk Setup

There should still be plenty of room in the Blynk Board project for the LED widget. You can either keep the button widget from the previous project, or remove it to save a little space. If it’s not bugging you, we suggest keeping the button widget around– you’ll be re-configuring and using it again soon.

Saving and Re-Purposing Widgets

Widgets cost Blynk energy! Even if you get most of that energy refunded when you remove it from a project, it can take a psychological toll – every energy point is precious!

Throughout this guide, never feel obligated to remove any widget from a project – even if you're not using it in the active project. That's especially true with the button and value widgets, which will be reocurring throughout this project guide.

Add an LED Widget to V1

Like the button widget before, follow these steps to add an LED widget:

  1. If your project is running touch the sqaure button in the upper-right corner to stop it.
  2. Touch anywhere in the blank project space to open the widget box.
  3. Select the LED widget near the top of the "Displays" section.

Adding an LED from the Widget box

  1. Drag and position the LED widget anywhere in your project space.
  2. Touch the LED widget to open up the Settings dialog, and adjust these values:
    1. Name: "Btn" (not "Button" for reasons...)
    2. Pin: V1. Any pin beginning with a "V" will be found under the "Virtual" list.
    3. Color: Touch the red circle to change the color of your LED. You can even set it up as a mythical black LED.

Configuring the LED settings

Touch the Play button in the upper-right corner to start the project back up.

Blynk Run

With your project running, push down on the little gold circle of the Blynk Board’s push-button.

Pressing the button on the Blynk Board

While you’re holding the button down, you should see the Blynk project’s LED illuminate. Depending on lagtime, the LED may take a couple seconds to notice the button is pressed. Releasing the button will turn the LED back off.

Virtual Pins

V1, which we're using in this example to control the Blynk LED state, is one of the Blynk project's 32 virtual pins– a custom-programmed input or output, that can read or write values of all types to the Blynk Board or app.

Instead of directly reading or writing to digital or analog pins, virtual pins have to be implemented in firmware (the code running on the board). When you start writing your own Blynk programs, you can re-define these virtual pins to read or write any value, or to control anything that meets your fancy. For now, though, these pins are all defined in the Blynk Board's firmware; you should discover nearly all 32 of them throughout this guide.

Going Further: Launch a Rocket

Blynk LED widgets are great for indicating the digital status of any input pin, or any other virtual pin. You can tie just about any digital input into the 0 pin on the Blynk Board.

For example, grab a couple alligator clips and a rocket-launcher-style toggle switch, then connect them up like this:

Connecting clips to the rocket launcher switch

Be careful not to allow the two alligator clips to touch – it’s a tight fit, but it works!

Then connect the black wire to GND and the colored cable to 0.

Now, turning on the LED is even more satisfying! When the toggle switch is set to “ON”, the LED should illuminate.

Project 3: Slide-Dimming LEDs

Now that you’re an expert on digital inputs and outputs, it’s time to throw a curveball with analog signals. Analog values can take on any shape and be any value among the infinite possibilities in our world.

As with digital signals, the Blynk Board can also produce analog outputs or read in analog inputs. By producing an analog input, the Blynk Board can dim an LED, instead of being left with either turning it on or off.

Blynk regular and large sliders

To produce analog outputs, we’ll use the Slider widget in the Blynk app. The slider allows you to precisely set the value of an output on the Blynk Board – it’s not just ON or OFF. Now, you can set a value between 0-255, 0-1023, -8 to +8, or whatever else you please.

Pulse-Width Modulation (PWM)

To be honest, the Blynk Board actually can't produce truly analog outputs. Instead, it quickly pulses a digital signal high and low to produce an average voltage in a technique called pulse-width modulation (PWM).

PWM waves aren't really analog, but they go up and down so fast that a lot of components – like LEDs – can't tell the difference.

Blynk Setup

Once again, you should have plenty of room left in your project – only delete widgets if you want to clean up a bit. However, if you still have the button triggering the pin 5 blue LED, you’ll need to disconnect it in order to use a slider on the pin.

One Pin At a Time

When configured to monitor or control a pin, a Blynk widget lays claim over that pin until it's disconnected. In fact, in most cases the Blynk app won't let you assign one pin to multiple widgets at once.

By limiting pin-control to one widget at time, we make sure the Blynk Board can't get confused – you wouldn't like it when it's confused.

Disconnect the Button From Pin 5

  1. Stop the project.
  2. Touch the button to bring up its settings.
  3. Change the pin to the dash (–) and hit OK a couple times.

Disconnnect the button from pin 5

If you still have a button controlling pin 5, disconnect it by clearing the pin setting.

The button will remain in your project – you won’t lose any energy – but it’ll be disconnected from any digital or virtual pins for now. Pressing it while the project is running won’t have any effect.

Connect a Slider Widget to Pin 5

  1. Touch anywhere in the blank project space to open the widget box.
  2. Select the Slider near the top of the "Controllers" section.
  3. Drag and position the Slider widget anywhere in your project space.
  4. Touch the Slider widget to open up the Settings dialog, and adjust these values:
    1. Name: "LED Dimming"– we're using it to control the LED
    2. Pin: 5– under the "Digital" list
    3. Range: 0⟷255, covering the full PWM output range.
    4. Color: Touch the red circle to change the color of your slider.

Adjusting the slider settings

Confirm the settings, and run the project.

Blynk Run

Once the project is running, try grabbing the slider and gradually moving it from one side to the other. The small, blue LED should brighten and dim as you do so. The closer the slider value is to 0, the dimmer it will be. 255 is 100% ON and 0 is totally off.

You can also give the large slider a try. Both sliders accomplish the same task, but the large sliders tend to provide a bit more precision over the pin’s value.

Going Further: RGB Precision Control

Sliders can take on all sorts of applications in a Blynk project. In addition to directly controlling a digital pin’s PWM value, they can be used to provide a range of input to firmware running on the Blynk Board.

In fact, we’ve set up virtual pins 2, 3, and 4 to individually control the red, green, and blue channels of the RGB LED. Try adding three more sliders:

WidgetNamePinMinimumMaximum
Large SliderRedV20255
Large SliderGreenV30255
Large SliderBlueV40255

Configuring the RGB sliders

Run the project, and slide around. You may find that the three individual sliders provide more precise control over the mixed color of the RGB LED compared to the zeRGBa widget.

Sliding the RGB LED

Brightness Control

Time for another admission of guilt: We’ve been holding back the full awe – and terror – of the Blynk Board’s RGB LED. In fact, we’ve been limiting the LED brightness to about 12.5% of it’s full power.

To set the maximum range of the RGB LED add a slider to V15– you can re-purpose the small slider widget controlling the pin 5 LED, if you’d like. Name it “Brightness”, and once again set the range to 0-255.

Adding a brightness slider

Play with all four sliders to see the full range of colors you can create. Just be careful! That LED really can get blindingly bright.


Dimming LEDs isn’t all the sliders are good for. Later projects will use them as input control, setting values like Twitter timers, moisture thresholds, and sensor update rates.

Project 4: Temperature and Humidity Values

Blynk’s Value widget is the workhorse of many-a-Blynk project. Set to a digital pin, it can display the real-time HIGH or LOW values of the pin. Set to the proper virtual pin, it can display as much information as you can fit into four characters.

Example value widgets

In this project, we’ll use two-or-three Blynk value widgets to read how hot your Blynk Board is running and find out whether it’s hydrated enough.

This is the first project to use the Blynk Board’s on-board temperature and humidity sensor– the tiny, white scare adjacent to the “12” pin. This is the first step towards creating environment-sensing projects – for example, you could wire up a relay to turn a fan on or off depending on the local weather conditions.

Blynk Setup

Clean up your Blynk Board project as necessary, make sure the project is stopped, and add three new value widgets.

Add Three Value Widgets to V5, V6, and V7

The Value widgets are located at the top of the “Displays” category. Once in the project, set the widgets up like this:

NamePinMinMaxFrequency
Temp FV51 sec
Temp CV61 sec
HumidityV71 sec

Adjusting the value settings

As always, feel free to adjust your widget colors to your heart’s delight.

The frequency setting controls how often the Blynk app asks the Blynk Board for updated values. You can set it anywhere from four times a second (250ms) to a little less than a minute. Don’t set it to push, though, as the Blynk Board firmware isn’t configured to “push” these values to the app.

For these virtual pins, the range (defaulted to 0-1023) won’t have any effect on the displayed value – you can ignore them.

Once you’ve set all three value widget’s up, run the project.

Blynk Run

A second-or-so after you hit Play, you should see the three values begin to update. “Temp F” and “Temp C” display the temperature in Fahrenheit and Celsius, respectively, while “Humidity” displays the relative humidity as a percentage.

Temperature and humidity values displayed

The most effective way to interact with this project is to get up close to the white temperature/humidity sensor and blow on it. Your breath should quickly raise the humidity reading, before it slowly drops back down. Or, if you can take your Blynk Board outside, go check the environment readings against your local weatherman.

Hot blooded

You can probably tell by placing a finger under the Blynk Board that it tends to run hot. Don't worry! Your desk probably isn't 90°F.

The humidity sensor should still be correct, but, to get a more accurate temperature reading, try unplugging the board, letting it cool off for a minute-or-so, and plugging it back in.

Going Further

Continue to play around with the value widget settings to get a feel for the update rate. Try setting it as fast as possible (250ms) – the Blynk Board should be able to keep up.

You can use the value widget for just about any Blynk input built into the firmware. For example, try setting either the “Temp F” or “Temp C” widgets to V1 (you may have to disconnect the LED first). Now, when you press the button, you’ll reinforce the idea that 255 is equivalent to 100% ON, and 0 is completely off.

Or – if you want to get a jump-start on the next project – set one of the value widget’s pin’s to ADC0, under the “Analog” list. What are these 0-1023 values all about? All of you questions will be answered in the next project!

Project 5: Gauging the Analog-to-Digital Converter

To read in analog inputs, the Blynk Board uses a special-purpose pin called an analog-to-digital converter (ADC). An ADC measure the voltage at a set pin and turns that into a digital value. The ADC on the Blynk Board produces a value between 0 and 1023 – 0 being 0V/LOW/OFF, 1023 being 3.3V/HIGH/ON, and 512 being somewhere in the middle ~1.65V.

Gague widget example

There are a variety of widgets that can be used to display the voltage at the ADC pin. In this project, we’ll use the Gauge widget, which provides the real-time reading on the ADC pin in a nice, proportional manner.

Hardware Setup

The Blynk Board’s ADC input is floating– not electrically connected to any circuitry. Without something connected to the pin, the voltage may wildly fluctuate, so to produce a reliable, steady voltage, we’ll need to wire it up.

There are a huge variety of analog-signal producing electronic components out there, but the most traditional is a potentiometer. “Pots” come in all sorts of shapes and sizes from rotary to linear to soft.

Trimpot 10K with Knob

COM-09806
$0.95
6
Slide Pot - X-Large (10k Linear Taper)

COM-09119
$2.95
Rotary Potentiometer - 10k Ohm, Linear

COM-09939
$0.95
6
SoftPot Membrane Potentiometer - 50mm

SEN-08680
$4.95
1

To really get the most out of this project, consider grabbing a sliding linear potentiometer and three alligator clip cables. Wire up the bottom of the slide pot like below – red cable on the pin labeled “1”, yellow connected to “2” and black connected to “3”.

Hooking alligator clips to the slide pot

Then route the other ends of the alligator-clip cables like below – red to 3.3V, black to GND, and yellow to ADC.

Slide pot connected to the Blynk Board

The yellow cable – terminating on the ADC pin – will carry a voltage that varies between 0V (GND) and 3.3V, depending on the position of the slide pot.

Blynk Setup

The Gauge widget takes up a good chunk of room, so you may need to remove some previous widgets before adding it. Keep a value widget from the previous experiment – we’ll use it to display the calculated voltage.

Connect a Gauge to ADC

You’ll find the Gauge widget under the “Displays” section. Once it’s added, modify the settings like so:

NamePinMinMaxFrequency
ADCADC (under "Analog")01023250 ms

ADC gauge settings

We’re reading directly from the ADC – the Blynk Board’s analog-to-digital converter input. The 10-bit ADC produces a value between 0 and 1023, which is a value proportional to a voltage between 0 and about 3.3V. So, an ADC reading of 0 equates to 0V, 1023 equals 3.3V, and 512 is about 1.75V.

Repurpose a Value Widget to V8

If you don’t want continuously do that voltage-converting math in your head, modify a value widget to display V8, and set the name to Voltage.

Value widget settings

The Blynk Board will convert the ADC reading to an equivalent voltage for you.

Blynk Run

Run the project, and watch for the gauge to settle in on a value. If you have a potentiometer wired up, the reading should remain rather steady. Try moving the wiper up and down.

Project action shot

If you don't have a potentiometer handy or any way of connecting it to the Blynk board, don't fret. You're a variable resistor too! You can test out the ADC by putting a finger on the "ADC" pin.

You should be able to move the gauge around by placing another finger on either the "GND", "VIN", or "3.3V".

(Electricity is running through your body, but it's a minuscule, insignificant amount. You don't have anything to worry about.)


There are a huge variety of analog-signal producing electronic components out there. You could wire up an accelerometer, stick the circuit on a washer/dryer, and check the analog readings to observe if your laundry is done or not. Or wire up a force-sensitive resistor, hide it under your doormat, and check if anyone’s at the front door.

Later in this guide, we’ll wire the ADC up to a Soil Moisture sensor and connect your houseplant to your twitter account, so it can notify the world when it’s thirsty.

Project 6: Automating With the Timer

A large chunk of Internet-of-Things projects revolve around home automation– a classic example of which is automatically switching your lights on and off. Using the Blynk Timer widget, you can trigger specific outputs to fire at any time of the day – even if your app is closed and your smart device is off!

Timer example

The timer’s pair of settings include a start time and a stop time. When the start time is triggered, the timer’s configured pin turns HIGH. When the stop time is met, the pin goes back into a LOW state.

Blynk Setup

All you’ll need for this project is the simple but powerful Timer widget.

Add a Timer Widget on V9

Add the Timer widget to your project – you’ll find it under the “Controllers” list. Then tap the widget to open up the settings page.

Depending on what you have plugged into the board, there are a variety of options available to you on the Pin setting. For now, let’s use it to trigger an RGB light show. Set the Timer’s pin to V9, which is configured to start Rainbow Mode on the Blynk Board’s RGB LED.

Setting a timer to V9

Alternatively, you can use it to toggle any digital pin – like the pin 5 blue LED, or an external LED on pins 12 or 13.

For experimenting purposes, set the start time to about a minute from now, and the stop time to 30-60 seconds later. Once you get a feel for the timer, you can start using it more strategically.

As usual, give it any name and color you please.

Blynk Run

Once you’ve set your timer up, run the project. Hopefully you get it running before the timer’s programmed Start Time! If not, stop and increase the start time another 30 seconds-or-so.

The timer has a hidden feature in run mode: if you tap it you can switch between the start-time display and a countdown display. Countdown display mode is especially handy while your just testing around.

LED Timer expiration

Once the timer triggers it will fade in and out to indicate the pin is on. If the timer’s fading, your pin should be active. Watch the RGB do its hypnotic rainbow dance.

RGB LED timer active

Once the timer hits the Stop Time, the LED should return to its previous duties – waiting to shine another day (literally, you better adjust the start time again).

Going Further: Controlling Lamps With the Power-Switch Tail

The PowerSwitch Tail is one of our favorite general-purpose components in the catalog. With a simple HIGH/LOW signal from the Blynk Board, you can use the PowerSwitch Tail to control power to any device you would otherwise connect to a wall outlet. Best of all, it’s completely enclosed and totally safe.

PowerSwitch Tail II

COM-10747
$28.95
3

Parts Not Included

The PowerSwitch Tail used in this example is not included with the Blynk Board IoT Starter Kit.

To follow along with this example, you'll need the PowerSwitch Tail, a long, phillips-head screwdriver, a couple jumper wires and two alligator clip cables.

First, use your screwdriver to securely wire the jumpers into the PowerSwitch Tail’s “+IN” and “-IN” pins (leave the “Ground” pin unconnected). Then clip alligator cables to the ends of those wires. Wire the “-IN”-connected cable to the Blynk Board’s GND pin, and the “+IN” cable to the Blynk Board’s pin 12.

Powerswitch tail connected to Blynk Board

Plug a lamp, fan, or any device you’d like to automate into the PowerSwitch Tail’s 3-prong female connector. Then connect male 3-prong connector into the wall.

Then set up a new timer – this time connected to pin 12. Adjust the start and stop times, and have the Blynk Board make sure your lights are off when you’re out of the house.

Project 7: The LCD's Wealth of Information

The 16x2 Liquid-Crystal Display– a 16-column, 2-row LCD, which can display any combination of up to 32 alphanumeric characters – is one of the most commonly recurring components in electronic projects. It’s simple to use, and has they ability to convey a wealth of information pertaining to your project.

Alpha-numeric 16x2 LCD

Blynk’s LCD widget is similarly useful in displaying diagnostic and other Blynk-project information. In this project, we’ll the LCD widget to display everything from the Blynk Board’s temperature and humidity readings, to the length of time it’s been up-and-running.

Blynk Setup

This project requires the LCD widget as well as three button widgets, which you can repurpose from the previous projects.

Connect an LCD Widget to V10

Add an LCD widget from the “Displays” section of the widget box, and tap it to bring up the settings page.

Before adjusting anything else, slide the Simple/Advanced slider to Advanced. Then set the pin to V10, and adjust the background and text color as you please (can’t beat white text on black).

LCD Widget settings

Add Button Widgets to V11, V12, and V13

Set the three buttons up to trigger virtual pins 11, 12, and 13. Leave them in Push mode:

NamePin
T/HV11
InputsV12
RuntimeV13

Button settings

Blynk Run

Once the button’s are set, you’re ready to run. Until you hit one of the three buttons, the LCD may print a greeting message. But that will quickly fade once you trigger V11, 12 or 13.

Button running

Although it takes up a lot of room initially, you can see how valuable the LCD is – and the wealth of information and text it can display. While the Value widgets are limited to four characters, the LCD can display up to 32!

Project 8: Joystick Joyride

Joysticks are a staple input for a variety of control systems, including arcade gaming, RC-car driving, drone guiding, and assistive-tech maneuvering. They produce two pieces of data: position components along x- and y-axes. Using that data, a project can compute an angle between 0 and 360°, and use it to drive another mobile mechanism.

Joystick example

Blynk’s take on the joystick is analogous to a physical joystick – as you move the center-stick around, it’ll send x- and y-axis values between 0 and 255 to the Blynk Board. What are we going to to do with that data? Spin a motor!

Servo - Generic (Sub-Micro Size)

ROB-09065
$8.95
6

To be more exact, we’re going to use the joystick to drive a servo motor. Servo’s are specialized motors with a built-in feedback system, which allows for precise control over the motor’s position. Instead of rotating continuously, like DC motors, a servo will move to a position you tell it to, and stop (unless it’s a continuous rotation servo. They’re useful for projects which require complete control over movement, like opening or closing a door to an automatic pet-feeder.

Hardware Setup

Most servo motor’s are terminated with a 0.1"-pitch 3-pin female header. To interface it with your Blynk Board, plug in a few male-to-male jumper wires into the servo socket (if you have the “connected” jumper wires, peel off a strip of three wires). Then clip a few alligator clip cables onto the ends of those wires.

Wiring to a servo

Connect the cable wired to the servo’s black wire to GND, red to VIN, and the white signal wire to pin 15.

Connecting servo to Blynk Board

Press one of the servo motor’s mounts onto the motor head, so you can better-see the spin of the motor.

Blynk Setup

In addition to the Joystick widget, this project can also optionally use a gauge (or value), and a slider. The slider controls the servo motor’s maximum angle, the gauge displays the calculated servo position (especially handy if you don’t have a servo connected).

Connect the Joystick to V14

Add a Joystick widget from the “Controllers” section. Slide the Split/Merge switch to Merge, and set the pin to V14. It’s not required, but we recommend setting autoreturn to off.

Joystick settings

Connect a Slider to V16

If you have a slider in your project, you can re-purpose it to adjust the servo’s maximum angle. Set the pin to V16, and modify the range to make it easy to set your servo’s maximum value.

Slider settings

Connect a Gauge or Value Widget to V17

Finally, the project produces a virtual output on V17 displaying the servo’s current angle. You can use a Value or Gauge widget to show this value. Neither are required – but it does provides feedback if you don’t have a servo motor attached.

Gauge angle output settings

Modify the range of the gauge, or else you might not get the right feel for the servo’s position.

Blynk Run

Once everything’s set up, run it and joystick!

Servo project in action

As you rotate the stick, the servo should noisily reposition itself along the angle you’ve set.

In the background the Blynk Board firmware is grabbing the x and y values of the joystick, doing some trigonometry on them to calculate an angle (in degrees), and pushing that calculation back out to V17.

Going Further

Once you’ve got the servo rotating, connect something physical up to it! How about an automatic fish feeder?

Scrounge around for a bottlecap, and screw it into the servo’s single-arm.

alt text

Then slot the servo arm onto your servo motor head, and check the motion of the bottlecap – you may need to re-position the cap to get the rotation you need.

Now when you rotate the joystick, you’ll have a mobile-food-dumping apparatus – perfectly sized for a goldfish!

Project 9: Graphing Voltage

Electrical engineers love measuring voltage. Whether we’re using a multimeter to get a real-time view into a line’s potential, or a monitoring a periodic signal’s shape using an oscilloscope, monitoring voltage can be critical to project-debugging.

Blynk graph widget

While we can’t really re-create an oscilloscope’s signal-triggering in Blynk, we can chart the Blynk Board’s voltage-over-time using the Graph widget. The graph widget periodically pulls in data from a virtual or physical pin, and creates either a bar or line graph representing how that input changes over time. You can set the graph to draw as fast as four times per second, or as slow as once-a-minute.

Hardware Setup

The Blynk Board’s input voltage will range anywhere from 3.7 to 6V – well outside the acceptable input range of 0-3.3V. So, to properly measure the input voltage, we’ll need to step it down using a voltage divider. Although it sounds complex, a voltage divider is actually just a pair of resistors sitting in between one voltage and another.

To create a voltage divider, first grab a couple 10kΩ resistors, and twist them together at the ends. Clip a yellow alligator clip to the twisted legs of the resistors, and connect red and black alligator cables to either of the other two legs.

Two 10k's twisted together and clamped

Wire the other ends of the cables to ADC (yellow), VIN (red), and GND (black).

Voltage divider connected to the Blynk Board

Voltage: divided. A voltage divider made out of two 10kΩ resistors will cut the voltage in half. So if the Blynk Board’s input voltage is 5V, the voltage at the ADC pin will only be 2.5V.

Blynk Setup

In addition to the graph widget, you can optionally add two value widget’s to help get a better view into the Blynk Board’s voltage measuring.

Connect the Graph to V20

You’ll find the Graph widget under the “Displays” section of the widget box. Add it, then tap it to configure. Set the pin to V20, and adjust the range to something like 0-6. Bump the update frequency up to 250ms.

Graph settings

You can play with the Bar/Line switch, but a line graph seems to work best for this type of data.

Monitor the ADC and V8 With Value’s

For a bit more insight into the Blynk Board’s ADC reading, consider adding a couple value widgets to monitor the ADC pin and V8– the calculated ADC voltage.

ADC value settingVoltage value setting

Blynk Run

See how steady that USB supply is. Try zooming the graph in, so the minimum is 4 and maximum is 6. The more “wiggles” in the signal, the noisier your supply is.

Graphing the USB supply voltage

Fortunately, the Blynk Board regulates that input voltage, to create a nice, steady 3.3V supply. In fact, if you want to measure the 3.3V supply, simply swap the red cable from VIN to 3.3V. Is it steadier than the VIN supply?

Plotting Battery Voltage

If you want to recreate that feeling as you watch your phone’s battery-life icon progressively empty – or the excitement of watching it charge, consider powering the Blynk Board with a LiPo Battery. There are a variety of Blynk Board-compatible LiPo batteries, we recommend either the 450mAh, 850mAh, or 1000mAh.

Graphing the Blynk Board's batter voltage

If you set the read rate to the maximum – 59 seconds– and let the Board run for a while, you should begin to see an interesting downward slope while the battery discharges. Or plug the Blynk Board in and watch that slope incline.

Going Further

The graph widget should work for any of the Blynk Board’s output values. Try changing it to V5 or V6– see how the temperature fluctuates over time. You may need to adjust the graph’s range to actually see the line.

alt text

Plotting the Blynk Board’s Fahrenheit temperature output.

Try plugging other Blynk Board outputs you’ve already used into the Graph widget. Make some interesting curves!

Project 10: Charting Lighting History

Blynk’s History Graph widget takes the standard graph to the next level. It allows you to compare a widget’s value to data from hours, days, weeks, even months back.

History Graph example

In this project, we’ll plug readings from a light sensor into the History Graph. After you’ve let the project run for a while, you’ll be able to track the sun rise/set time, or find out if someone’s been snooping in a room when they’re not supposed to be.

Hardware Setup

To measure ambient light, we’re going to use a light-sensitive resistor called a photocell. When it’s pitch-black, the photocell morphs into a large, 10kΩ resistor, but when light shines on the cell, the device’s resistance drops closer to 1kΩ.

Mini Photocell

SEN-09088
$1.5
6

To create a voltage for the Blynk Board’s ADC, using the photocell’s variable resistance, we need to pair it with a second resistor. The photocell and resistor will combine to create a variable voltage divider.

That second resistor should be somewhere in the middle of the photocell’s resistance range – right about 5kΩ. There aren’t any 5k&Omgea; resistors in the IoT Starter Kit, but it does include the means to create one! By combining two equal resistors in parallel, we can cut their total resistance in half.

So, to create a 5kΩ resistor, grab two 10kΩ resistors, and twist them together in parallel – that is, twist the ends of both resistors together, so the bodies are touching each other. Then twist one leg of the photocell together with one shared leg of our new 5kΩ resistor.

Photocell twisted with 2 10k resistors

Clip a yellow alligator cable to the middle legs – the behemoth that is two resistors and a photocell leg twisted together. Then clip a red cable onto the photocell’s leg, and a black cable onto the other resistor leg.

Alligator clips clamped onto photocell circuit

On the Blynk Board – as you’re probably used to by now – clip the yellow to ADC, red to 3.3V, and black to GND.

Photocell circuit connected to Blynk Board

This circuit will produce a higher voltage in the light and a lower voltage in the dark.

Blynk Setup

This Blynk project combines the History Graph widget with a Value widget to display the real-time light reading.

Configure a Value Widget

Before adding the graph, add a Value widget and configure it to read from V18.

Configuring a value widget

Set the update rate to 1 second, and name the widget “Light.”

Add a History Graph Widget

Once the Value widget is in place, add a History Graph widget. In the settings, configure any one of the four PIN’s to V18.

Configuring the History Graph widget

The textbox adjacent to the pin should automatically update to “Light” (or whatever the Value widget is configured as).

There is one quirk with the History Graph widget – it won’t directly pull or request a variable’s value. It relies on widgets like Value or Gauge to get the latest value from a virtual or physical pin.

Blynk Run

After running the project, begin by monitoring the Value widget’s reading – it should vary between 0 and 1023. See how high you can get the value reading by shining a light on it. (Hint: your phone might just have a bright LED to shine on the photocell.)

Light tracker in action

Then cover up the photocell, or turn off your lights, and see how low you can get the reading. Or! Add a zeRGBa, turn the brightness up to max, and have the Blynk Board feed back into its own light sensor.

To really get the most out of the history widget, you need to leave the project running for at least an hour. If it’s about time to hang it up for the night, leave your Blynk project plugged in and graphing. Maybe you’ll catch someone sneaking in and turning the light on!

If you ever want to delete old history from the History Graph, swipe left on the graph (while the project is running), and select "Erase data."

Going Further

You can add up to four values to the History Graph – play around with the other three pins to see what other interesting info you can graph.

You may have to remove some of the previous pins to adjust the graph’s scale.

Charting temperature and humidity

Celsius temperature and humidity – usually around the same order of magnitude – pair nicely on the graph together. Use the legend so you don’t forget which is which!

Project 11: Terminal Chat

The word “terminal” may instill images of 80’s hacker-kids playing a game of Global Thermonuclear War or 90’s Mr. Anderson’s following white rabbits, but, retro as they may sound, engineers still use terminals on a daily basis.

Blynk terminal example

The Blynk Terminal widget allows you to pass endless information to and from the Blynk Board. It can be incredibly handy – in fact, we’ll use it in all four of the final projects to enter email addresses, pass debug information, and name your Blynk Board.

In this project, we’ll use the terminal on your Blynk app, and a terminal on your Blynk Board-connected computer to set up a “chat program.”

Hardware Setup

There aren’t any external components to connect to your Blynk Board in this experiment, but you may need to do some extra legwork to set up a terminal on your computer.

Install FTDI Drivers, Identify Your Serial Port

The Blynk Board uses a specialized chip called an “FTDI” to convert USB data to a more simple serial interface. If you’ve never used an FTDI-based device before, you’ll probably need to install drivers on your computer. Our How to Install FTDI Drivers tutorial should help get your drivers installed, whether you’re on a Mac, Windows, or Linux machine.

Install FTDI Drivers

Once you’ve installed the drivers, your Blynk Board should show up on your computer as either COM# (if you’re on a Windows machine) or /dev/tty.usbserial-######## (if you’re on a Mac/Linux computer), where the #’s are unique numbers or alphabetic characters.

Download, Run, and Configure the Terminal

There are a huge variety of software serial terminals out there. If you don’t already have one, read through our Serial Terminal Basics tutorial for some suggestions.

Download a Terminal

Once you’ve selected terminal software – and found your Blynk Board’s serial port number – open it and set the baud rate to 9600. The Serial Terminal Basics tutorial linked above should have directions for configuring the serial port.

serial terminal settings

Using TeraTerm to communicate with the Blynk Board over a serial interface.

Don’t be alarmed if your Blynk Board resets when you open the terminal. It may also print some debug messages as it re-connects – they’re handy, but nothing you’ll really need to concern yourself with.

Once the port is open, swap back over to your Blynk project. Time to install another terminal!

Blynk Setup

Just one widget this time: the Terminal. We’ll be using the Terminal widget for the rest of this tutorial, so make it cozy, and don’t delete it.

Add a Terminal Widget

Find the terminal widget under the “Displays” list of the widget box.

Once added, tap the terminal to enter the settings screen. Set the terminal widet’s pin to V21. Keep “Input Line” and “Auto Scroll” set to ON.

Terminal widget settings

Pick any screen and background color you please – how about green background and black text, to get a little oppo-matrix style going.

That’s it. Now run the project.

Blynk Run

Try typing something in your computer terminal – you should see those same characters almost instantly pop up on your Blynk project’s terminal.

Computer terminal example

Computer terminal example - text sent by the Blynk Board/App.

Then try typing something into the Blynk terminal. They should show up on your computer.

Who's on first?

The Blynk Terminal has the full transcript of our confusing conversation.

Now have a conversation with yourself! Or share the project and chat with a friend.

Project 12: BotaniTweeting

For over ten years now, Twitter has been the microblog-of-choice for human and machine alike. While the rich-and-famous use-and-abuse twitter to reach their millions of followers, twitter-enabled projects like our old Kegerator or bots like Stupidcounter have found their own use for the service.

Blynk’s Twitter widget is one of three notification-enabling devices in the app. After connecting it to a Twitter account, the widget will give your Blynk Board a voice on the world-wide-web.

Tweeting plant project

This project, inspired by the Botanicalls Kit, will set your Blynk Board up as a fully-configurable plant soil moisture monitor. Plugged into your favorite house plant, the Blynk Board will give it a voice – so it can shout to the world when it’s thirsty.

Hardware Setup

Our handy Soil Moisture Sensor will be the hardware focus of this experiment.

SparkFun Soil Moisture Sensor

SEN-13322
$4.95
2

At its core, this two-probed sensor is simply a resistance sensor. Wet soil is less resistive than dry soil, so a parched, dry plant will produce a lower voltage than a wet, sated one.

In addition to the soil moisture sensor, you’ll need jumper wires, alligator clip cables, and a screwdriver

Note that while the Soil Moisture Sensor included with the IoT Starter Kit has a screw terminal installed, the stand-alone product does not.

If you've bought the Soil Moisture Sensor separately, you will need to solder wires or a connector to the board.

Hook Up The Soil Moisture Sensor

There are a few hoops to jump through to get the moisture sensor connected to your Blynk Board. To begin, grab a screwdriver, and three jumper wires – black, red, and yellow.

Flip the board over to see the terminal labels. Plug the yellow wire into the “SIG” terminal, black wire into “GND”, and red into “VCC”. Use the small flathead screwdriver bit to securely tighten the jumper wires into the connector.

The SparkFun Pocket Screwdriver includes half-a-dozen bits – small/large, flat/Phillips – but they're hidden in the cap. To access the bits, unscrew the cap and pour them out. Look for the smallest flathead you can find in there and slot it into the head.

Once the jumper wires are secured, clamp alligator clip cables onto the other ends – match up the colors if you can!

Moisture sensor hookup

Finally, clamp the other ends of the alligator clips to 3.3V (VCC/red), GND (GND/black), and the ADC (SIG/yellow).

The higher the reading on the ADC, the wetter (and happier) your plant is.

Blynk Setup

This project requires five widgets: Twitter, Terminal, a Value, and two Sliders. Hopefully you’ve got the Terminal – and maybe a few others – from previous projects. Here’s how to set them up:

Set Up the Twitter Widget

Add the Twitter widget from the “Notifications” list. Move it anywhere you’d like, and tap it to configure.

Hit Connect Twitter, and the app will take you to a foreign screen, where you can log in to your Twitter account. This is an OAUTH connection from Blynk to your Twitter account – if you ever want to disconnect Blynk from your account, you can do so in the Apps section of your account settings.

Connected to Twitter

Once you’ve logged in, and allowed Blynk access to your account, the Twitter widget should have a @YOUR_ACCOUNT link in the settings page. Confirm the settings, and head back to the project.

Set Up the Terminal

As with the previous project, the Terminal should be connected to V21, make sure “Input Line” is turned ON.

Terminal widget settings

Give the terminal any color(s) you’d like.

Set Up the Sliders

A pair of sliders are used to set your plant’s moisture threshold and the minimum tweet rate. Add, or re-configure two sliders (large or regular) as so:

WidgetNamePinMinimumMaximum
SliderMoisture ThresholdV2301023
SliderMinimum Tweet RateV24560

Threshold slider settingsTweet rate slider settings

The minimum tweet rate slider sets the minimum number of minutes between tweets. The Twitter widget can’t tweet more often than once-a-minute, so make sure that’s the bare-minimum of the slider. Set the maximum to as long as you’d like between tweets (e.g. 60 minutes, 720 minutes [12 hours], etc.)

If the reading out of the soil moisture sensor falls below the minimum threshold, it will begin tweeting as often as it’s allowed (by the tweet rate), until the reading goes back up.

Set up the Value

Finally, add or re-configure a value widget to monitor the ADC pin. You’ll need that as you hone in on a good threshold value.

Value widget on ADC

Blynk Run

Once you’ve got all of those widgets set up, run the project. Plug your moisture sensor into your plant, and check the ADC reading.

Project setup

If your soil is nice-and-moist, the reading should be somewhere around 700-800. Try watering your plant – see if the reading goes up.

To verify that the project is functioning and tweeting, set the threshold to 1023 and set the tweet limit to 1. Within a minute-or-so, you should see a new tweet on your timeline.

Example tweet

So far, so good. Now the tricky part. You need to set the moisture threshold to a “dry soil” value. It’ll be under the current value a bit. If you’re moisture is reading out at about 750, try setting the threshold to 740. Then you play the waiting game (or take a heaterizer to your plant’s soil). When the soil dries up, your plant should tweet.

Why is there an ugly [2341584] at the bottom of every tweet? Twitter rules require that no user can send the same content in a recent tweet. So, just in case you're tweeting every minute, and the moisture hasn't really changed, we've added a "counter" to the bottom of the tweet. That should keep the message unique.

Going Further: Setting the Plant’s Name

Why the terminal? To name your plant! Come up with a unique, identifiable name for your plant. Then, in the terminal, type $MY_PLANTS_TWITTER_NAME and hit enter. Make sure to type the “$” first, the terminal will catch that, and begin tweeting with your new name next time your plant gets thirsty.

Naming the board in terminal

Now when your plant tweets, it’ll identify which one it is.

Project 13: Push Door, Push Phone

Push notifications: you either love them or hate them (or it varies, depending on the app sending them), but they can come in handy every once-in-a-while. The Blynk Push widget allows your Blynk Board to send your phone periodic push notifications, so you’re the first to be made aware of a state change in the board.

This project combines a Door Switch Sensor with the push widget. When the door’s state changes – whether it opens or closes – you’ll be the first…well…at least the second to know!

Hardware Setup

This project is based around a Magnetic Door Switch– a truly magical door-state sensor.

Magnetic Door Switch Set

COM-13247
$2.95

This door switch is what we call a reed switch– a magnetically-actuated electronic switch. There are two components to the device: the switch itself, and a simple magnet. When the two components are in close proximity, the switch closes. And when they’re pulled far enough apart, the switch opens up. These switches are commonly used as part of a burglar alarm system or as a proximity-detecting device.

Wire Up the Door Switch

To connect the door switch to your Blynk Board, you’ll just need a couple alligator clip cables – how about red and green. Clamp a red wire to one of the switch’s wires, and the green wire to the other.

Door switch wired

Then clamp the other end of the red wire to 3.3V and the green wire to 16.

We’ve got a pull-down resistor on pin 16. So when the switch is open, it reads as LOW, but when the switch closes the pin connects directly to 3.3V and reads as HIGH.

Blynk Setup

This project uses three widgets: Push (of course), Terminal, and Value. Here’s how to set them up:

Add the Push Widget

You’ll find the Push widget under the “Notifications” list, towards the bottom. After adding it, tap it to configure its settings.

Android push widget settings

Notifications work differently in iOS and Android devices. If you’re using an Android device, your settings will look like above. You can turn the “Notify when hardware goes offline” setting on or off at your discretion – it can be handy in other projects. The Priority setting can be set to HIGH, but it will end up draining your phone’s battery a little faster.

The iOS settings look like this:

iOS Push settings

Again, both of these sliders are left to your discretion. Enabling background notifications will likely take a bit more battery-life out of your phone.

Configure the Terminal

If you’ve still got the Terminal widget from previous projects, great – leave it be. If not, configure it to use pin V21.

Terminal settings

Configure the Value Widget

Finally, set the value widget to V25. This widget will display the up-to-date state of your door switch sensor.

Value settings

Blynk Run

Once everything’s added, run the project! Try putting the two door switches close together, or pulling them apart. A few things should happen:

  • The Terminal will print a debug message – stating that the door opened or closed.
  • The Value widget should display the up-to-date state of the door.

Notified!

And! Hopefully, your phone will pop up a notification that the switch’s state changed. Unfortunately (or fortunately, depending on how much you enjoy notifications), the Blynk app limits project notifications to once-a-minute. If you open and close the door to fast, you might get the first notification, but for the next minute you’ll need to check the terminal or value widgets.

As with the previous project, you can set the name of your board by typing $BOARD_NAME. That name will be added to the notification that pops up on your phone.

Going Further

Tape or screw the door switch sensor to something! If you’ve got the IoT Starter Kit, you may already have something to test it out on.

Using the SparkFun Box to test a door switch

The unique red SparkFun box has been re-purposed as a project enclosure in countless projects. Or you can use it to store your valuables.

SparkFun Box closed, valuables safe!

With a Blynk-enabled alarm – you’ll be notified whenever someone’s sneaking into your box!

Project 14: Status Emails

The final notification-creating Blynk gadget is the Email widget, which allows you to tailor an Email’s subject and message, and send it to anyone’s inbox. It’s a great power; use it responsibly. Don’t go creating a Blynking spam bot!

Email widget

This project gathers data from all of the sensor’s we’ve been using in these projects, combines them into an Email message, and sends that message to an Email address of your choice (set using the Terminal widget).

There is no external hardware required for this project. If you had a favorite analog component for the ADC, or want to plug a digital input into pin 16, feel free to alligator-clip at will! Among other values, the readings from those pins will be added to the Email's body.

Blynk Setup

This project uses three widgets: Email, Terminal, and a Button.

Add the Email Widget

Find the Email widget under the “Notifications” list, towards the bottom of the widget box.

Email "Settings"

You’re understandably conditioned to tap the Email widget to configure it, but that’s not necessary this time. The Email widget doesn’t have any settings! All it does is provide your Blynk Board with Email-sending ability.

Configure a Terminal Widget

As with the previous experiments, we’ll be using the Terminal widget as an general-purpose string input/output device. If you’ve still got the Terminal widget from previous projects, great – leave it be. If not, configure it to use pin V21.

Terminal widget settings

Most importantly, the Terminal widget will be used to enter an Email address, otherwise the Blynk Board will have nowhere to send your data.

Connect a Button to V27

Finally, we’ll use a button to trigger the sending of an Email. Add or reconfigure a button to activate V27. Make sure it’s a Push button.

Button widget settings

Blynk Run

After running the project, tap into the Terminal input box. Type an exclamation point (!), then type your (or a friend’s) email address. Hit enter, and the Blynk Board should respond with a message verifying the email address you entered.

Emails sent

Now all that’s left is to tap the “Send Email!” button, and check your inbox. A status update should be dispatched to your inbox.

Example emails

Don’t go mashing on the “Send Email!” button, now. The Email widget is limited to sending at most one email a minute. If you’re too trigger-happy, the Terminal will let you know when you can next send an email.

Resources & Going Further

Finished all the projects? Wondering where you go from here? Now that you’re a professional Blynker, consider re-programming the Blynk Board to create a unique project of your own! Check out our Programming the Blynk Board in Arduino tutorial to find out how to level up your Blynking!

New!

Blynk Board Arduino Development Guide

March 25, 2016

How to get your computer set up with Arduino and the Blynk Board hardware definitions -- so you can start creating Blynk projects of your own!

Or, if you’re looking for more general Blynk Board or Blynk App resources, these may help:


If you need any technical assistance with your Blynk Board, don’t hesitate to contact our technical support team via either e-mail, chat, or phone.


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

Blynk Board Bridge Widget Demo

$
0
0

Blynk Board Bridge Widget Demo a learn.sparkfun.com tutorial

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

Introduction

The Bridge Widget available in the Blynk app allows for Device-to-Device communication. No app is required to be running. This demo shows a few ways the Bridge widget can be used for app to app communications, app to board communications, and board to board communications.

For full functionality two mobile devices and two SparkFun Blynk Boards are required. If you aren’t interested in app to app communications, only one mobile device will be required. Mobile devices can be running Android or iOS.

Hardware Hookup

No need to futz with extra hardware to prove concepts. You software people out there might appreciate this. Once you have the built in button controlling the built in LED, it’s a simple matter of changing one or two values and clipping on extra hardware.

For this tutorial all you need to do is provide power the the Bylnk Boards. This is easiest two ways; USB, or a 4.2V LiPo battery (1S).

SparkFun Blynk Board powered with a single cell LiPo battery

SparkFun Blynk Board powered with a single cell LiPo battery

Powering the device with a USB cable connected to your development machine is the easiest way to prototype. Load new code and it just runs.

alt text

SparkFun Blynk Board powered with a USB micro-B cable

Mobile Apps

To create a mobile app first make sure you have the mobile app. If you don’t please install the version for your OS from one of these two sources:

AS_link
GP_link

Exact instructions are beyond the scope of this tutorial. Once you have the app installed, login, or create a new account.

Bylink app login screen

Bylink app login screen

Once you have logged in select the large Create New Project button.

Empty Blynk project

Empty Blynk project

This will bring you to where you get to name the project, select the hardware that you will be connecting to, and get your authentication token. This token (7DF0F1DE119F48149EFF64BC7B2FBD11 in this example) will be very important later on. I find that emailing it to myself is easier than typing it out. It will be sent to the email account that you registered with when you created your account.

Default project settings

Default project settings

I gave my project a name that matches the sketch designed to work with it. This is unnecessary, but helps keep confusion to a minimum. Once you select some SparkFun hardware you will note that the theme changes.

Configured project

Configured project

Select the CREATE PROJECT option to create and open the project.

Empty project

Empty project

Now that you have an empty project canvas to work with it’s time to start adding UI elements. Let’s start with the Terminal widget. You find this by double tapping the canvas and scrolling the sidebar until you see the widget of interest.

Terminal widget in Widget Box

Terminal widget in Widget Box

Select the widget and the Widget Box will close and the widget will appear in the next available slot on the canvas.

Placed terminal widget

Placed terminal widget

Now that you have a terminal widget in place find the button widget in the Widget Box.

Button widget the Widget Box

Button widget the Widget Box

Follow the same procedure to place the Bridge widget. It can be found in the other section of the Widget Box at the bottom.

Bridge widget placed

Bridge widget placed

Once all of the widgets are placed (or one by one) it’s time to configure the widgets. Let’s start by configuring the Terminal widget. Give it a name/label. It doesn’t matter what cAsE you enter it in, it will be converted to upper CASE.

Labeling Terminal widget

Labeling Terminal widget

In order to interact with a widget you need to assign a pin to it. Some widgets use real, physical pins, while others use virtual pins. All of the UI in this example uses virtual pins. In this case I’ve chosen to connect the terminal to virtual pin 0. I left the other settings for the Terminal widget at their default values.

Configured Terminal widget

Configured Terminal widget

The procedure is the same for the Button widgets as it is for the Termial widget. Give them names/labels, and select a pin to communicate through. I think case I’m using virtual pin zero to control the local LED connected to GP5. The reason for using a virtual pin rather than a physical pin will be explained in the firmware section.

Configured Button widget

Configured Button widget to control the local LED

You may note that in the image above I’ve also changed the button from PUSH (momentary) to SWITCH (latching). For now please follow along. The other configuration options for Button widgets control to color. That wasn’t important to this demo and I left the defaults. Here is what the finished app should look like:

Bridge example device 1 setup

Bridge example device 1 setup

When the triangle in the upper-right corner is pressed, the app will run and the details of the wiring are hidden from the user.

Bridge example device 1 running

Bridge example device 1 running

Firmware

The firmware for this demo is Arduino code. For detailed information on getting the Blynk libraries installed and your development environment configured, please see to Arduino development guide.

Configuration

One major way that the firmware for this demo differs from that in ‘standard’ Blynk firmware is that you need a second authentication code.

language:c
char auth[] = "7DF0F1DE119F48149EFF64BC7B2FBD11"; // Put your Auth Token here
char remoteAuth[] = "RemoteAuthToken"; // Auth token of bridged device

To get this second auth code you need a second project on your mobile device, or for the chat to also work, you will want to start the second project on a second mobile device logged into with the same account. Once you have the second project for a secondary Blynk Board that token can be entered as the remoteAuth for the primary Blynk Board. These two lines are the only differences between Bridge_Example_1.ino and Bridge_Example_2.ino. Two were created as a convenient way keep the confusion low and to make tweaks to one, but not both easier.

The next section to configure is the section of aliases used to tell the body of the code which virtual pin was chosen in the app. These don’t need to be changed if you followed along in the previous section on the mobile app configuration. In both the code and in the mobile app we have the local LED button mapped to virtual pin 1 (V1). We have configured the second button labeled REMT LED in the app to use virtual pin 2 (V2), so here in the code we defined an alias REMOTE_LED_BUTTON for V2. This section allows us to use the exact same code for many bridged devices.

language:c
// Virtual Pins:
#define TERMINAL                 0  // V0
#define LOCAL_LED_BUTTON         1  // V1
#define REMOTE_LED_BUTTON        2  // V2
#define TERMINAL_RECEIVE         3  // V3
#define BRIDGE                   4  // V4
#define LOCAL_LED_RECIEVE        5  // V5
#define REMOTE_LED_STATUS_UPDATE 6  // V6

The final configuration needed is to tell the Blynk Board how to connect to the Wi-Fi®. Replace SSID with the SSID (the name of your Wi-Fi® network) leaving the double quotes. Also replace PASSWORD with the actual password for your network; again leaving the double quotes.

language:c
Blynk.begin(auth, "SSID", "PASSWORD");  // Here your Arduino connects to the Blynk Cloud.

How it works

Physical button

Let’s start with the physical button on the Blynk Board. This button will be used to toggle the LED on the other Blynk Board.

This button connects GPIO0 to ground when pressed. This is called active low; the signal goes low, when the button is pressed/active. An internal pull-up resistor is used to keep this signal high when inactive. An interrupt service routine is used to immediately capture the button press event, but the resulting action isn’t taken until the main loop of the code gets around to doing it. This keeps more important things running fast. Here is the code snippet to configure what was just described.

language:c
// Setup the onboard button
pinMode(BUTTON_PIN, INPUT_PULLUP);
// Attach BUTTON_PIN interrupt to our handler
attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), onButtonPress, FALLING);

The second parameter to the attachInterrupt function call is the name of the interrupt service handler, onButtonPress.

language:c
// Interrupt service routine to capture button press event
void onButtonPress()
{
  // Invert state, since button is "Active LOW"
  wasButtonPressed = !digitalRead(BUTTON_PIN);
}

This function is called when the physical button is pressed. Since the processor may be in the middle of doing something with more critical timing, this function does as little as possible, and the even is dealt with later. Here we have a variable wasButtonPressed that keeps track of whether or not the button was pressed. We store the opposite of the current state of the pin in this variable. The opposite is obtained with the ! operator. We read this pin a second time as a form of debouncing. A real button press should send the value of that pin low, and it should remain low at least the fraction of a second it takes to jump to this function and double check the state. This avoids changing state based on fast transient glitches.

Next let’s discuss the main loop:

language:c
void loop()
{
  Blynk.run(); // All the Blynk Magic happens here...

  if (wasButtonPressed) {
    // This can be seen in the Serial Monitor
    BLYNK_LOG("Physical button was pressed.");
    // Toggle state
    remoteLedState ^= HIGH;
    // Send new state to remote board LED
    bridge.virtualWrite(LOCAL_LED_RECIEVE, remoteLedState);
    // Update state of button on local mobile app
    Blynk.virtualWrite(REMOTE_LED_BUTTON, remoteLedState);
    // Clear state variable set in ISR
    wasButtonPressed = false;
  }
}

Two things happen here. First we let the Blynk library do its thing. Next we check to see if the physical button was pressed. If the button had been pressed since the last time this check was run, we have a few things to do.

First, if the Blynk Board is connected via a micro USB cable to a computer running a terminal emulator or the Arduino Serial Monitor, we write a debug message to that at 9600 baud. This is done with BLYNK_LOG("Physical button was pressed.");. This code can be compiled out if the first line of actual code in the sketch is removed or commented out (#define BLYNK_PRINT Serial).

Next a state variable keeping track of the state of the remote LED is toggled. This is done with remoteLedState ^= HIGH; but could also be done with something like remoteLedState = 1 - remoteLedState;, or remoteLedState = !remoteLedState;.

Next we send the new state across the bridge doing a virtual write to the remote LOCAL_LED_RECIEVE virtual pin. On the other end is a function that handles the value sent.

After we have told the remote devices to update we need to update the state on the mobile app attached to this Blynk Board. We do this with a virtual write to the REMOTE_LED_BUTTON with the new state value.

The final thing to do is clear the variable that indicates we have an unhandled button press, wasButtonPressed. This causes the code block we are in to be skipped until the button is pressed again.

To follow along to logical flow of a physical button press, let’s cover the function that handles when another device signals that its button has been pressed:

language:c
// Remote device triggered an LED change. Update the LED and app status.
BLYNK_WRITE(LOCAL_LED_RECIEVE)
{
  // This can be seen in the Serial Monitor
  BLYNK_LOG("Remote device triggered LED change");

  ledState = param.asInt();
  // Turn on LED
  digitalWrite(LED_PIN, ledState);
  // Set state of virtual button to match remote LED
  Blynk.virtualWrite(LOCAL_LED_BUTTON, ledState);
}

The new or important items found in this function are the digitalWrite and the virtualWrite. After updating the state of the LED, this value is sent to the GPIO connected to the LED. We then update the UI on the mobile app associated with this board.

The previous code block handled updating the GUI associated with the board that had the button pressed, and this block update the physical LED, and the GUI associated with the board with the LED that changed. One virtual button press updated a physical pin, and two GUI elements.

LED button in the mobile app GUI

When the button labeled LED is pressed the following function is called. The first bit is nothing new, we update the state variable, log this info via a serial connection if it exists.

language:c
// Virtual button on connected app was used to change remote LED.
// Tell remote devices about the change.
BLYNK_WRITE(REMOTE_LED_BUTTON)
{
  remoteLedState = param.asInt(); // Update state with info from remote
  BLYNK_LOG("New remote LED state: %s", param.asInt() ? "HIGH" : "LOW");
  // Send updated status to remote board.
  bridge.virtualWrite(LOCAL_LED_RECIEVE, remoteLedState);
}

The last statement in this function sends the remoteLedStat to the other Bkynk Board’s LOCAL_LED_RECEIVE virtual pin over the bridge. The bridge was configured in this line:

language:c
WidgetBridge bridge(BRIDGE);

BRIDGE was defined earlier in the code to be virtual pin 4.

The other end of the bridge reacts to this signal with the following function. Nothing new to see here, we log via the serial port if it exists, update the state variable, update the physical pin, and finally update the state of the GUI.

language:c
// Remote device triggered an LED change. Update the LED and app status.
BLYNK_WRITE(LOCAL_LED_RECIEVE)
{
  // This can be seen in the Serial Monitor
  BLYNK_LOG("Remote device triggered LED change");

  ledState = param.asInt();
  // Turn on LED
  digitalWrite(LED_PIN, ledState);
  // Set state of virtual button to match remote LED
  Blynk.virtualWrite(LOCAL_LED_BUTTON, ledState);
}

Remote LED button in the mobile app GUI

The remote LED button in the mobile app GUI behaves roughly the same as the LED button. In this case the button is labeled REMT LED. It uses the following functions. This first is called when the button in the app is pressed.

language:c
// Virtual button on connected app was used to change remote LED.
// Tell remote devices about the change.
BLYNK_WRITE(REMOTE_LED_BUTTON)
{
  remoteLedState = param.asInt(); // Update state with info from remote
  BLYNK_LOG("New remote LED state: %s", param.asInt() ? "HIGH" : "LOW");
  // Send updated status to remote board.
  bridge.virtualWrite(LOCAL_LED_RECIEVE, remoteLedState);
}

That function sends a signal handled on the other end of the bridge handled with the following function.

language:c
// Remote device triggered an LED change. Update the LED and app status.
BLYNK_WRITE(LOCAL_LED_RECIEVE)
{
  // This can be seen in the Serial Monitor
  BLYNK_LOG("Remote device triggered LED change");

  ledState = param.asInt();
  // Turn on LED
  digitalWrite(LED_PIN, ledState);
  // Set state of virtual button to match remote LED
  Blynk.virtualWrite(LOCAL_LED_BUTTON, ledState);
}

Inter-device chat window

Another part of this demo is sending text over the bridge. Alone this isn’t the most amazing use of the technology, but in the case of an Internet outage a local Blynk Server and a Wi-Fi® router could be setup for a phone to phone chat service.

The first requirement is to setup a Terminal widget to go with the one added in the mobile app.

language:c
// Attach virtual serial terminal to TERMINAL Virtual Pin
WidgetTerminal terminal(TERMINAL);

Next a function takes the output of this widget and sends it to another Blynk Board.

language:c
// You can send commands from Terminal to your hardware. Just use
// the same Virtual Pin as your Terminal Widget
BLYNK_WRITE(TERMINAL)
{
  // Send from this terminal to remote terminal
  bridge.virtualWrite(TERMINAL_RECEIVE, param.asStr());
}

On the other side of the bridge is the following function that takes the received string and writes it to the local terminal.

language:c
// Receive a string on LOCAL_RECEIVE and write that value to the connected
// phone's terminal
BLYNK_WRITE(TERMINAL_RECEIVE)
{
  terminal.println(param.asStr());  // Write received string to local terminal
  terminal.flush();
}

Example of chat functionality

Example of chat functionality

Resources and Going Further

In this demo we used 7 virtual pins. Three of them were used to send various types of data. If your project became more complex and you ran out of virtual pins, you could send all of the data over one by encoding information on one end and decoding it on the other.

This demo was aimed a little more at the software inclined user since it required no extra hardware. It used the built in buttons and LEDs. This could easily be modified to use other pins with whatever you want to connect to them. The button on one end could be replaced with a SparkFun Sound Detector, and the LED on the other Blynk Board could be replaced with SparkFun Beefcake Relay Control Kit. This would allow you to make your own Wi-Fi® version of The Clapper. Clap in one room to turn on/off a lamp on another house!

Related tutorials:


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

Getting Started with the SparkFun Blynk Board

$
0
0

Getting Started with the SparkFun Blynk Board a learn.sparkfun.com tutorial

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

Introduction

The SparkFun Blynk Board – ESP8266 is your hardware gateway to the app-controlled wonderland that is Blynk. Combining the Blynk Board with the Blynk app (on your iOS or Android device), will allow you to control LEDs from your phone, send a tweet when it’s time to water your plants, monitor local weather conditions, and much more!

Blynk Board and app action shot

This tutorial will explain how to get your Blynk Board connected to a local Wi-Fi network – in a process called provisioningand connected to a project within the Blynk app. Once you’ve completed the tutorial, you’ll have already created your first project: a zebra-controlled multicolored LED (it’ll make sense when you see it).

Gather the Gear

To follow along with this tutorial, you’ll need the following physical and digital goods:

SparkFun Blynk Board – ESP8266– The Blynk Board comes fully programmed – ready to start Blynking. All you need to do is connect it to Wi-Fi and your Blynk account.

SparkFun Blynk Board - ESP8266

WRL-13794
$29.95

The Blynk Board also includes a Blynk Subscription code card, which you’ll need to connect the Blynk Board to your Blynk account (and to charge it up!).

Micro-B USB Cable– The Blynk Board can be powered via a USB cable connected on the other end to either a computer, laptop, or USB wall adapter.

USB microB Cable - 6 Foot

CAB-10215
$4.95
6
Wall Adapter Power Supply - 5V DC 2A (USB Micro-B)

TOL-12890
$5.95
9
Wall Charger - 5V USB (1A)

TOL-11456
$3.95
2
USB Micro-B Cable - 6"

CAB-13244
$1.95
3

Powering the Blynk Board with Lithium-Polymer Batteries

The Blynk Board is equipped with LiPo battery support for truly wireless Blynking. The 2-pin, white JST connector adjacent to the USB port, mates with a variety of SparkFun LiPo batteries. The batteries are available in a range of capacities, but we recommend either the 400mAh, 850mAh, or 1000mAh varieties.

A USB cable is still recommended – it's used to charge the battery. But once you find a Blynk project that requires your board not be tied down to a wall or computer, definitely consider equipping it with a battery.

Blynk App– The Blynk smartphone app comes in two flavors: iOS and Android. Before going any further, download the app to your smart device:

AS_link
GP_link

Blynk app in action

The Blynk app is compatible with iDevices running iOS 7.0+, and Android’s running any version above or equal to 4.0.

Local Internet-Connected Wireless (Wi-Fi) Network– The Blynk Board is equipped with Wi-Fi support, and should be able to connect to most home wireless networks: 2.4GHz Wi-Fi networks, that are either open (no password) or protected with WPA, WPA-2, or WEP authentication.

alt text

Note that the Blynk Board cannot connect the 5GHz band of a dual-band Wi-Fi router. If your Wi-Fi router has two visible options, like HOME-AB12-2.4 and HOME-AB12-5, connect the Blynk Board to the “2.4” option.

Powering Up the Blynk Board

Once you’ve gathered all of the materials from above, it’s time to power up the Blynk Board! Grab your USB Cable, plug one end into a computer or USB wall adapter, and plug the other into the Blynk Board.

Blynk Board plugged in, powered, LEDs on

Blynk Board plugged in, PWR LED (in the upper-left of this image) is illuminated

You should immediately see the small, red “PWR” LED illuminate, followed shortly thereafter by a random-looking blinking of the large, RGB LED.

Identifying Your Blynk Board

While the Blynk Board’s RGB blinking may look random at first, it will follow a repeating pattern – a unique sequence of four colors including either red, green, blue, purple, or yellow, with a long stop in between. This color-code will help identify your board, just in case you’re not the only one in town setting up a Blynk Board.

Four characters matching that color code will be added to the name of your Blynk Board. For example, if the RGB LED is blinking a pattern of blue, green, red, green..

Blynk Board blinking blue, green, red, green

…the Blynk Board name will be BlynkMe-BGRG.

The table below documents which color matches which character.

ColorBlynk Name Character
RedR
GreenG
BlueB
PurpleP
YellowY

That’s not all the RGB LED does though!

RGB Status Codes

During setup, the RGB LED on the Blynk Board will be your window into its soul. The board uses this multi-colored LED to indicate all sorts of status modes. If you’re ever unclear of what the RGB color-code means, consult the table below:

RGB ColorBlink SpeedStatusNotes
PurpleMedium (2Hz)Device connected to Blynk BoardVerifies that your phone (or possibly someone else's) is connected to the Blynk Board.
BlueFast (4Hz)Connecting to Wi-Fi networkAfter sending it the info, the Blynk Board will attempt to connect to your Wi-Fi network for up to 30 seconds.
Blynk GreenSlow (1Hz)Connecting to Blynk CloudAfter connecting to your Wi-Fi network, the Blynk Board will establish a connection with the Blynk server.
Blynk GreenSmoothly fading in/outConnected to BlynkAfter successfully connecting to Wi-Fi and Blynk, this is the sign that everything is working! The LED will continue to "breathe" until you tell it to do something else.
YellowSlow (1Hz)Re-connecting to BlynkConnection issues should resolve themselves, but the Blynk board will likely be unresponsive while blinking yellow. If it continues to Blynk yellow for over a minute, try cycling power to the Blynk Board.
WhiteMedium (2Hz)Blynk Board waiting for configIf your Blynk Board was unable to connect to either Wi-Fi or Blynk, it'll sit in this mode – waiting for you to press a button. More on this in the Reconfiguring a Blynk Board section

Provisioning the Blynk Board

In order to connect the Blynk Board to your local Wi-Fi network – and the Blynk app – you’ll need to send it a few pieces of information, including the name and password of your Wi-Fi network. This is a process called provisioning.

Provisioning?

In the provisioning process, we'll use a smartphone, laptop, or computer to connect to directly (over Wi-Fi) to the Blynk Board. Once connected, your smart-device will send the necessary data and tell the Blynk Board to go connect to your Internet-connected wireless network and Blynk.

The Blynk Board is initially configured to operate as a Wi-Fi access point (abbreviated "AP", kind of like a router). A smartphone or Wi-Fi-enabled computer can briefly connect to the Blynk Board, and, using either the Blynk app or a browser, send all of the necessary information over to it. After the Blynk Board receives that info, it'll transition from AP to Wi-Fi device and connect to your Wi-Fi network.

The Blynk Board has plenty of backup provisioning options, but the easiest method is through the Blynk app. Both iOS and Android versions of the Blynk app support Blynk Board provisioning. All you’ll need is the Blynk QR-Code Card, included with your Blynk Board.

Blynk QR Code Card

Don't Throw Away Your Blynk QR-Code Card!

Although you'll only be able to benefit from the 15,000 energy points once, the QR-Code card can be used to re-provision your Blynk Board, should the need ever arise. We recommend you keep it hand, for now, just in case!

Provisioning on a Smartphone (or Tablet)

The setup process in each OS looks and feels a little different. Select one of the sections below to get directions for your phone (or tablet) OS.

iOS Provisioning

If you haven’t already, download the Blynk App from the App store. Then open it, create an account and log in.

If you already have the Blynk app installed on your phone, make sure it’s updated to the latest release!

Step 1: Scan the Blynk Board QR Code

Click the QR-code icon in the top-right corner of the Blynk app.

Select QR icon

Then scan your phone camera over the QR code on your Blynk Board card. Blynk should pop up a new screen – congrats, you’ve got some new Blynk energy to play with!

Blynk congrats

Step 2: Connect to the Blynk Board

From the “Congrats!” page, hit Set Up New Device, read through the "Pre-Flight Checklist", and – as long as your Blynk Board is powered up and blinking the unique color code – hit Continue.

Read through the "Connect to Device" screen, and hit Open Wi-Fi Settings to swap over to your iDevice’s Wi-Fi settings.

You may have to wait a few seconds for your device to scan for networks, but you should eventually see a Wi-Fi network named BlynkMe-CCCC. If that color code matches your Blynk Board’s pattern, select that network.

The connecting process may take up to a minute to complete – eventually, though, you should see a checkmark next to the BlynkMe network. The Blynk Board will begin to blink purple– faster than before – when a device has connected to it.

Blynk Board connected

The Blynk app may (or may not) pop up a notification indicating it has sensed a connection to a BlynkMe network. If so, hit open. If the notification isn’t popping up, but you have a checkmark next to the BlynkMe network, hit Back to Blynk in the upper-left corner.

Step 3: Connect the Blynk Board to Wi-Fi/Blynk

On the next screen, enter the name and password of your Wi-Fi network. While typing the password, hit the eye icon (eyecon?) if you want/need to show your password.

Enter the Wi-Fi name and password

After typing both your network name and password in exactly (both fields are case-sensitive, and be careful not to add any spaces at the end), hit continue.

Step 4: Monitor the Blynk Board's RGB LED

While it connects to Wi-Fi and Blynk, the Blynk Board will use the RGB LED to keep you informed on its progress.

After hitting "Continue", your Blynk Board should begin to blink blue, which indicates it’s attempting to connect to your Wi-Fi network. This process usually takes around 10 seconds, but if it still hasn’t connected after 30 seconds, it will give up and go back to setup mode.

If the provisioning process isn't going as planned – whether it's failing to connect to Wi-Fi or Blynk – try cycling power to your Blynk Board (unplug and re-plug the USB cable in), and starting from the beginning.

If you're still not having any luck provisioning through the app, you may have to use an alternative provisioning process.

After the Blynk Board successfully connects to your Wi-Fi network, it will establish a connection with the Blynk Cloud. During this process, it will blink a soft, Blynk-colored green.

Finally, after a successful Blynk cloud connection, you should see the “Finished!” page. The RGB should be smoothly fading in-and-out. If so, click Done and Blynk will take you to a fresh Blynk Board project. Head over to the Do the zeRGBa section of this tutorial to start Blynking!

Blynk connect success

If you had trouble provisioning your Blynk Board, try giving the whole process one more shot. Cycle power to your Blynk Board, by unplugging it and plugging it back in. Then try again from step 1.

If you're still not having any luck, consult the Troubleshooting section of this tutorial.

Android Provisioning

If you haven’t already, download the Blynk App from the Google Play store. Then open it, create an account and log in.

Or, if you already have the Blynk app installed on your phone, make sure it’s updated to the latest release!

Step 1: Scan the Blynk Board QR Code

Click the QR-code icon in the top-right corner of the Blynk app (or the bigger icon on the main screen).

Android QR code button

Then scan your phone over the QR code on your Blynk Board card. Blynk should pop up a new screen – congrats, you’ve got some new Blynk energy to play with!

Android welcome screen

Step 2: Connect to the Blynk Board

From the “Congrats!” page, hit Set Up New Device, read through the Pre-flight checklist and – as long as your Blynk Board is powered up and blinking the unique color code – hit Continue.

This next page is where you’ll select your Blynk Board. Scroll through the device list and select a network named BlynkMe-CCCC (one may already be selected). Make sure that color code suffix matches your Blynk Board’s RGB LED blinking.

Select a Blynk Board

Hit Continue. The app should attempt to connect to your Blynk Board. After a few seconds you should see the Blynk Board’s RGB LED blink purple– faster than before – and the app should present you with a “Connected to BlynkMe” page.

Blynk Board connected

From there hit Continue to proceed to the Wi-Fi provisioning.

Step 3: Connect the Blynk Board to Wi-Fi/Blynk

On the next screen, select your Wi-Fi network from the scroll bar. Then enter your network’s password.

Enter the Wi-Fi configuration

After both network and password are correctly entered (both fields are case-sensitive! be careful not to add any spaces at the end), hit continue.

Step 4: Monitor the Blynk Board's RGB LED

While it connects to Wi-Fi and Blynk, the Blynk Board will use the RGB LED to keep you informed on its progress.

Your Blynk Board will begin to blink blue, which indicates it’s attempting to connect to your Wi-Fi network. This process usually takes around 10 seconds, if it still hasn’t connected after 30 seconds, it will give up and go back to setup mode.

If the provisioning process isn't going as planned – whether it's failing to connect to Wi-Fi or Blynk – try cycling power to your Blynk Board (unplug and re-plug the USB cable in), and starting from the beginning.

If you're still not having any luck provisioning through the app, you may have to use an alternative provisioning process.

After the Blynk Board successfully connects to your Wi-Fi network, it will establish a connection with the Blynk Cloud. During this process it will blink a soft, Blynk-colored green.

After a successful Blynk cloud connection, you should see the “Finished!” page. And the RGB should be smoothly fading in-and-out.

Blynk Board configuration finished

From there, click Done and Blynk will take you to a fresh Blynk Board project. Head over to the Do the zeRGBa section of this tutorial to start Blynking!

If you had trouble provisioning your Blynk Board, try giving the whole process one more shot. Cycle power to your Blynk Board, by unplugging it and plugging it back in. Then try again from step 1.

If you're still not having any luck, consult the Troubleshooting section of this tutorial.

Do the zeRGBa

Once you’ve connected the Blynk Board to a local Wi-Fi network – and connected it to your Blynk account – the Blynk app should present you with a nearly blank canvas of a Blynk project.

You should be greeted by a festively colored zebra – the zeRGBa– and an LCD widget with a rather helpful link.

Blynk Board default Blynk project - zeRGBa and LCD

Your first Blynk project should be all set up to communicate with the Blynk Board. It should also already be running, meaning it’s play time! Poke and prod the zeRGBa to select a new color – you should quickly see a physical manifestation of that color on the Blynk Board.

zeRGBa setting the Blynk Board's LED to purple!

If your zeRGBa isn’t making LEDs blink, first make sure the project is running. The icon in the upper-right corner of the app should be a square “stop” button. If it’s a triangular “play” button, tap that to run the project.

Caution: As tempting as it may be to perform a hypnotic light show, dragging your finger along the zeRGBa may cause the Blynk Board and Blynk App to occassionaly "lag out." If the Blynk Board is slow to update the RGB's color, wait a couple seconds for it to re-connect.

To avoid this occasional connection-drop, try "poking" at your zeRGBa color of choice.

Congratulations! You’re well on-your-way to being a professional Blynker. From here we recommend you visit the Blynk Board Project Guide to explore over a dozen Blynk projects built into the Blynk Board.

New!

Blynk Board Project Guide

March 25, 2016

A series of Blynk projects you can set up on the Blynk Board without ever re-programming it.

Or, you may want to check out some of these other Blynk-related tutorials:

New!

Blynk Board Bridge Widget Demo

A Blynk project that demonstrates how to use the Bridge widget to get two (or more) Blynk Boards to communicate.
New!

Blynk Board Arduino Development Guide

How to get your computer set up with Arduino and the Blynk Board hardware definitions -- so you can start creating Blynk projects of your own!

Troubleshooting

If, for any reason, you can’t successfully provision the Blynk Board through the Blynk app, you have a few alternatives. But first, you’ll need to create a new Blynk project.

Creating a Blynk Project

Each of the alternative provisioning methods below will require a Blynk project to be previously created. The new Blynk project will be assigned a Blynk auth token– a 32-character, unique string, which connects the Blynk Board to your Blynk project. That’s what we’re after in this process.

Follow these steps to create a new Blynk project and get a new auth token:

Step 1: Create a Blynk Project

Open the Blynk app, and log in if you haven’t. Make sure your phone is connected to an Internet-connected Wi-Fi network. On the Blynk main page, select Create new project.

Create a Blynk Project

Create a new Blynk Project by tapping “Create New Project” on the Blynk main page.

Step 2: Configure the Blynk Project

On the next page, select SparkFun Blynk Board under the “Hardware Model” list. You can give the project any name you please – the provisioning process sets it to “BlynkMe”.

Configure the new project

Configure a new project: name it, and set the board type to “SparkFun Blynk Board.”

Do not hit Create Project yet!

Step 3: Email and Copy the Auth Token

Depending on which alternative provisioning option you choose, you’ll either need the auth token copied to your phone’s clipboard, or sitting in your email inbox. Might as well do both while we’re here!

Email and copy the auth token

Tap the E-Mail button to send the auth token to your Blynk-connected email account. Then tap the Auth token itself to copy the string to your phone’s clipboard. The phone should pop up a notification confirming that the token was copied.

Step 4: Create Project

Finally, with the token emailed and copied, click Create or Create Project. You should be brought to a new, blank project – perfect for now!

Alternative Provisioning

There are a few options available for alternatively provisioning the Blynk board. In order of our recommendation, you can:

  1. Connect the Blynk Board to Wi-Fi/Blynk using a laptop or Wi-Fi-enabled computer.
  2. Configure the Blynk Board through a serial terminal on a computer connected over USB to the Blynk Board.
  3. Creatively use copy/paste, and app-switching on your smartphone to provision the Blynk Board.

Click one of the links below to see how.

Option 1: Laptop/Computer, Browser-Based Provisioning

If the Blynk app isn’t correctly provisioning your Blynk Board and you have a computer with Wi-Fi capability nearby, you can use your computer and smartphone to join forces to get your Blynk Board configured. Just follow these steps:

Step 1: Get the Auth Token From Your E-Mail Inbox

Make sure you've followed the steps from above – created a project, and emailed the auth token to yourself. Then open your email on your computer and copy the auth token– either to your clipboard or a simple text editor.

Create a new project in the Blynk app

Check your email, and copy the Auth token.

Step 2: Connect to Your Computer to the Blynk Board’s Wi-Fi Network

Find your computer’s Wi-Fi settings, and have it scan for nearby Wi-Fi networks. You should see something that starts with BlynkMe-. The last four characters should match the four-color sequence your board is blinking.

Create a new project in the Blynk app

Connect your computer to the BlynkMe Wi-Fi network.

Select the “BlynkMe-CCCC” network to connect your computer to it. On successful connection your Blynk Board should begin to blink purple.

Step 3: Point a Web Browser to 192.168.4.1

Open Safari, Chrome, Firefox, Edge, or whatever your favorite web browser may be, and navigate to 192.168.4.1 (that link will only work on a device connected to the Blynk Board).

After a couple seconds, the Blynk Board should serve up the Blynk Board Config Page. It may take a couple of tries to load the page; if your browser says “Failed to load webpage,” or something to that effect, try refreshing.

Step 4: Send your Wi-Fi Network and Blynk Auth Token

The config page will present a list of visible Wi-Fi networks within range. If you see your network on there, great! Select that. If your network is hidden, scroll down to “[Enter manually …]”, and type it in yourself.

Next enter the password for your Wi-Fi network. If it’s an open network (no password), leave the box blank.

Finally, paste the auth token into the Blynk auth token box. This process varies by phone, either a light tap (iOS) or a tap-and-hold should bring up the paste option.

Create a new project in the Blynk app

Unless you’re connecting to the Blynk Board to a custom server (which you’re most likely not), leave the Blynk host and port entries as-is.

Now click Apply.

Step 5: Monitor the Blynk Board

After hitting apply, the Blynk Board should begin to blink blue as it attempts to connect to your Wi-Fi network.

If that’s successful, it’ll begin to blink Blynk-green while it establishes a connection with the Blynk server.

Once both parties are happy, the Blynk Board’s RGB LED should “breathe” Blynk-green, fading in-and-out, in-and-out. That’s a great sign! Swap back to your phone, open the Blynk app and we’ll set up a zeRGBa.

If that didn't work, go back to the provisioning options, and try something else. Or consider getting in touch with our technical support team.

Option 2: Serial Terminal Over a USB-Connected Computer/Laptop

If Wi-Fi-based commissioning doesn't seem to be working out, you can provision the board over a hard-wire – and get a little debug info at the same time – using a serial terminal. In order to use the serial terminal method, you’ll need:

  1. The Blynk Board connected over USB to a computer or laptop
  2. FTDI drivers installed on your computer
  3. Serial terminal software

Step 1: Install FTDI Drivers

The Blynk Board uses a specialized chip called an “FTDI” to convert USB data to a more simple serial interface. If you’ve never used an FTDI-based device before, you’ll probably need to install drivers on your computer. Our How to Install FTDI Drivers tutorial should help get your drivers installed, whether you’re on a Mac, Windows, or Linux machine.

Install FTDI Drivers

Once you’ve installed the drivers, your Blynk Board should show up on your computer as either COM# (if you’re on a Windows machine) or /dev/tty.usbserial-######## (if you’re on a Mac/Linux computer), where the #’s are unique numbers or alphabetic characters.

Step 2: Select, Download, Install, Run Terminal Software

There are many, many software variants on the serial terminal out there. If you don’t already have one, read through our Serial Terminal Basics tutorial for some suggestions.

Download a Terminal

Step 3: Configure the Serial Terminal Settings, Open the Connection

Once you’ve selected terminal software – and found your Blynk Board’s serial port number – open it and set the baud rate to 9600.

serial terminal settings

Using TeraTerm to communicate with the Blynk Board over a serial interface on COM3.

After opening the terminal connecting press 'h' to print a help menu. This will also confirm that your Blynk Board and terminal are talking to each other.

terminal help message

Don't be alarmed if your Blynk Board prints messages before that help message. The board is configured to print a few handy debug messages at startup.

Step 4: Configure Wi-Fi

There are four single-character commands available for configuring the Blynk Board’s Wi-Fi network, password, and Blynk token. Typing any of these characters will initiate the command:

  • h– Prints a help menu.
  • s– Scan for Wi-Fi networks, and select from a list of visible networks.
  • w– Manually enter a Wi-Fi network.
  • b– Initiates Blynk Token configuration.

Press ’s' in the terminal to scan for Wi-Fi networks and begin configuration. After a couple seconds, you should be presented with a list of visible Wi-Fi networks.

scan for networks

If you see your Wi-Fi network, type the number or letter next to which it’s listed. If you don’t see the network – or if it’s supposed to be hidden – hit 0 to type it in manually.

Following the network selection, the configuration tool will immediately ask you for the Wi-Fi network password– type that in, and hit enter. If you’re Wi-Fi network is open, just hit enter, leaving the password blank.

Step 5: Configure Blynk

After following the "Create a Blynk Project" directions, you should have an email sitting in your inbox containing your Blynk project's auth token. Load up your e-mail, and copy that auth token to your computer's clipboard.

scan for networks

Once you have the token copied to your clipboard, type ‘b’ to enter Blynk Auth Token config mode. Then paste your token in, and hit enter. Terminal programs all deal with copying/pasting differently, but you usually can’t go wrong with Edit > Paste.

Blynk auth token configuration

Step 6: Monitor the Blynk Board

After sending over your Wi-Fi and Blynk credentials, the Blynk Board should begin to blink blue as it attempts to connect to your Wi-Fi network.

If that’s successful, it’ll begin to blink Blynk-green while it establishes a connection with the Blynk server.

Once both parties are happy, the Blynk Board’s RGB LED should “breathe” Blynk-green, fading in-and-out, in-and-out. That’s a great sign! Swap back to your phone, open the Blynk app and we’ll set up a zeRGBa.

If that didn't work, go back to the provisioning options, and try something else. Or consider getting in touch with our technical support team.

Option 3: Smartphone Browser-Based Provisioning

If the Blynk app isn’t correctly provisioning your Blynk Board, you can still use your phone to go about the process manually. Follow these steps to manually set up your Blynk Board:

From the "Create a Blynk Project" directions above, you should have a 32-character Blynk auth token copied to your phone's clipboard. Make sure you do before proceeding – you'll be cut off from the Internet for the next few steps.

Step 1: Connect Your Phone to the Blynk Board’s Wi-Fi Network

Temporarily jump out of the Blynk app, and find your phone’s Wi-Fi settings. On an iOS device, this will be the “Wi-Fi” entry under the Settings app. On an Android, it should be in the Wi-Fi section of the phone's settings.

Have your phone scan for Wi-Fi networks, and look for something that starts with BlynkMe-. The last four characters should match the four-color sequence your board is blinking.

Connect your phone to the “BlynkMe-CCCC” network. Upon a successful connection, your Blynk Board should begin to blink purple.

Step 2: Point a Web Browser to 192.168.4.1

Open Safari, Chrome, Firefox, “Internet”, or whatever your favorite phone web browser may be, and navigate to 192.168.4.1 (that link will only work on a device connected to the Blynk Board).

After a couple seconds, the Blynk Board should serve up a webpage like this:

It may take a couple refreshes to load the Blynk Board Config page. If your browser says “Failed to load webpage”, or something to that effect, try refreshing.

Step 3: Send your Wi-Fi Network and Blynk Auth Token

The config page will present a list of visible Wi-Fi networks within range. If you see your network on there, great! Select that. If your network is hidden, scroll down to “[Enter manually …]”, and type it in yourself.

Next, enter the password for your Wi-Fi network. If it’s an open network (no password), leave the box blank.

Finally, paste the auth token into the Blynk auth token box. This process varies by phone, either a light tap (iOS) or a tap-and-hold should bring up the paste option.

Unless you’re connecting to the Blynk Board to a custom server (which you’re most likely not), leave the Blynk host and port entries as-are (blynk-cloud.com and 8442).

Now click Apply.

Step 4: Monitor the Blynk Board

After hitting apply, you should be served a confirmation page, informing you of what the Blynk Board is attempting to do.

The Blynk Board should immediately begin to blink blue as it attempts to connect to your Wi-Fi network.

If that’s successful, it’ll begin to blink Blynk-green while it establishes a connection with the Blynk server.

Once both parties are happy there, the Blynk Board’s RGB LED should “breathe” Blynk-green, fading in-and-out, in-and-out. That’s a great sign! Swap back to the Blynk app and we’ll set up a zeRGBa.

If that didn't work, go back to the provisioning options, and try something else. Or consider getting in touch with our technical support team.

Manually Adding a zeRGBa Widget

Hopefully one of the three alternative provisioning processes has worked for you. If not, please don’t hesitate to get in touch with our technical support team.

If your Blynk Board is breathing Blynk-green, open the Blynk app on your phone, and select the bare project you’ve created. Look at that blank canvas – room for so many widgets!

Blank Blynk project

A new Blank Blynk project. (Android left, iOS right)

To add a widget to the Blynk app, first make sure the project isn’t running– you should see a triangular-shaped “play” icon in the upper-right-hand corner. Now tap anywhere in the grey project space to bring up the Blynk widget box.

Adding a zergba

Add a zeRGBa widget from the Blynk widget box.

Select the zeRGBa widget to add it to your project. You can tap-and-hold the widget to drag it around the project space. We find the zeRGBa prefers to be the center-of-attention.

Now tap the zeRGBa to enter the widget settings – you’ll get very used to this. Slide the Split/Merge switch over to Merge. Then tap “PIN”, and set the box to V0. The widget settings should look like this:

zeRGBa settings

To back out of the settings tab, hit OK on iOS or the upper-left back arrow on an Android.

Back at the project screen, tap the play button in the upper-right corner to start Blynking! Once you’ve got the project running, poke-and-prod that colorful zebra!

zeRGBa purple, LED purple!


Congratulations! You’re well on-your-way to being a professional Blynker. From here we recommend you visit the Blynk Board Project Guide to explore over a dozen Blynk projects built into the Blynk Board.

New!

Blynk Board Project Guide

March 25, 2016

A series of Blynk projects you can set up on the Blynk Board without ever re-programming it.

Or, you may want to check out some of these other Blynk-related tutorials:

New!

Blynk Board Bridge Widget Demo

A Blynk project that demonstrates how to use the Bridge widget to get two (or more) Blynk Boards to communicate.
New!

Blynk Board Arduino Development Guide

How to get your computer set up with Arduino and the Blynk Board hardware definitions -- so you can start creating Blynk projects of your own!

Reconfiguring a Blynk Board

If you’ve taken your Blynk Board somwhere new, and need to reconfigure its Wi-Fi network – or if you need to update the Blynk auth token – there’s a built-in method for re-entering configuration mode to reset both credentials.

While the Blynk Board is attempting to connect to a Wi-Fi network or Blynk – blinking blue or green – press and hold the 0 button.

Hold the 0 button for 3 seconds to reprovision

You should see the RGB LED turn white and slowly increase in brightness. After about a second, the LED will begin to dim. Once you’ve held the button for about 4 seconds and the LED begins to brighten again, release the button.

If the reset was successful, you should see the Blynk Board revert back to its R/G/B/Y/P color-combo sequence. It should also show up as a Wi-Fi access point, and you’ll be able to configure it over either Wi-Fi or a serial terminal.

You can even re-scan your Blynk Board QR-Code Card. No, you won’t get another 15k energy, but you will be able to step through the provisioning process again!

Resources

If your Blynk Board is successfully provisioned, head over to the Blynk Board Project tutorial to explore the Blynk Board’s pre-loaded projects.

If you need any technical assistance with your Blynk Board, don’t hesitate to contact our technical support team via either e-mail, chat, or phone.

If you need general Blynk Board or Blynk App resources, these may help:


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

Boss Alarm

$
0
0

Boss Alarm a learn.sparkfun.com tutorial

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

Introduction

It’s a common occurrence in any office – you’re on Facebook or browsing SparkFun when all of a sudden your boss walks in to see that you’re not working.

This project aims to avoid that embarrassment and frowns from management. The Boss Alarm alerts you of anyone walking into your office and automatically changes the active program on your computer. The sensors are inconspicuously hidden in cute woodland creatures that are guaranteed to brighten up your office and definitely not creep out any of your coworkers!

Owl Face

Definitely not creepy

The Boss Alarm uses an infrared breakbeam sensor made with a few common components. The design is based on schematics from this article with a few modifications.

There are three components to the Boss Alarm. There is a transmitter (hidden in the squirrel) that sends an invisible beam to the owl. The owl contains an infrared receiver (namely, the TSOP38238 IR Receiver Diode) and also another infrared transmitter. The last component is another IR receiver connected to a Teensy 3.2.

Boss Alarm

Harmless woodland creatures!

The Teensy is configured as a USB keyboard device. When the beam between the owl and the squirrel is broken, the owl sends a signal to the Teensy. When the Teensy receives this signal, it simply sends the Alt+Tab keyboard command to your computer to change the active program. If you are on a different operating system, you can change the key commands to whatever you want (for example, Windows Key + D to minimize all programs). You can trigger practically anything using this project.

Check out a video of the project in action below:

Materials

You’re going to need a few things to build this project yourself.

Along with those parts, you will need a few other parts and tools:

If you plan on installing the electronics in the woodland creature enclosures, you will also need access to a 3D printer and a hot glue gun. You may also wish to paint them.

I highly recommend obtaining some sort of oscilloscope for troubleshooting, but it is not necessary to complete this project. You may also want to acquire a decent multimeter for diagnosing any issues you encounter.

Recommended Reading

You may need to read up on a few subjects to wrap your head around this project:

Printing the Models

Owl Model

Sectioned owl model enclosure

Squirrel Model

The cute squirrel model

I am more of an engineer than an artist, so I sourced the basic owl and squirrel models from Autodesk’s 123Dapp website. The original artist’s page for the owl can be found here. And the squirrel’s artist can be found here.

Unpainted Models

The elusive nuclear-green owl

I modified the models a bit to fit the electronics inside. The owl was too tall for my printer to handle so I separated it into two parts and used printed pegs to align them. This also aids in assembly later on and isn’t too noticeable. I used Autodesk’s free, online program, Tinkercad, to create the models.

You should start the printer now, the models take a while to print!

Making the Squirrel Transmitter

The transmitter is a simple astable 555 timer circuit. The 555 timer is a popular and versatile (and some might say dated) IC found in many hobbyist projects.

The parts you need for this component of the project are:

  • 220Ω, 2.2kΩ, and 10kΩ Resistors (1 each)
  • 10kΩ potentiometer
  • 1nF and 10nF ceramic capacitors
  • Infrared LED
  • 555 timer (x1)
  • 9V Battery Connector and 9V Battery
  • Snapable Protoboard
  • Heatshrink Tubing

Here’s the circuit diagram:

Squirrel Transmitter Circuit

The infrared receivers we are using have built-in filtering that makes them very reliable for digital communication. However, in order for the receivers to see our infrared beam we need to modulate it (turn it off and on) at 38kHz.

When operated in astable mode, the 555 timer will oscillate between high and low voltage at a frequency determined by external resistors and capacitors. If you want to learn more about how to work with a 555 timer, there are several websites dedicated to the chip.

Let me remind you of the pinout for the infrared receiver:

TSOP Pinout

Ask me why I know this by heart…

Solder together the circuit in the diagram, try to keep it a bit compact so it fits in the model nicely! The squirrel can accommodate a 9V battery and a circuit board about 1.25 X 1 and 0.5 inches tall.

Squirrel Circuit board

The Squirrel’s circuit board

Don’t solder the infrared LED directly on the board. Instead, solder some longer-than-you-think-you-need wires onto the LED’s terminals making sure to note which one is the anode (+) and which is the cathode (-).

Soldering leads on the LEDs

To avoid short circuits, you should put some shrink wrap tubing on the soldered connections. You can use a heat gun or a blow dryer to shrink the tubing. I used a lighter but be careful not to melt the LED or yourself.

Shrink wrap on the LEDs

If you are using the printed models, I recommend painting them so they blend into your desk’s knick-knacks better.

You can install the infrared LED in the squirrel’s acorn. You may need to drill out the hole a bit to make the LED fit. Feed the wires through the model until they come out the bottom and then use a little hot glue to keep the LED in place. Tuck the wires away, and then no one will notice the squirrel is actually a nark!

Squirrel Circuit board installed

The squirrel’s circuit board installed

Squirrel Overview

The finished squirrel transmitter

Making the Owl Transceiver

Circuit Operation

Here’s the circuit schematic for the owl:

Owl Transceiver Circuit

Click the image for a closer look.

The circuit for the owl may look really complicated but it’s not! The owl transceiver operates in a way similar to the squirrel transmitter. Only instead of having one 555 timer circuit, the owl has TWO! Let’s go through it step by step.

The owl has a 555 timer operating in monostable mode and another operating in astable mode. The IR Receiver Diode is an active low device. This means that, when it receives a signal, the output pin is pulled low. This works great with our 555 timer since the trigger pin needs to be pulled low to activate the monostable circuit.

The monostable circuit is designed to hold the output high for approximately 1 second (this timing isn’t crucial) when triggered by the IR Receiver.

The next part of the circuit is our reset transistor. There are two current-limiting resistors (1kΩ for the base, 220Ω for the Red eye LED) and a 10kΩ pull-down resistor on the transistor’s emitter.

Notice that the emitter is also connected to the reset pin of the second 555 timer. In most astable applications, you tie the reset pin to the supply voltage so the chip is always on. However, in this project we only want the owl to send a signal to the computer when someone walks by.

In this configuration, when the output of the first 555 is low, the transistor will be off. The pull-down resistor makes sure the voltage seen by the second 555 timer’s reset pin is around 0V, keeping it off. When the circuit is triggered, the red LED and the transistor turn on. Since the transistor is conducting, the voltage at the emitter becomes high enough to enable the second 555 timer for about 1 second.

The second 555 timer is designed to operate in astable mode at 38kHz just like the circuit in the squirrel. This sends another infrared signal to your computer telling it that someone walked by!

The additional circuits shown in the schematic are the 5V regulator circuit and the infrared receiver filtering circuit. The regulator simply takes the 9 volts from the battery and outputs a stable 5V source that plays nicely with our infrared receiver. The filtering circuit has a couple capacitors that help stabilize the output of the receiver and a pull-up resistor to keep the output high when the receiver is off.

Soldering Time!

The parts you need for this component of the project are:

  • 100Ω, 220Ω (x2), 1kΩ, 2.2kΩ, 10kΩ (x3), and 100kΩ Resistors
  • 10kΩ potentiometer
  • 1nF, 10nF (x2), 0.1μF (x3), and 10μF (x2) capacitors
  • Infrared LED
  • Red LED
  • Infrared Receiver
  • 555 timer (x2)
  • 2N3904 NPN Transistor
  • L7805 Regulator
  • 9V Battery Connector
  • Snapable Protoboard
  • Heatshrink Tubing

Build the circuit according to the included schematic. Make sure not to solder the red and infrared LEDs or the infrared receiver. Just like with the squirrel, solder on some long wires to these, and cover the connections with shrink tubing.

Owl Circuit Board

Completed owl circuit board. It looks complicated, but that’s just because it’s densely populated!

Paint the owl however you want; I went with a classic brown woodland owl. Again, you may need to drill out the mounting holes to get the parts to fit. It’s best to do this before painting the models to avoid scratching the paint off.

When your model is prepped, you can install the components. The infrared LED is mounted in the hole on the side of the log. The Red LED goes in either eye of the owl. The IR receiver goes in the other eye of the owl. Solder the components to the board, and it should be all set!

Owl Side of Log

Hot glue the infrared LED in the side of the log. I accidentally melted the paint a bit, try to avoid that!

Owl Eyes

The Red LED and the IR receiver get installed in the head of the owl. The split in the model makes installation much easier!

Owl Overview

The completed owl model. Such beautiful eyes!

Tuning the Transmitters

You may have noticed each astable 555 timer circuit includes a potentiometer. This allows us to fine-tune the frequency at which the circuit oscillates. We want it to be as close to 38kHz as possible so the receiver can see it in full strength.

This is where an oscilloscope comes in handy. This nice piece of kit lets you visualize voltage waveforms in (pretty much) real time. My current oscilloscope is a USB-based one called the Analog Discovery 2 by Digilent. This device not only acts as a 2-channel oscilloscope but also has a 2-channel function generator, a variable power supply, a pattern generator for digital circuits, and a logic analyzer! I prefer actual lab equipment but the Analog Discovery is nice for how compact and affordable it is.

Analog Discovery 2

Analog Discovery 2 – Photo courtesy of Digilent

Use a small screwdriver to adjust the potentiometer. When you have it tuned just right, you may want to hot glue the knob in place so it doesn’t get changed accidentally. Make sure to repeat this procedure for each transmitter circuit!

Tuning the potentiometer

Tuning the transmitter frequency with a potentiometer

Tuning Without an Oscilloscope

To tune the circuit without an oscilloscope, you can just play with the potentiometer until the circuit operates reliably. The IR receiver will work with frequencies that are close enough to 38kHz.

Tuning With an Oscilloscope

If you are lucky enough to have access to an oscilloscope, this part becomes very easy. Simply hook your probe up to the output pin of the astable 555 timer, and the waveform should appear. You can adjust the potentiometer until the frequency is about 38kHz.

With the equipment mentioned above, measure the frequency of the wave using vertical cursors, and place them one period apart. The inverse of the difference between them will be your frequency (the oscilloscope usually does this calculation for you).

Tuning frequency with oscilloscope

Checking the frequency using an oscilloscope. Notice the frequency is almost exactly 38kHz!

If you’re just getting started with the oscilloscope, you should read this guide.

Making the Computer Receiver

The computer receiver is just a copy of the IR filtering circuit used in the owl hooked up to a Teensy 3.2.

Computer Receiver

The IR filter and Teensy connected. I used an old servo connector to join the two boards. Notice the pins the filter board connects to. (Contrary to convention) Black is Vs, red is ground, and white is out.

Build the Circuit

The parts you need for this component of the project are:

  • Teensy 3.2 and USB Cable
  • Male headers
  • 100Ω and 10kΩ Resistors
  • 0.1μF, and 10μF capacitors
  • Infrared Receiver
  • Snapable Protoboard

Here’s the schematic again:

IR Filtering Schematic

First, solder headers on your Teensy board, if you haven’t already.

Solder together the IR filtering circuit, and use a connector to tie the Teensy’s power and ground pins to the appropriate pins on the infrared receiver. Make sure to use the V_USB pin to get a 5V source rather than the 3.3V source on the Teensy. Connect the output of the receiver to pin 0 on the Teensy.

IR Filtering Board

The IR filtering board. Notice I messed up with the IR receiver: it’s soldered twice!

Programming the Teensy

Plug the Teensy into your computer, and get ready to program it! If you haven’t used the Teensy before, read this guide to get started.

The Teensy is like an Arduino, but it has a unique feature – it can be configured as a USB device. This lets your computer “see” the Teensy as another device and automatically load the drivers for it. For example, you can configure the Teensy as a USB keyboard (as in this project), and, when you plug it in, your computer will see it as a keyboard – no special software required!

The code used in this project is almost identical to the Teensy’s USB keyboard example sketch. We simply treat the output of the IR receiver as a switch and send key presses/releases on the falling/rising edge of the receiver’s output.

language:c
/* Title: Boss Alarm
 * Date: 3/14/2016
 * Author: Don Beckstein

   Note: You must select Keyboard from the "Tools > USB Type" menu

*/

#include <Bounce.h>

// Helps us debounce the output from the IR receiver (helps suppress false-alarms)
Bounce button0 = Bounce(0, 100);

//Change these to set the key combination used
unsigned const int modifierKey = MODIFIERKEY_ALT;
unsigned const int combinationKey = KEY_TAB;

//If you're on Mac you can try this code (I haven't tested it)
//unsigned const int modifierKey = MODIFIERKEY_GUI;
//unsigned const int combinationKey = KEY_TAB;

//If you want it to show your desktop on Windows instead of switch windows, use this code:
//Sends Windows Key + D
//unsigned const int modifierKey = MODIFIERKEY_GUI;
//unsigned const int combinationKey = KEY_D;

void setup() {
  // Configure the pins for input mode with internal pullup resistors.
  pinMode(0, INPUT_PULLUP);

}

void loop() {

  //Update the buttons
  button0.update();

  //Press keyboard keys when the IR Receiver is triggered
  if (button0.fallingEdge()) {

    //Send the key commands
    Keyboard.set_modifier(modifierKey);
    Keyboard.send_now();
    Keyboard.set_key1(combinationKey);
    Keyboard.send_now();
  }

  //Release the keyboard keys when the trigger returns to normal
  if (button0.risingEdge()) {

    //Release keys
    Keyboard.set_modifier(0);
    Keyboard.set_key1(0);
    Keyboard.send_now();
  }
}

The default key combination is ALT+Tab to switch between programs on Windows. If you have multiple monitors you might want all programs to be minimized. I included a few different key combinations in the code, you can uncomment/comment lines of code to suit your needs. I also included a key combination that should work on Mac. If you want to make your own key command, this page provides a reference to the Teensy’s defined keys.

Make sure to click Tools->Board->Teensy 3.2 and Tools->USB Type->Keyboard+Mouse+Joystick to set up your Teensy correctly. Load the Boss Alarm code onto your Teensy, and it should be all set!

Setting Up the Boss Alarm

The squirrel and owl should be placed across from each other at the same height for best operation. Make sure the IR LED in the owl is pointing towards your computer! The Boss Alarm should work well for typical small office spaces.

Remember that light can reflect (including infrared, we just can’t see it)! You may find that the IR signal coming from the squirrel gets picked up by your Teensy receiver causing false-alarms. If this happens, reposition the squirrel so it is angled away from your Teensy receiver.

Plug in the Teensy board, and that’s it!

The Boss Alarm will change your active program using Alt-Tab. Make sure the last program you had selected was work-related. Excel has some nice templates that certainly look business-y.

Owl wave test

The red LED lets you know it’s working.

Screen Change

The active program changes to something more business-y

The Boss Alarm has the unintended benefit that when your boss walks away, it will trigger again and return your active program to whatever you were doing before!

Now you can browse SparkFun at work without fear of your boss finding out. :)

Resources and Going Further

Though it may seem like something out of a spy movie, you likely use this kind of technology every day. The infrared receiver in the owl’s eye is the same you will find if you open up any modern TV or DVD player. That’s right – remote controls use this to send key presses!

Tenacious Lasers

Dramatization of your manager after the Boss Alarm is set up. (Clip from Tenacious D and the Pick of Destiny)

To Infinity… and Beyond!

Infrared communication has applications beyond breakbeam sensors and remote controls. NASA is using infrared lasers to speed up data transmission to and from Mars! It is also used in modern fiber-optic communication systems. For more on infrared communication, read this page on Wikipedia.

Infrared is one of my favorite communication methods to use in my projects. It is a pretty lightweight, cheap, and versatile platform. All it takes is a common IR LED and an IR receiver diode.

Another project I made for a hackathon was a multi-user chatroom that transferred messages across the room using infrared! My team even transmitted a picture over the channel. We called it IRC (pun intended, InfraRed Chat).

You can use this design as a basis for a number of other projects! See if you can modify the circuits to trigger other things using an infrared breakbeam sensor.

Aside from those mentioned in the tutorial, here are a few resources I used along the way:

If you are having trouble with the Teensy, browse through the board’s website to find more information and tutorials.

If you have any interest in microelectronics, you might like this article on the internals of the 555 timer!

For more project ideas, check out these other great SparkFun tutorials.

Binary

Binary is the numeral system of electronics, and widely used in programming...so it must be important to learn. But, what is binary? How does it translate to other numeral systems like the decimal we're used to?

IR Communication

This tutorial explains how common IR communications works, as well as shows you how to set up a simple IR transmitter and receiver.

Hexadecimal

How to interpret hex numbers, and how to convert them to/from decimal and binary.

Getting Started with OBD-II

A general guide to the OBD-II protocols used for communication in automotive and industrial applications.

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

Blynk Board Washer/Dryer Alarm

$
0
0

Blynk Board Washer/Dryer Alarm a learn.sparkfun.com tutorial

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

Introduction

We created the SparkFun Blynk Board to solve problems. Big problems – like keeping plants healthy– and problems trending closer to the “first-world” end of the spectrum – like a phone-alerting laundry monitor.

alt text

This tutorial demonstrates how to pair the Blynk Board with an MMA8452Q Accelerometer Breakout to create a shake-sensing laundry monitor. Once the laundry is done, the electronics will communicate with the Blynk app– over Wi-Fi – to send your phone a push notification.

alt text

Together, the Blynk Board and app will allow you to power through laundry day as quickly and efficiently as possible!

Required Materials

The wishlist below includes all of the electronics and components you’ll need to follow along with this tutorial:

In addition to those breakout boards and cables, this project also requires a bit of soldering. A simple soldering iron, some solder, wire strippers, and a flush cutter should be all you really need.

Wire Strippers - 30AWG (Hakko)

TOL-12630
$9.95
1
Flush Cutters - Hakko

TOL-11952
$6.95
14
Soldering Iron - 30W (US, 110V)

TOL-09507
$9.95
3
Solder Lead Free - 15-gram Tube

TOL-09163
$3.5
1

Suggested Reading

To follow along with this tutorial, you’ll need to program your Blynk Board with new firmware. Hopefully, by this point, you’ve already exhausted the Project Guide and set your computer up to program the Blynk Board using Arduino. If not, check out either – or both – of those tutorials first.

Blynk Board Project GuideBlynk Board Arduino Development Guide

This project builds on a handful of electronics concepts. If your unfamiliar with any of the subjects below, consider reading through that tutorial first.

How to Solder - Through-hole Soldering

New to electronics and soldering? Have you soldered before but need a refresher? This tutorial with cover everything you need to know about through-hole soldering.

Accelerometer Basics

A quick introduction to accelerometers, how they work, and why they're used.

I2C

An introduction to I2C, one of the main embedded communications protocols in use today.

MMA8452Q Accelerometer Breakout Hookup Guide

How to get started using the MMA8452Q 3-axis accelerometer -- a solid, digital, easy-to-use acceleration sensor.

Hardware Hookup

The MMA8452Q is controlled and monitored via an I2C interface interface – a two-wire, serial interface popular among embedded electronics like this. On the Blynk Board, that interface is broken out to the 4-pin, white JST connector adjacent to the USB port.

I2C connector location

Our 4-Pin JST wire assembly mates perfectly with that connector, but tying the other end to an accelerometer will require some soldering.

If you’ve never soldered before, don’t run off just yet! This is relatively simple soldering, and is a great introduction to the skill. Check out our How to Solder - Through Hole tutorial to learn how to get started.

Solder the JST Cable to the Accelerometer

Plugged into the Blynk Board, the colors of the 4-wire JST assembly match up closely with what you’d expect. Black is ground, red is power (3.3V), yellow is SCL, and blue is SDA. That’s exactly how you’ll need to solder the accelerometer on the other end.

MMA8452Q accelerometer soldered

Once the JST cable is soldered into the accelerometer, simply plug the connector into the mating end of the Blynk Board.

Blynk Board and accelerometer together

Optional: Add a Battery

This project can take advantage of the Blynk Board’s integrated LiPo battery charger. If you don’t have an empty wall outlet nearby, you can simply plug the battery in and set the assembly on top of your washer/dryer.

Battery plugged in to circuit

Any of our single-cell lithium-polymer batteries should work. If you’re looking for suggestions, we find the 400mAh and 850mAh LiPo’s to be a nice compromise between capacity and size.

To charge the battery, simply connect a USB cable (connected on the other end to either a computer or wall adapter) to the Blynk Board.

Blynk Setup

To enable phone notifications – and to configure the Blynk Board laundry monitor on-the-fly – we're using the Blynk app. Blynk is available for both iOS and Android devices. Click one of the links below, if you don't have the app yet.

AS_link
GP_link

On your phone, create a new Blynk project (or use a previously-created project if you prefer). Then drag in the following widgets:

Push Notifications

The most critical widget of the bunch! There’s not a whole lot to configure here. The “Send even if app is in background” option is useful, but may end up draining more of your phone’s battery.

Notification settings

Button | “Enable Push” | V0

This button will allow you to easily enable or disable push notifications – just in case you don’t always want the intrusive alerts.

Button settings

Make sure the button is set to switch mode.

Slider | “Shake Threshold” | V1

The code adds up sensed acceleration in all three dimensions, then compares that sum against a previous measurement. This threshold value sets the minimum difference between those two measurements that will trigger a “shake”.

Threshold slider settings

Depending on how much your washer or dryer shakes, a value between 10 and 100 should work. You can monitor the gauge widget to fine-tune this value.

Slider | “Start Time (ms)” | V2

This slider configures the amount of time shaking must be sensed before the Blynk Board assumes the laundry is running. This helps filter out steps, a door closing, earth tremors, etc.

Start time slider settings

You may need to tweak this value, but 500 (milliseconds) is usually a good default.

Slider | “Stop Time (s)” | V3

This slider sets the number of seconds from when shaking stops to when the notification is sent. Some washers or dryers will try to fake you out, by pausing their cycle for a few seconds before picking back up.

Stop time slider settings

A value between 10 and 60 seconds should work – though you may have to extend it even more depending on your appliance. Just know that the higher this value is, the slower you’ll be to your laundry when it’s done.

LCD | “Laundry Status” | V4 (Advanced)

Bits of data like the state of your washer/dryer or how long it’s been running/stopped are routed to the LCD.

LCD Slider settings

A quick glance at this, while the project is running, may give you an idea of how much time is left on your wash.

Gauge | “Shakiness” | V5

The raw “shakiness” calculation is supplied to this virtual variable a few times per second.

Shakiness gauge settings

This widget is helpful in tweaking the threshold (V1) slider. Or for verifying that the machine is still shaking.


Arrange the widgets however you’d like, customize the colors, have fun with it! Here’s an example set up:

Example project layout

Program the Blynk Board

If you haven’t set your computer up to program the Blynk Board using Arduino yet, read through our Blynk Board Arduino Development Guide first. Following that, you should have the Blynk Board hardware definitions and most of the libraries you’ll need added to your Arduino IDE.

Set your Arduino IDE up for Blynk Board development!

Install the SparkFun MMA8452Q Arduino Library

The latest version of our MMA8452Q Arduino library can be downloaded from the SparkFun_MMA8452Q_Arduino_Library GitHub repository (click the “Download ZIP” button there). Or you can skip the detour, by clicking the button below.

Download the MMA8452Q Arduino Library

The library will be downloaded as a ZIP file. To install it in Arduino, navigate to Sketch>Include Library>Add .ZIP Library…. Then select the MMA8452Q ZIP folder you just downloaded.

Add library from zip folder

Copy/Paste the Code

Our “Blynk Board Laundry Monitor” source code is also available on GitHub. Download it from there, or copy/paste from the box below:

language:c
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <Wire.h> // Must include Wire library for I2C
#include <SparkFun_MMA8452Q.h> // Includes the SFE_MMA8452Q library
#include <Adafruit_NeoPixel.h>

//////////
// WiFi //
////////// // Enter your WiFi credentials here:
const char WiFiSSID[] = "WiFiNetworkName";
const char WiFiPSWD[] = "WiFiPassword";

///////////
// Blynk //
///////////             // Your Blynk auth token here
const char BlynkAuth[] = "0a1b2c3d4e5f";
bool notifyFlag = false;
#define VIRTUAL_ENABLE_PUSH     V0
#define VIRTUAL_SHAKE_THRESHOLD V1
#define VIRTUAL_START_TIME      V2
#define VIRTUAL_STOP_TIME       V3
#define VIRTUAL_LCD             V4
#define VIRTUAL_SHAKE_VALUE     V5
WidgetLCD lcd(VIRTUAL_LCD);
bool pushEnabled = false;
void printLaundryTime(void);

/////////////////////
// Shake Detection //
/////////////////////
unsigned int shakeThreshold = 50;
unsigned int shakeStartTimeHysteresis = 1000;
unsigned int shakeStopTimeHysteresis = 10;
unsigned long shakeStateChangeTime = 0;
unsigned long shakeStartTime = 0;
bool loadTimer = true;

enum {
  NO_SHAKING_LONG, // Haven't been shaking for a long time
  NO_SHAKING,  // Hasn't been any shaking
  PRE_SHAKING, // Started shaking, pre-hysteresis
  SHAKING,     // Currently shaking
  POST_SHAKING // Stopped shaking, pre-hysteresis
} shakingState = NO_SHAKING;

// Possible return values from the shake sensor
enum sensorShakeReturn {
  SENSOR_SHAKING,
  SENSOR_NOT_SHAKING,
  SENSOR_NOT_READY
};
sensorShakeReturn checkShake(void);
void shakeLoop(void);

////////////////////////////
// MMA8452Q Accelerometer //
////////////////////////////
MMA8452Q accel;
int16_t lastX, lastY, lastZ;
void initAccel(void);

//////////////////////////
// Hardware Definitions //
//////////////////////////
const int LED_PIN = 5;
const int RGB_PIN = 4;
Adafruit_NeoPixel rgb = Adafruit_NeoPixel(1, RGB_PIN, NEO_GRB + NEO_KHZ800);
void setLED(uint8_t red, uint8_t green, uint8_t blue);

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

  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, LOW); // Turn off blue LED
  rgb.begin(); // Set up WS2812
  initAccel(); // Set up accelerometer
  setLED(0, 0, 32); // LED blue

  // Initialize Blynk, and wait for a connection before doing anything else
  Serial.println("Connecting to WiFi and Blynk");
  Blynk.begin(BlynkAuth, WiFiSSID, WiFiPSWD);
  while (!Blynk.connected())
    Blynk.run();
  Serial.println("Blynk connected! Laundry monitor starting.");
  setLED(0, 32, 0); // LED green
}

void loop()
{
  shakeLoop(); // Check if we're shaking, and update variables accordingly
  Blynk.run(); // Blynk run as much as possible
}

bool firstConnect = true;
BLYNK_CONNECTED()
{
  if (firstConnect) // When we first connect to Blynk
  {
    // Two options here. Either sync values from phone to Blynk Board:
    //Blynk.syncAll(); // Uncomment to enable.
    // Or set phone variables to default values of the globals:
    Blynk.virtualWrite(VIRTUAL_SHAKE_THRESHOLD, shakeThreshold);
    Blynk.virtualWrite(VIRTUAL_STOP_TIME, shakeStopTimeHysteresis);
    Blynk.virtualWrite(VIRTUAL_START_TIME, shakeStartTimeHysteresis);
    Blynk.virtualWrite(VIRTUAL_ENABLE_PUSH, pushEnabled);

    // Print a splash screen:
    lcd.clear();
    lcd.print(0, 0, "Laundry Monitor ");
    lcd.print(0, 1, "     Ready      ");
  }
}

BLYNK_WRITE(VIRTUAL_ENABLE_PUSH)
{
  int enable = param.asInt();
  if (enable > 0)
  {
    pushEnabled = true;
    Serial.println("Push notification enabled");
  }
  else
  {
    pushEnabled = false;
    Serial.println("Push notification disabled");
  }
}

BLYNK_WRITE(VIRTUAL_SHAKE_THRESHOLD)
{
  int inputThreshold = param.asInt();

  shakeThreshold = constrain(inputThreshold, 1, 2048);

  Serial.println("Shake threshold set to: " + String(shakeThreshold));
}

BLYNK_WRITE(VIRTUAL_START_TIME)
{
  int inputStartTime = param.asInt();

  if (inputStartTime <= 0) inputStartTime = 1;
  shakeStartTimeHysteresis = inputStartTime;

  Serial.println("Shake start time set to: " + String(shakeStartTimeHysteresis) + " ms");
}

BLYNK_WRITE(VIRTUAL_STOP_TIME)
{
  int inputStopTime = param.asInt();

  if (inputStopTime <= 0) inputStopTime = 1;
  shakeStopTimeHysteresis = inputStopTime;

  Serial.println("Shake stop time set to: " + String(shakeStopTimeHysteresis) + " seconds");
}

void printLaundryTime(void)
{
  unsigned long runTime = millis() - shakeStartTime;
  int runSeconds = (runTime / 1000) % 60;
  int runMinutes = ((runTime / 1000) / 60) % 60;
  int runHours = ((runTime / 1000) / 60 ) / 60;

  // Create a string like HHHH:MM:SS
  String runTimeString = "" + String(runHours) + ":";
  if (runMinutes < 10) runTimeString += "0"; // Leading 0 minutes
  runTimeString += String(runMinutes) + ":";
  if (runSeconds < 10) runTimeString += "0"; // Leading 0 seconds
  runTimeString += String(runSeconds);

  // Fill out the rest of the string to 16 chars
  int lineLength = runTimeString.length();
  for (int i=lineLength; i<16; i++)
  {
    runTimeString += "";
  }

  if (shakingState == PRE_SHAKING)
    lcd.print(0, 0, "Laundry starting");
  else if (shakingState == SHAKING)
    lcd.print(0, 0, "Laundry running ");
  else if (shakingState == NO_SHAKING)
    lcd.print(0, 0, "Laundry stopping");
  else if (shakingState == NO_SHAKING_LONG)
    lcd.print(0, 0, "Laundry done!   ");
  lcd.print(0, 1, runTimeString);
}

void shakeLoop(void)
{
  sensorShakeReturn sensorState = checkShake();
  if (sensorState == SENSOR_SHAKING) // If the sensor is shaking
  {
    switch (shakingState)
    {
    case NO_SHAKING_LONG:
    case NO_SHAKING: // If we haven't been shaking
      setLED(32, 0, 32); // LED purple
      shakingState = PRE_SHAKING; // Set mode to pre-shaking
      shakeStateChangeTime = millis(); // Log state change time
      if (loadTimer)
      {
        loadTimer = false;
        shakeStartTime = millis(); // Log time we started shaking
      }
      printLaundryTime();
      break;
    case PRE_SHAKING: // If we're pre-hysteresis shaking
      if (millis() - shakeStateChangeTime >= shakeStartTimeHysteresis)
      { // If we've passed hysteresis time
        shakingState = SHAKING; // Set mode to shaking
        digitalWrite(LED_PIN, HIGH); // Turn blue LED on
        Serial.println("Shaking!");
        notifyFlag = true; // Flag that we need to notify when shaking stops
        setLED(32, 0, 0); // LED red
      }
      break;
    case SHAKING: // If we're already shaking
      printLaundryTime(); // Update laundry timer
      break; // Do nothing
    case POST_SHAKING: // If we didn't stop shaking before hysteresis
      shakingState = SHAKING; // Go back to shaking
      break;
    }
  }
  else if (sensorState == SENSOR_NOT_SHAKING) // If the sensor is not shaking
  {
    switch (shakingState)
    {
    case NO_SHAKING_LONG: // If we haven't been shaking for a long time
      break; // Do nothing
    case NO_SHAKING: // If we haven't been shaking
      if (millis() - shakeStateChangeTime >= (shakeStopTimeHysteresis * 1000))
      { // Check if it's been a long time
        setLED(0, 32, 0); // Turn LED green
        shakingState = NO_SHAKING_LONG;
        if (notifyFlag == true) // If notify flag was set during shaking
        {
          loadTimer = true;
          printLaundryTime(); // Update LCD
          notifyFlag = false; // Clear notify flag
          if (pushEnabled) // If push is enabled
            Blynk.notify("Washer/dryer is done!"); // Notify!
        }
      }
      break;
    case PRE_SHAKING: // If we're pre-hysteresis shaking
      shakingState = NO_SHAKING; // Go back to no shaking
      setLED(0, 32, 0);
      break;
    case SHAKING: // If we're already shaking
      shakingState = POST_SHAKING; // Go to hysteresis cooldown
      shakeStateChangeTime = millis();
      break; // Do nothing
    case POST_SHAKING: // If we're in the shake cooldown state
      if (millis() - shakeStateChangeTime >= shakeStartTimeHysteresis)
      {
        digitalWrite(5, LOW); // LED off
        shakingState = NO_SHAKING;
        printLaundryTime();
        setLED(32, 16, 0);
        Serial.println("Stopped.");
      }
      break;
    }
  }
}

sensorShakeReturn checkShake(void)
{
  static unsigned long lastShakeCheck = 0;
  float shake = 0;
  if (accel.available()) // If new accel data is available
  {
    int16_t x, y, z;

    accel.read(); // read the data in
    x = accel.x;
    y = accel.y;
    z = accel.z;

    // To determine if we're shaking, compare the sum of
    // x,y,z accels to the sum of the previous accels.
    shake = abs(x + y + z - lastX - lastY - lastZ);

    // Write the value to Blynk:
    Blynk.virtualWrite(VIRTUAL_SHAKE_VALUE, shake);

    // Update previous values:
    lastX = x;
    lastY = y;
    lastZ = z;
  }
  else // If sensore didn't have new data
  { // Return not ready
    return SENSOR_NOT_READY;
  }
  // If shake value exceeded threshold
  if (shake >= shakeThreshold)
    return SENSOR_SHAKING; // Return "shaking"
  else
    return SENSOR_NOT_SHAKING; // Or return "not shaking"
}

void initAccel(void)
{
  // Use a slow update rate to throttle the shake sensor.
  // ODR_6 will set the accelerometer's update rate to 6Hz
  // Use +/-2g scale -- the lowest -- to get most sensitivity
  accel.init(SCALE_2G, ODR_6); // Initialize accelerometer

  while (!accel.available()) // Wait for data to be available
    yield(); // Let the system do other things
  accel.read(); // Read data from accel
  lastX = accel.x; // Initialize last values
  lastY = accel.y;
  lastZ = accel.z;
}

void setLED(uint8_t red, uint8_t green, uint8_t blue)
{
  rgb.setPixelColor(0, rgb.Color(red, green, blue));
  rgb.show();
}

Before uploading, however, you’ll need to adjust a few strings.

Configure Your WiFi Network

Near the top of the sketch, you’ll find a couple string constants named WiFiSSID and WiFiPSWD. Change the WiFiNetworkName and WiFiPassword values to match your WiFi network name (SSID) and password.

language:c
const char WiFiSSID[] = "WiFiNetworkName";
const char WiFiPSWD[] = "WiFiPassword";

Configure Your Blynk Token

Next, you’ll need to configure the BlynkAuth string to match your Blynk auth token. You can find this in the settings section of your Blynk project – click the hexagon-shaped “nut” icon in the upper-right.

Use the E-Mail feature to send yourself a copy of the auth token, which you can copy and paste into the code:

language:c
const char BlynkAuth[] = "0a1b2c3d4e5f..."

Upload the Code

Finally, upload the code – making sure your serial port is correctly selected and the board type is set to SparkFun Blynk Board.

Select the Blynk Board board

Monitoring the Monitor

Once you’ve uploaded the code, set up your Blynk project, and connected the hardware. You should be all set to monitor your laundry machines!

RGB Status LED

You may want to test the apparatus out with some manual shaking first. Aside from the LCD and gauge widgets, the Blynk Board’s RGB LED should also relay information about the laundry monitor’s state.

LED ColorState
BlueBoard initializing, connecting to WiFi/Blynk.
GreenMonitor primed - laundry inactive.
PurplePreliminary shakes detected. "Start time" hasn't been fully triggered yet.
RedLaundry machine active!
OrangePreliminary laundry stoppage. No shaking, but the full "stop time" hasn't elapsed yet.

Once the board connects to WiFi and Blynk, the LED should turn green. As you begin to shake the sensor it should turn purple. Continuing to shake beyond the “start time” settings should turn the LED red, and it will remain red as long as you continue shaking above the threshold.

Once the shaking stops, the LED should turn orange. And as long as the shaking stays below the threshold for the set “stop time” setting, the LED will eventually turn back to green.

When the LED turns from orange to green, the Blynk Board will send a notification – assuming the “Enable Push” button is ON.

Continue shaking the sensor until you get a feel for how all three the sliders affect the board’s state.

Place the Sensor!

Load up your laundry, add your detergent, and set the laundry monitor up on top of your appliance. Use this first load to gauge some of the time and threshold settings that need adjusting.

Monitor in place

While the machine is rocking, you should see the “shakiness” gauge widget doing some rocking of its own. Tune the threshold slider up or down so it only triggers when the machine is running. Messages on the LCD should tell you whether or not the Blynk Board thinks your laundry is running.

Watch for any “fake stops”, and turn the “Stop Time” slider up accordingly. If you feel like everything’s set where it needs to be, turn the “Enable” button on, and go take care of other household needs. When your machine stops shaking, your phone should let you know!

Laundry done notification

Resources & Going Further

You can find the code from this project, as well as more examples in our Blynk Board GitHub repository.

For more Blynk documentation, check out the docs section of Blynk.cc. Or check out their Blynk Arduino library GitHub repository to learn more about the Blynk Arduino API.

Looking for another project? More Blynk stuff?! Check out some of these tutorials.

ESP8266 Thing Development Board Hookup Guide

An overview of SparkFun's ESP8266 Thing Development Board - a development board for the Internet of...Things. This tutorial explains the circuitry driving the board, and how to get it up and running in an Arduino environment.

LED Cloud-Connected Cloud

Make a RGB colored cloud light! You can also control it from your phone, or hook up to the weather!
New!

Blynk Board Project Guide

A series of Blynk projects you can set up on the Blynk Board without ever re-programming it.
New!

Blynk Board Bridge Widget Demo

A Blynk project that demonstrates how to use the Bridge widget to get two (or more) Blynk Boards to communicate.

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


OpenLog Hookup Guide

$
0
0

OpenLog Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The OpenLog Data Logger is a simple-to-use, open-source solution for logging serial data from your projects. The OpenLog provides a simple serial interface to log data from a project to a microSD card.

OpenLog

SparkFun OpenLog Datalogger

Materials Required

In order to fully work through this tutorial, you will need the following parts:

Recommended Reading

If you are not familiar or comfortable with the following concepts, we recommend reading through these before continuing on with the OpenLog Hookup Guide.

Hardware Overview

Power

The OpenLog runs at the following settings:

OpenLog Power Ratings
VCC Input3.3V-12V (Recommended 3.3V-5V)
RXI Input3.3V-6V
TXO Output3.3V max
Idle Current Draw2mA
Active Current Draw6mA

The OpenLog draws 6mA when recording a 512 byte buffer, but as that process takes a fraction of a second, the average current draw is closer to 5mA. Keep in mind though that if you are recording a constant data stream at 115200bps, you will approach that 6mA limit.

Microcontroller

The OpenLog runs off of an onboard ATmega328, running at 16MHz thanks to the onboard crystal. The ATmega328 has the Optiboot bootloader loaded on it, which allows the OpenLog to be compatible with the “Arduino Uno” board setting in the Arduino IDE.

ATmega328

The brain of the OpenLog.

Interface

The primary interface with the OpenLog is the FTDI header on the board edge. This header is designed to plug directly into an Arduino Pro or Pro Mini, which allows the microcontroller to send the data over a serial connection to the OpenLog.

FTDI_Header

Serial Connection Header.

Because of the pin ordering that makes it compatible with the Arduinos, it cannot plug directly into an FTDI Breakout board.

There are also four SPI test points broken out on the opposite end of the board. You can use these to reprogram the bootloader on the ATmega328.

SPI Test Points

SPI Test Points.

If you need to use an ISP to reprogram or upload a new bootloader to the OpenLog, you can use pogo pins to connect to these test points.

The final interface for communicating with the OpenLog is the microSD card itself. Not only is this where the data is stored by the OpenLog, but you can also update the OpenLog’s configuration via the config.txt file on the microSD card.

microSD Card

All data logged by the OpenLog is stored on the microSD card. The OpenLog works with microSD cards that involve the following features:

  • 64MB to 64GB
  • FAT16 or FAT32

microSD Slot

microSD Slot on the bottom of the OpenLog.

Status LED

There are two status LEDs on the OpenLog to help you with troubleshooting.

  • STAT1 - This blue indicator LED is attached to Arduino D5 (ATmega328 PD5) and toggles on/off when a new character is received. This LED blinks when Serial communication is functioning.
  • STAT2 - This green LED is connected to Arduino D13 (SPI Serial Clock Line/ ATmega328 PB5). This LED only blinks when the SPI interface is active. You will see it flash when the OpenLog records 512 bytes to the microSD card.

Stat LEDs

Status LEDs on the OpenLog.

Hardware Hookup

There are two main methods for connecting your OpenLog to a circuit.

Basic Serial Connection

This hardware connection is designed for interfacing with an OpenLog if you need to reprogram the board, or log data over a basic serial connection.

Make the following connections:

OpenLog → FTDI Basic

  • GND → GND
  • GND → GND
  • VCC → 3.3V
  • TXO → RXI
  • RXI → TXO
  • DTR → DTR

Notice that it is not a direction connection between the FTDI and OpenLog - you must switch the TXO and RXI pin connections.

Your connections should look like the following:

OpenLog + FTDI

Once you have the connections between the OpenLog and the FTDI Basic, plug your FTDI board into a USB cable and into your computer.

Open up a serial terminal, connect to the COM port of your FTDI Basic, and go to town!

Project Hardware Connection

While interfacing with the OpenLog over a serial connection is important for reprogramming or debugging, the place where OpenLog shines is in an embedded project. This general circuit is how we recommend you hook up your OpenLog to a microcontroller (in this case, an Arduino Pro Mini) that will write serial data out to the OpenLog.

First you will need to upload the code to your Pro Mini you intend to run. Please check out the Arduino Sketches for some example code that you can use.

If you are unsure how to program your Pro Mini, please check out our tutorial here.

Once you have programmed your Pro Mini, you can remove the FTDI board, and replace it with the OpenLog. Make sure to connect the pins labeled BLK on both the Pro Mini and OpenLog (the pins labeled GRN on both will also match up if done correctly).

If you cannot plug the OpenLog directly into the Pro Mini (due to mismatched headers or other boards in the way), you can use jumper wires and make the following connections.

OpenLog → Pro Mini

  • GND → GND
  • GND → GND
  • VCC → VCC
  • TXO → RXI
  • RXI → TXO
  • DTR → DTR

Once you’re finished, your connections should look like the following:

OpenLog Pro Mini

Note that the connection is a straight shot with the OpenLog “upside-down” (with the microSD facing up).

Power up your system, and you are ready to start logging!

Arduino Sketches

There are six different examples sketches included that you can use on the Arduino when connected to an OpenLog.

  • OpenLog_Benchmarking - This example is used to test OpenLog. This sounds very large amounts of data at 115200bps over multiple files.
  • OpenLog_CommandTest - This example shows how to create and append a file via command line control through the Arduino.
  • OpenLog_ReadExample - This example runs through how to control the OpenLog via command line.
  • OpenLog_ReadExample_LargeFile - Example of how to open a large stored file on OpenLog and report it over a local bluetooth connection.
  • OpenLog_Test_Sketch - Used to test OpenLog with lots of serial data.
  • OpenLog_Test_Sketch_Binary - Used to test OpenLog with binary data and escape characters.

Firmware

The OpenLog has two primary pieces of software on board: the bootloader and the firmware.

Bootloader

As mentioned previously, the OpenLog has the Optiboot serial bootloader on board. You can treat the OpenLog just like an Arduino Uno when uploading example code or new firmware to the board.

Note: If you are using an OpenLog that was purchased prior to March 2012, the onboard bootloader is compatible with the "Arduino Pro or Pro Mini 5V/16MHz w/ ATmega328" setting in the Arduino IDE.

If you end up bricking your OpenLog and need to reinstall the bootloader, you will also want to upload Optiboot onto the board. Please check out our tutorial on installing an Arduino Bootloader for more information.

Compiling and Loading Firmware onto the OpenLog

If for any reason you need to update or reinstall the firmware on your OpenLog, the following process will get your board up and running.

First, please download the Arduino IDE version 1.6.5. Other versions of the IDE may work to compile the OpenLog firmware, but we have verified this as a known good version.

Next, download the OpenLog firmware and required libraries bundle.

Download OpenLog Firmware Bundle

If you would prefer the most up-to-date versions of the libraries and firmware, you can download them directly from the GitHub repositories linked below.

Note: We are using modified versions of the SerialPort and SdFat libraries in order to arbitrarily declare how big the TX and RX buffers should be. The OpenLog requires the TX buffer to be very small (0) and the RX buffer needs to be as large as possible. Using these two modified libraries together allows increased performance of the OpenLog.

Once you have the libraries and firmware downloaded, install the libraries into Arduino. If you are unsure how to manually install the libraries in the IDE, please check out our tutorial here.

Next, to take advantage of the modified libraries, modify the SerialPort.h file found in \Arduino\Libraries\SerialPort directory. Change BUFFERED_TX to 0 and ENABLE_RX_ERROR_CHECKING to 0. Save the file, and open up the Arduino IDE.

If you haven’t yet, connect your OpenLog to the computer via an FTDI board. Please double check the example circuit if you are not sure how to do this properly.

Open the OpenLog sketch you would like to upload, select the “Arduino/Genuino Uno” board setting under Tools>Board, and select the proper COM port for your FTDI board under Tools>Port.

Upload the code.

That’s it! Your OpenLog is now programmed with new firmware. You can now open up a serial monitor and interact with the OpenLog. On power up, you will see either 12> or 12<. 1 indicates the serial connection is established, 2 indicates the SD card has successfully initialized, < indicates OpenLog is ready to log any received serial data and > indicates OpenLog is ready to receive commands.

OpenLog Sketches

There are three included sketches you can use on the OpenLog, depending on your particular application.

  • OpenLog - This firmware ships by default on the OpenLog. Sending the ? command will show the firmware version loaded onto a unit.
  • OpenLog_Light - This version of the sketch removes the menu and command mode, allowing the receive buffer to be increased. This is a good option for high-speed logging.
  • OpenLog_Minimal - The baud rate must be set in code and uploaded. This sketch is recommended for experienced users but is also the best option for the highest speed logging.

Command Set

You can interface with the OpenLog via a serial terminal. The following commands will help you read, write, and delete files, as well as change the settings of the OpenLog. You will need to be in Command Mode in order to use the following settings.

While the OpenLog is in Command Mode, STAT1 will toggle on/off for every character received. The LED will stay on until the next character is received.

File Manipulation

  • new File- Creates a new file named File in the current directory. Standard 8.3 filenames are supported. For example, “87654321.123” is acceptable, while “987654321.123” is not.

    • Example: new file1.txt
  • append File - Append text to the end of File. Serial data is then read from the UART in a stream and adds it to the file. It is not echoed over the serial terminal. If File does not exist when this function is called, the file will be created.

    • Example: append newfile.csv
  • write File OFFSET - Write text to File from the location OFFSET within the file. The text is read from the UART, line by line and echoed back. To exit this state, send an empty line.

    • Example: write logs.txt 516
  • rm File - Deletes File from the current directory. Wildcards are supported.

    • Example: rm README.txt
  • size File - Output size of File in bytes.

    • Example: size Log112.csv
    • Output: 11
  • read File + START+ LENGTH TYPE - Output the content of File starting from START and going for LENGTH. If START is omitted, the entire file is reported. If LENGTH is omitted, the entire contents from the starting point is reported. If TYPE is omitted, the OpenLog will default to reporting in ASCII. There are three output TYPEs:

    • ASCII = 1
    • HEX = 2
    • RAW = 3

    You may leave off some trailing arguments. Check the following examples.

    Basic read + omitted flags:

    • Example: read LOG00004.txt
    • Output: Accelerometer X=12 Y=215 Z=317

    Read from start 0 with length of 5:

    • Example: read LOG00004.txt 0 5
    • Output: Accel

    Read from position 1 with a length of 5 in HEX:

    • Example: read LOG00004.txt 1 5 2
    • Output: 63 63 65 6C

    Read from position 0 with a length of 50 in RAW:

    • Example: read LOG00137.txt 0 50 3
    • Output: André-- -þ Extended Character Test
  • cat File - Write the content of a file in hex to the serial monitor for viewing. This is sometimes helpful to see that a file is recording correctly without having to pull the SD card and view the file on a computer.

    • Example: cat LOG00004.txt
    • Output: 00000000: 41 63 65 6c 3a 20 31

Directory Manipulation

  • ls - Lists all contents of the current directory. Wildcards are supported.

    • Example: ls
    • Output: \src
  • md Subdirectory - Create Subdirectory in the current directory.

    • Example: md Example_Sketches
  • cd Subdirectory - Change to Subdirectory.

    • Example: cd Hello_World
  • cd .. - Change to a lower directory in the tree. Note that there is a space between ‘cd’ and ‘..’. This allows the string parser to see the cd command.

    • Example: cd ..
  • rm Subdirectory - Deletes Subdirectory. The directory must be empty for this command to work.

    • Example: rm temps
  • rm -rf Directory - Deletes Directory and any files contained within it.

    • Example: rm -rf Libraries

Low Level Function Commands

  • ? - This command will pull up a list of available commands on the OpenLog.

  • disk - Show card manufacturer ID, serial number, manufacture date and card size. Example output is:

      Card type: SD2
      Manufacturer ID: 3
      OEM ID: SD
      Product: SU01G
      Version: 8.0
      Serial number: 39723042
      Manufacturing date: 1/2010
      Card Size: 965120 KB
  • init - Reinitialize the system and reopen the SD card. This is helpful if the SD card stops responding.

  • sync - Synchronizes the current contents of the buffer to the SD card. This command is useful if you have less than 512 characters in the buffer and want to record those on the SD card.

  • reset - Jumps OpenLog to location zero, reruns bootloader and then init code. This command is helpful if you need to edit the config file, reset the OpenLog and start using the new configuration. Power cycling is still the preferred method for resetting the board, but this option is available.

System Settings

These settings can be manually updated, or edited in the config.txt file.

  • echo STATE - Changes the state of the system echo, and is stored in system memory. STATE can either be on or off. While on, the OpenLog will echo received serial data on the command prompt. While off, the system does not read back received characters.
Note: During normal logging, echo will be turned off. The system resource demands for echoing the received data is too high during logging.
  • verbose STATE - Changes the state of verbose error reporting. STATE can either be on or off. This command is stored in memory. By turning off verbose errors, OpenLog will respond with only a ! if there is an error rather than unknown command: COMMAND. The ! character is easier for embedded systems to parse than the full error. If you are using a terminal, leaving verbose on will allow you to see full error messages.

  • baud - This command will open up a system menu allowing the user to enter a baud rate. Any baud rate between 300bps and 1Mbps is supported. The baud rate selection is immediate, and the OpenLog requires a power cycle for the settings to take effect. The baud rate is stored to EEPROM and is loaded every time OpenLog powers up. The default is 9600 8N1.

Remember: If you get the board stuck in an unknown baud rate, you can tie RX to GND and power up OpenLog. The LEDs will blink back and forth for 2 seconds and will then blink in unison. Power down the OpenLog, and remove the jumper. OpenLog is now reset to 9600bps with an escape character of `CTRL-Z` pressed three consecutive times. This feature can be overridden by setting the Emergency Override bit to 1. See config.txt for more info.
  • set - This command opens a system menu to select the boot up mode. These settings will occur at the next power-on and are stored in non-volatile EEPROM.

    • New File Logging - This mode creates a new file each time OpenLog powers up. OpenLog will transmit 1 (UART is alive), 2 (SD card is initialized), then < (OpenLog is ready to receive data). All data will be recorded to a LOG#####.txt. The ##### number increases every time OpenLog powers up (the max is 65533 logs). The number is stored in EEPROM and can be reset from the set menu. All received characters are not echoed. You can exit this mode and enter command mode by sending CTRL+z (ASCII 26). All buffered data will be stored.

      Note: If too many logs have been created, OpenLog will output error Too many logs, exit this mode, and drop to Command Prompt. The serial output will look like 12!Too many logs!.
    • Append File Logging - Also known as sequential mode, this mode creates a file called SEQLOG.txt if it is not already there, and appends any received data to the file. OpenLog will transmit 12< at which time OpenLog is ready to receive data. Characters are not echoed. You can exit this mode and enter command mode by sending CTRL+z (ASCII 26). All buffered data will be stored.

    • Command Prompt - OpenLog will transmit 12> at which time the system is ready to receive commands. Note that the > sign indicates OpenLog is ready to receive commands, not data. You can create files and append data to files, but this requires some serial parsing (for error checking), so we do not set this mode by default.

    • Reset New File Number - This mode will reset the log file number to LOG000.txt. This is helpful if you have recently cleared out a microSD card and want the log file numbers to start over again.

    • New Escape Character - This option allows the user to enter a character such as CTRL+z or $, and set this as the new escape character. This setting is reset to CTRL+z during an emergency reset.

    • Number of Escape Characters - This option allows the user to enter a character (such as 1, 3, or 17), updating the new number of escape characters needed to drop to command mode. For example, entering 8 will require the user to hit CTRL+z eight times to get to command mode. This setting is reset to 3 during an emergency reset.

      Escape Characters Explanation:The reason OpenLog requires CTRL+z hit 3 times to enter command mode is to prevent the board accidentally being reset during upload of new code from the Arduino IDE. There is the chance that the board would see the CTRL+z character coming through during bootloading (an issue we saw in the early versions of the OpenLog firmware), so this aims to prevent that. If you ever suspect your board has been bricked due to this, you can always do an emergency reset by holding the RX pin to ground during power up.

Configuration File

If you would rather not use the serial terminal for modifying the settings on your OpenLog, you can also update the settings by modifying the CONFIG.TXT file.

Note: This feature only functions on firmware verison 1.6 or newer. If you have bought an OpenLog after 2012, you will be running firmware version 1.6+

To do this, you will need a microSD card reader and a text editor. Open up the config.txt file (the capitalization of the file name does not matter), and configure away! If you have never powered up your OpenLog with the SD card before, you can also manually create the file. If you have powered up the OpenLog with the microSD card inserted previously, you should see something like the following when you read the microSD card.

Default SD Configuration

The OpenLog creates a config.txt and LOG0000.txt file on first power up.

The default configuration file has one line of settings and one line of definitions.

OpenLog Config File

Default configuration file written by the OpenLog.

Note that these are regular visible characters (there are no non-visible or binary values), and each value is separated by a comma.

The settings are defined as follows:

  • baud: The communication baud rate. 9600bps is default. Acceptable values that are compatible with the Arduino IDE are 2400, 4800, 9600, 19200, 38400, 57600, and 115200. You can use other baud rates, but you will be unable to communicate with the OpenLog through the Arduino IDE serial monitor.

  • escape: The ASCII value (in decimal format) of the escape character. 26 is CTRL+z and is default. 36 is $ and is a commonly used escape character.

  • esc#: The number of escape characters required. By default, it is three, so you must hit the escape character three times to drop to command mode. Acceptable values are from 0 to 254. Setting this value to 0 will disable escape character checking completely.

  • mode: System mode. OpenLog starts in New Log mode(0) by default. Acceptable values are 0=New Log, 1= Sequential Log, 2 = Command Mode.

  • verb: Verbose mode. Extended (verbose) error messages are turned on by default. Setting this to 1 turns on verbose error messages (such as unknown command: remove !). Setting this to 0 turns off verbose errors but will respond with a ! if there is an error. Turning off verbose mode is handy if you are trying to handle errors from an embedded system.

  • echo: Echo mode. While in command mode, characters are echoed by default. Setting this to 0 turns off character echo. Turning this off is handy if handling errors and you don’t want sent commands being echoed back to the OpenLog.

  • ignoreRX: Emergency Override. Normally, OpenLog will emergency reset when the RX pin is pulled low during power up. Setting this to 1 will disable the checking of the RX pin during power up. This can be helpful for systems that will hold the RX line low for various reasons. If Emergency Override is disabled, you will not be able to force the unit back to 9600bps, and the configuration file will be the only way to modify the baud rate.

How OpenLog Modifies the Config File

There are five different situations for the OpenLog to modify the config.txt file.

  • Config file found: During power up, OpenLog will look for a config.txt file. If the file is found, OpenLog will use the included settings and overwrite any previously stored system settings.

  • No config file found: If OpenLog cannot find the config.txt file then OpenLog will create config.txt and record the currently stored system settings to it. This means if you insert a newly formatted microSD card, your system will maintain its current settings.

  • Corrupt config file found: OpenLog will erase the corrupted config.txt file, and will rewrite both the internal EEPROM settings and the config.txt settings file to the known-good state of 9600,26,3,0,1,1,0.

  • Illegal values in config file: If the OpenLog discovers any settings containing illegal values, OpenLog will overwrite the corrupt values in config.txt file with the currently stored EEPROM system settings.

  • Changes through command prompt: If the system settings are changed through the command prompt (either over a serial connection or via microcontroller serial commands) those changes will be recorded both to the system EEPROM and to the config.txt file.

  • Emergency Reset: If the OpenLog is power cycled with a jumper between RX and GND, and the Emergency Override bit is set to 0 (allowing emergency reset), OpenLog will rewrite both the internal EEPROM settings and the config.txt settings file to the known-good state of 9600,26,3,0,1,1,0.

Troubleshooting

There are several different options to check if you are having issues connecting over the serial monitor, having issues with dropped characters in logs, or fighting a bricked OpenLog.

Check STAT1 LED Behavior

STAT1 LED shows different behavior for two different common errors.

  • 3 Blinks: The microSD card failed to initialize. You may need to format the card with FAT/FAT16 on a computer.
  • 5 Blinks: OpenLog has changed to a new baud rate and needs to be power cycled.

Double check subdirectory structure

If you are using the default OpenLog.ino example, OpenLog will only support two subdirectories. You will need to change FOLDER_TRACK_DEPTH from 2 to the number of subdirectories you need to support. Once you’ve done this, recompile the code up, and upload the modified firmware.

Verify the number of files in the root directory

OpenLog will only support up to 65,534 log files in the root directory. We recommend reformatting your microSD card to improve logging speed.

Verify the size of your modified firmware

If you are writing a custom sketch for the OpenLog, verify that your sketch is not larger than 32,256. If so, it will cut into the upper 500 bytes of Flash memory, which is used by the Optiboot serial bootloader.

Double check file names

All file names should be alpha-numeric. MyLOG1.txt is ok, but Hi !e _.txt may not work.

Use 9600 baud

OpenLog runs off of the ATmega328 and has a limited amount of RAM(2048 bytes). When you send serial characters to OpenLog, these characters get buffered. The SD Group Simplified Specification allows an SD card to take up to 250ms (section 4.6.2.2 Write) to record a data block to flash memory.

At 9600bps, that’s 960 bytes (10 bits per byte) per second. That is 1.04ms per byte. OpenLog currently uses a 512 byte receive buffer so it can buffer around 50ms of characters. This allows OpenLog to successfully receive all characters coming at 9600bps. As you increase the baud rate, the buffer will last for less time.

OpenLog Buffer Overrun Time
Baud RateTime per byteTime Until Buffer is Overrun
9600bps1.04ms532ms
57600bps0.174ms88ms
115200bps0.087ms44ms

Many SD cards have a faster record time than 250ms. This can be affected by the ‘class’ of the card and how much data is already stored on the card. The solution is to use a lower baud rate or increase the amount of time between the characters sent at the higher baud rate.

Format your microSD card

Remember to use a card with few or no files on it. A microSD card with 3.1GB worth of ZIP files or MP3s has a slower response time than an empty card.

If you did not format your microSD card on a Windows OS, reformat the microSD card and create a DOS filesystem on the SD card.

Swap microSD cards

There are many different types of card manufacturers, relabeled cards, card sizes, and card classes, and they may not all work properly. We typically use an 8GB class 4 microSD card, which works well at 9600bps. If you need higher baud rates, or larger storage space, you may want to try class 6 or above cards.

Add delays between character writes

By adding a small delay between Serial.print() statements, you can give OpenLog a chance to record its current buffer.

For example:

    Serial.begin(115200);
    for(int i = 1 ; i < 10 ; i++) {
        Serial.print(i, DEC);
        Serial.println(":abcdefghijklmnopqrstuvwxyz-!#");
    }

may not log properly, as there are a lot of characters being sent right next to each other. Inserting a small delay of 15ms between large character writes will help OpenLog record without dropping characters.

    Serial.begin(115200);
    for(int i = 1 ; i < 10 ; i++) {
        Serial.print(i, DEC);
        Serial.println(":abcdefghijklmnopqrstuvwxyz-!#");
        delay(15);
    }

Add Arduino Serial Monitor Compatibility

If you are attempting to use the OpenLog with the built-in serial library or the SoftwareSerial library, you may notice issues with command mode. Serial.println() sends both newline AND carriage return. There are two alternative commands to overcome this.

The first is to use the \r command (ASCII carriage return):

    Serial.print("TEXT\r");

Alternatively, you can send the value 13 (decimal carriage return):

    Serial.print("TEXT");
    Serial.write(13);

Emergency Reset

Remember, if you need to reset the OpenLog to a default state, you can reset the board by tying the RX pin to GND, powering up the OpenLog, waiting until the LEDs begin to blink in unison, and then powering down the OpenLog and removing the jumper.

If you have changed the Emergency Override bit to 1, you will need to modify the configuration file, as the Emergency Reset will not work.

Check with the Community

If you are still having issues with your OpenLog, please check out the current and closed issues on our GitHub repository here. There is a large community working with the OpenLog, so chances are that someone has found a fix for the problem you are seeing.

Resources and Going Further

Now that you’ve successfully logged data with your OpenLog, you can set up remote projects and monitor all the possible data coming. Consider creating your own Citizen Science project, or even a pet tracker to see what Fluffy does when out and about!

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

Check out these additional resources for troubleshooting, help, or inspiration for your next project.


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

Paper Circuit Pin

$
0
0

Paper Circuit Pin a learn.sparkfun.com tutorial

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

Introduction

This quick craft project shows you how to create a circuit using copper tape instead of wire to light up an LED and make a wearable piece of e-craft art. Build the circuit on a cardstock template, attach a design printed on vellum to diffuse the LED’s light and use a binder clip to turn the circuit on and off.

Download printable templates for the base card design and different overlay designs or design your own circuit using these instructions as a guideline.

alt text

Materials and Tools

Here is a list of all the materials and tools you’d need to follow along:

Notes:

  • You will use ~9" of tape per card.
  • Choose your favorite LED color - here are some of our 5mm LEDs.

Additional Materials:

  • Cardstock (to print templates or design your own)
  • ½" square of vellum, wax paper, rice or parchment paper- creates a nice diffused effect for the LED to shine through the robot’s heart
  • Clear Tape
  • Scissors
  • 9/16" Metal Binder Clip - from your local office supply store or online. The black plastic ones will not work with this project, they need to be all metal.
  • Adhesive Pin Back - from your local craft store or online
  • Decorating Supplies - stickers, markers, or paints to embellish your designs

Step 1: Print Template

Paper Pin Template - 10 per pages, double sided

alt text

Print the base templates (double-sided) on cardstock, and cut them out. Depending on your printer’s margin settings, it may take some adjustments to make sure the front and back align. If possible, set your margins to 0 in both your program and print settings.

Robot Design - 18 per page

alt text

Print your pop up graphics on vellum or thin paper, and cut them out. Fold along the dotted lines.

Step 2: Create Copper Traces

Time to create a path for our electricity with copper tape. The template has icons to help guide you in constructing the circuit.

Line A

Take a look at the template and find the circle marked A. Peel away a few inches of the paper backing from the copper tape, and stick it down along the grey line.

alt text

This line continues around the edge of the template to the front of the card.

alt text

On the front of the card, we’ll need to turn a corner with the tape. To keep a solid connection of copper around corners, we’ll be using a folding technique to press the tape into shape.

Start by sticking the copper tape down until you reach the corner, then fold the tape backward on itself. Use a fingernail or pen to give it a good crease at the edge.

alt text

Then, carefully move the tape down around the corner – you should see the fold forming – and press down flat against the paper. Continue along the line, folding around one more corner.

alt text

Continue the tape until the end of the gray line.

alt text

Cut when you reach the scissors icon.

alt text

Line B

Line B is similar to Line A – we’ll fold around two corners. Begin at the gray line marked B, making sure to leave an opening after Line A. The LED will bridge the gap between these pieces of copper tape later.

alt text

Cut at the end of the line.

alt text

Line C

The last copper tape line will also form a battery holder. This line travels over the edge of the template to the back, so don’t cut until the end of the line.

alt text

Once the copper reaches the edge, flip the template over and continue the line.

alt text

This line allows the top of the copper to fold down over the coin cell battery – the positive side of the battery is the top and negative side is the bottom – creating a ‘battery sandwich’ with copper tape touching each side.

Fold along the dotted line toward the back of the template to create the flap.

Do not put the battery in yet.

Step 3: Prepare and Place LED

Now that our copper tape is in place, it’s time to add the LED. The template has an LED symbol on the front. We’ll be bending the LED to fit over the red circle icon.

LEDs are polarized, which means they can only be installed one way. There is a positive and negative side to each LED – the longer leg is positive and shorter is negative. There is also a flat side on the bulb itself; this is the negative side.

Read more about LED polarity in our Light-emitting Diodes (LEDs) Tutorial .

alt text

Bend the positive leg of the LED flat, and make a small right angle bend so that it touches the copper tape marked with a + sign. Do the same to the negative side, and place the LED on the space between the tape as shown.

alt text

Use clear tape over the wires to hold down to the copper.

alt text

Step 4: Installing Battery and Switch

Once the LED is installed, it’s time to test our circuit by adding a battery. Carefully slip the battery underneath the folded flap we made earlier, and center it inside the circle icon. Make sure the positive side of the battery (top, marked with the battery model and +) is facing up.

alt text

Press the flap over the battery, then use the binder clip to hold everything together.

alt text

Flip the project over, and use the handle of the binder clip as a switch to connect the battery to the rest of the copper tape circuit. Flip it back up to turn off. The back handle can be flipped down and taped for extra stability.

alt text

alt text

Step 5: Decorate and Customize

Now that the project is lighting up, it’s time to customize!

If you downloaded a graphic, print on vellum or thin paper to create a lantern effect. Cut along the solid lines, and fold along the dotted lines. Secure with tape around the edges of the project.

alt text

Add an adhesive pin back placed on the labeled rectangle to make the project wearable.

alt text

Resources and Going Further

You should now have a wearable paper circuit badge that you can wear with pride!

For more e-craft project ideas, check out these other SparkFun tutorials.

Light-Up Father's Day Card

Light up your dad's day with this electronic pop-up card!

Light-Up Valentine Cards

Light up your love with paper circuits - no soldering required!

Heartbeat Straight Jacket

An EL project that displays one person's heartbeat on another person's costume.
New!

Paper Circuit Pin

This quick craft project shows you how to create a circuit using copper tape instead of wire to light up an LED and make a wearable piece of e-craft art.

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

Raspberry Pi 3 Starter Kit Hookup Guide

$
0
0

Raspberry Pi 3 Starter Kit Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Now that the Raspberry Pi 3 is the latest and greatest in the line of Raspberry Pi Single Board Computers, what’s new? This hookup guide goes through the same process of getting going that worked with the Pi 2, but from a Pi 3 point of view.

Raspberry Pi 3 Starter Kit

KIT-13826
$89.95

Covered in This Tutorial

Materials Required

You’ll need a mouse, keyboard, and monitor to begin with. Once configured, the pi can be operated from its own peripherals or another computer connected over the internet.

Note: The serial port still has a few bugs, so it's not recommended to use for configuration. Raspbian can be hacked to get it to work but it's not covered by this guide. This Pi forum post talks about the serial port in more depth.

As a desktop, these materials are required:

  • Pi 3 Starter kit -or- Pi 3/2 Accessory Kit and your own Pi
  • USB Mouse
  • USB Keyboard
  • HDMI monitor/TV/adapted VGA

After configuration, ‘headless’ operation over Telnet/SSH requires:

  • Pi 3 Starter kit -or- Pi 3/2 Accessory Kit and your own Pi
  • 2nd computer connected via internet
  • Telnet/ssh terminal software

You’ll also need an internet connection to get resources! This link can be wired or wifi and must be available for the Pi. For wireless connections, check out our WiFi Adapter.

Suggested Reading and Viewing

You may want to check out the following tutorials and videos before continuing.

Assembly

The Pi is straight-forward and easy to put together, but, in the event that something doesn’t seem right, this section will give you an idea of what it is supposed to look like.

alt text

Unbox and gather these components before beginning the assembly

  1. Snap the Pi into the base of the ‘tin’, then snap the top into place.

    alt text

    Fit the Pi into the base of the tin. Make sure the Pi is fully seated. Check that the PCB is evenly recessed about the perimeter.

    alt text

    Click the two halves together/center>

  2. Add the SD card

    alt text

    Installing an SD card – make sure the microSD card is flush with the side of the case when inserted properly. The Pi 3 microSD slot doesn’t have a spring as the previous pis did, so if it’s flush with the label outward, it is seated correctly.

  3. Connect the ribbon cable to the Pi – notice that the pin 1 marking is very subtle. Orient the red stripe on the cable towards the SD card. Alternately, pin 1 can be identified by finding the missing/beveled corner of the header’s silkscreen on the pi.

    alt text

    The pin 1 location and silkscreen is the same between the Pi B+ and Pi B. This image shows a partially inserted ribbon cable without the case in the way. The ribbon cable is oriented with the red “pin 1” marking pointing towards the SD card slot.

  4. Attach the ribbon cable to the wedge. Pin 1 is pointing towards the FTDI adapter.

    alt text

    Socket the end of the ribbon cable into the Wedge. It is keyed, but each end of the cable is different. Make sure the ribbon extends away from the breadboard connection.

  5. Socket the Wedge into your breadboard

    alt text

    Wedge inserted in breadboard.

  6. Attach the FTDI connector matching “GRN” to “GRN” and “BLK” to “BLK” between the boards.

    alt text

    The FTDI serial adapter is connected matching GRN and BLK connections

  7. Attach desired consumer computer equipment.

    alt text

    The fully assembled kit. Additional to the kit, user supplied monitor, mouse, and keyboard are shown. This Pi is now a desktop computer.

Getting an OS

Note: At the time this was written, the kit comes with a 16GB card loaded with the Noobs OS installation image, version 1.9.0. This card should be ready to boot right out of the box.

Getting a New Image

If something didn’t work, or the installation has been corrupted (messing around in the file system were you?), getting a new copy is easy.

  • Obtain the Noobs OS from raspberrypi.org.
  • Format the card to erase all the files.
  • Unzip the contents of the Noobs zip file to the empty, formatted microSD card.

That’s it! You’re ready to go. For other imaging, check out this tutorial on sd cards and writing images. You can also check out this guide from the Raspberry Pi foundation.

The First Boot

Before you apply power for the first time, run through this pre-flight checklist.

  • Is the microSD card installed and seated firmly?
  • Is the HDMI attached and the monitor powered?
  • Are the mouse and keyboard plugged in?
  • Are the mouse and keyboard standard USB, not wireless? – Some wireless keyboards have trouble enumerating, so use one you trust.
  • Is the whole setup secure on your desk and not liable to jump onto the floor at the first touch?

Ok, you’re ready to apply the power to the Pi.

Power Adapter Requirement! Make sure the power being supplied is from a the included 5.24V, 2.4A power supply and not your USB connection. The USB most likely won’t have enough current supplying capacity and will result in a brown-out of the Pi that can damage it, and it will likely mess up the files on your SD card.

First, you should see a color chart appaer on your screen that indicates the Pi has power and is doing something but doesn’t have software loaded yet.

Next, Noobs asks if the raspbian distro should be installed. Check the box to select it, and choose your language/keyboard layout here (can also be changed later).

Noobs will take a few minutes to manage the partitions and install the OS.

When it’s done, it should report that the OS was installed successfully. Click OK, the Pi will reboot into a graphical interface.

The Noobs default configuration is to auto-log in as user pi, password raspberry.

Performing a Full System Upgrade

Once connected to the Internet (see the Configuring the Pi section), it can be a good idea update all the packages that are currently installed. Usually, new packages replace old ones that are faulty, but sometimes new packages have bugs of their own. If your current system is stable and all the functions are good, maybe don’t upgrade. If you’re starting a fresh project though, get everything up-to-date before you start putting in the work.

Enter the following commands in the shell (process takes about 10 minutes).

  • sudo apt-get update– go fetch the latest package information.
  • sudo apt-get upgrade– And answer Y. Upgrades all the packages. This stage will take a while.
  • sudo shutdown -r now– Reboot the machine.

Methods of Working with the Pi

Once the Pi is configured, there are a few methods of using it depending on if you want to use it like a desktop or manage it remotely.

This section covers using the Pi in the following ways

  • Using HDMI-out – Operate your Pi like a desktop computer.
  • Using the serial terminal – some functionality but buggy in the latest Raspbian release.
  • Using SSH – Operate through a network linked to another computer.

Using HDMI-out

Noobs 1.8.0, with Raspbian, automatically logs in and starts a graphical user interface.

If configured to boot to shell, log in with pi as the user name and raspberry as the password. Then, enter startx to enter a graphical environment where you are presented with a desktop-type menu-driven operating system.

If you need to get back to text land, you can either

  • log off through the Task Bar Menu – drops back to the shell, closing down the X window system
  • open xterm from the Task Bar – opens a shell in a graphical window
  • Use CTRL-ALT-1 through CTRL-ALT-8 – gives you a number of shells, with 7 being the graphic environment (if loaded).

Remember, shutdown with the menu item or enter sudo shutdown -h now from a shell, and wait for the system to halt before removing power.

Using the Serial Terminal without a Monitor

Connect the FTDI to the mini-usb cable and plug into a usb port on your computer.

Set the serial settings to 72000 baud, 8 bit, no parity, 1 stop and no flow control. This is an odd rate that is 1.6 times slower than before. Also, CPU frequency effects the symbol rate so be careful if using this interface, and plan for administering by a different method.

Using SSH

A good way to operate a Pi is to attach it to the local network somewhere, then manage it from another computer connected to that same network.

Note: This method relies on a local Internet connection. Work through the configuration process with the monitor/mouse/keyboard or serial terminal (described below), then come back here.

To do this, download PuTTY or a similar SSH terminal for your system and connect to the Internet port used by the pi. The TTY interface gives you a serial-like interface but with colors that make it a little nicer to use.

alt text

A PuTTY terminal looks nicer than serial and can be used over networks

To obtain your IP address, get to a terminal, and use the command ifconfig. Alternately, hover the mouse pointer over the network icon on the task bar.

With Ethernet and wireless attached, ifconfig returns something like the following:

pi@raspberrypi:~$ ifconfig
eth0      Link encap:Ethernet  HWaddr b8:a8:3b:56:1a:f7
        inet addr:14.7.3.188  Bcast:14.7.3.255  Mask:255.255.255.0
        UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
        RX packets:3026 errors:0 dropped:0 overruns:0 frame:0
        TX packets:462 errors:0 dropped:0 overruns:0 carrier:0
        collisions:0 txqueuelen:1000
        RX bytes:229516 (224.1 KiB)  TX bytes:60888 (59.4 KiB)

lo        Link encap:Local Loopback
        inet addr:127.0.0.1  Mask:255.0.0.0
        UP LOOPBACK RUNNING  MTU:65536  Metric:1
        RX packets:8 errors:0 dropped:0 overruns:0 frame:0
        TX packets:8 errors:0 dropped:0 overruns:0 carrier:0
        collisions:0 txqueuelen:0
        RX bytes:1104 (1.0 KiB)  TX bytes:1104 (1.0 KiB)

wlan0     Link encap:Ethernet  HWaddr 74:df:21:5b:a3:9c
        inet addr:32.8.0.142  Bcast:32.8.0.255  Mask:255.255.255.0
        UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
        RX packets:120 errors:0 dropped:40 overruns:0 frame:0
        TX packets:12 errors:0 dropped:4 overruns:0 carrier:0
        collisions:0 txqueuelen:1000
        RX bytes:20955 (20.4 KiB)  TX bytes:9956 (9.7 KiB)

If it looks similar but the IP addresses aren’t present, that network link hasn’t been established.

In this example, we know our Ethernet is on IP 14.7.3.188 and our wireless on 32.8.0.142. These can be entered into the PuTTY configuration window to begin the session. From here, it just works like the serial link!

alt text

Configuring PuTTY

Configuring the Pi

This section goes over configuring the keyboard, wired, and wireless internet.

Configuring the Keyboard Layout

The Raspbian distribution comes defaulted to European hardware. With US keyboards, the “ (quotation mark) symbol is replaced by @ (commercial at) and our number sign # is replaced by the European pound sign £. This can make it aggravating when trying to #define things. Invoke the config tool with "sudo raspi-config,” and take the following actions:

Set the default locale for the system

  • Select “Internationalisation Options”
  • Select “Change Locale”
  • Deselect en_GB.UTF-8 UTF-8
  • Select en_US.UTF-8 UTF-8, (Ok)
  • Set default to en_US.UTF-8, (Ok)

Change the keyboard layout– from the Internationalisation Options menu,

  • Change Keyboard Layout
  • Leave set as: Generic 105-key (Intl) PC (Ok)
  • Select Other (Ok)
  • Select English (US) (Ok)
  • Select English (US) (Ok)
  • Select default (Ok)
  • Select No compose key (Ok)
  • Set Ctrl+Alt+Bksp function (Ok)

Finish with the dialog and get back to the shell

Try the “ and # keys at the prompt. It may be necessary to restart the pi at this point.

Configuring the Internet Interfaces

Automatic Configuration

Raspbian does a good job of configuring wireless networks automatically. By default, DHCP is configured so that the Pi will receive an IP address when a network cable is plugged it to the Ethernet port or when a wireless network is connected.

To use the graphical network tool, right click on the icon on the right side of the task bar, and click “WiFi Networks (dhcpcdui) Settings”. Then, select the interface desired (wlan0 or eth0) to disable the DHCP and set your own IP, if necessary.

To connect to a wireless network, click on the icon, select the desired network, and enter the password.

Hovering over the icon will bring up a status of wlan0 and eth0 that also shows the IP address.

Manual (text-based) Configuration

At this time, the network configuration works out of the box so there’s really nothing to configure, but in case something goes awry, here’s the basics of what can be played with and a known-working configuration to compare with.

A configuration file, interfaces, configures both wired and wireless devices. Enter the following command into a terminal to edit the interfaces file.

sudo nano /etc/network/interfaces

Replace “nano” with “leafpad” if you prefer graphics. Here’s what our Pi 3 is using:

# interfaces(5) file used by ifup(8) and ifdown(8)

# Please note that this file is written to be used with dhcpcd
# For static IP, consult /etc/dhcpcd.conf and 'man dhcpcd.conf'

# Include files from /etc/network/interfaces.d:
source-directory /etc/network/interfaces.d

auto lo
iface lo inet loopback

iface eth0 inet manual

allow-hotplug wlan0
iface wlan0 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

allow-hotplug wlan1
iface wlan1 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

By default, this file is set up to get its configuration from /etc/wpa_supplicant/wpa_supplicant.conf, which is really the proper place for wifi information. Here are the contents:

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1

network={
        ssid="myNetworkSSID"
        psk="mySuperSecurePassword"
        key_mgmt=WPA-PSK
}
A note on network configuration: Try the gui tool first, and only modify the files as a last resort. If you find the tool doesn't work, save your configuration files as a backup, and don't be afraid to try your hand at a manual configuration.

Applying the Changes

Sometimes the link should be cycled for a new configuration to take. Rather than shutting down the pi and restarting, use ‘ifdown’ and ‘ifup’ to bring the link down and back up.

For wireless connections, use

sudo ifdown wlan0

and

sudo ifup wlan0

For wired connections, use

sudo ifdown eth0

and

sudo ifup eth0

Reading Inputs and Toggling the LEDs

This section contains instructions for getting the software necessary to compile programs that use the GPIO, then redirects to our Raspberry gPIo tutorial.

Getting WiringPi for Using C++

The WiringPi library is required to operate the GPIO with C++. There are two methods to get it, mentioned below. Either way, it will have to be built before use.

Get From the WiringPi Website

The first way to obtain it is to download from a direct link to the WiringPi website: http://wiringpi.com/download-and-install/.

Get Using Git (Preferred)

Another way to obtain it is using apt-get to obtain git, then by using git to get the repository.

  • Install Git – Enter sudo apt-get install git-core (may be installed by default)
  • Git the wiringPi repo – Enter sudo git clone git://git.drogon.net/wiringPi

This will make a folder in your current directory called WiringPi.

Build WiringPi

However it was obtained, the first step is to build the WiringPi library. The source comes with a script to do all this for you.

  • Go to the WiringPi directory – Enter cd wiringPi
  • build the WiringPi resources – Enter sudo ./build

This builds the helper files, modifies some paths in Linux and gets WiringPi ready to rock.

At this point, the library should work. Try it out

  • Enter gpio readall

An Ascii table of pins and states should appear.

Getting Python

Raspbian comes with Python pre-installed. Continue to the gPIo tutorial to find out how to use it.

Using the GPIO.

This excellent tutorial covers all the INs, OUTs, and PWMs of GPIO with the Pi platform.

Raspberry gPIo

October 29, 2015

How to use either Python or C++ to drive the I/O lines on a Raspberry Pi.

Resources and Going Further

With the Pi 3 reading buttons and toggling LEDs, you’re sure to be the coolest kid on the block, but what else can it do? Let us know how you use your Pi 3 in the comments!

Here are some links to our other Pi resources.

Need some inspiration?


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

SIK Keyboard Instrument

$
0
0

SIK Keyboard Instrument a learn.sparkfun.com tutorial

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

Introduction

The SparkFun Inventor’s Kit (SIK) is a great starting place for learning about electronics, programming, and physical computing. We can combine some of the concepts found in the SIK Guide to make our own projects. In this tutorial, we will make a keyboard using parts found in the SIK.

SIK Piano Keyboard

We can use the Arduino to read the location of a touch on the soft potentiometer strip (“soft pot”) and use that information to play a particular note from the buzzer. While it may be small, we can divide the soft pot into 8 segments. That’s enough for a scale! In this case, we’ll use the C major scale.

Required Materials

From the SIK, you will need:

In addition, you will need a few tools:

  • Scissors
  • Masking tape
  • Hobby knife
  • Ruler
  • Pen or Sharpie
  • Cardboard (a small box is preferable)

Other required tools

Suggested Reading

Before continuing with this project, we suggest you be familiar with a few concepts:

Hardware Hookup

Prepare the Breadboard

Before connecting anything, we recommend separating the breadboard into its three parts. Use a pair of scissors to cut the adhesive backing. This part is optional, but it helps the breadboard fit into the project enclosure later.

Cutting the breadboard

Connect the Components

Once you are ready to connect the components, check out the Fritzing diagram below.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

SIK keyboard Fritzing diagram

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

Once you are done, the soft pot should be sticking straight up from the breadboard.

Completed wiring

Create the Keyboard

The “keyboard” is actually the soft potentiometer. We will divide up the soft pot into eight (8) segments, and the resistance we read with the Arduino from touching the soft pot will determine the key being pressed.

To create something that looks like a keyboard, place a piece of masking tape over the soft pot so it covers the entire length with some overhand (we will use the overhang to attach the soft pot to the box).

Tape on the soft pot

Place a ruler next to the touchable (silver) area on the soft pot. Starting from the breadboard end, mark every 6mm. Fill in or note that the first 6mm section is not to be used.

Marking out the keyboard

Starting from the breadboard side, write the note of each key in between the marks. We’ll use C, D, E, F, G, A, B, C.

Marking notes on the keys

Make the Project Box

While we can play our keyboard on the breadboard, it might be more fun to have it in a project box to add a little stability.

Peel the backing off the two pieces of the breadboard to which we attached components.

Peel off the breadboard backing

Attach the large breadboard piece to the side of the cardboard box with the soft pot lying flat on the box’s floor. Stick the smaller breadboard piece (the one with the buzzer) to the box’s floor opposite the soft pot. Stick the overhang tape on the soft pot to the floor of the box.

Attach the breadboard pieces to the inside of the box

Fold a piece of tape over (into a loop), and stick it to the RedBoard.

Sticking tape to the RedBoard

Place the RedBoard in between the soft pot and top breadboard piece.

Arduino in place

Use the scissors to remove the top of the box.

Cut off the box top

Use the hobby knife to cut a hole in the side of the box so you can pass the USB cable through for power.

Cut a hole in the box

Cut a large notch in the front of the box just above the keyboard. This allows for easier access to the keyboard.

Cut a hole in the front to access the keyboard

The Code

To program the Arduino from your browser, select SparkFun RedBoard in the first drop-down menu in the window below, select the COM port associated with your RedBoard, and click Run on Arduino.

NOTE: For this example, we're hosting the code on codebender, which not only features code-sharing, but also allows anyone to upload and debug Arduino sketches from within a web browser. Plus, it works on lower-tech machines, like Chromebooks!

There are codebender plugins for Chrome, Chromium, and Firefox. Visit the codebender plugin page for help installing the codebender plugin.

If you would like to use the Arduino IDE instead, copy the following code into the editor and click the Upload button.

NOTE: If the Codebender embedded window did not show up, go here to see the code.

Code to Note

We combine the code from Part 10: Reading a Soft Potentiometer and Part 11: Using a Piezo Buzzer in the SIK Guide, and we recommend you read the “Code to Note” sections in each of those to understand how we are getting data from the soft pot as well as playing particular frequencies on the buzzer.

language:c
if ( (val > 10) && (val <= 160) )
{
    return 'c';
}
...

We pass the findNote(int val) function the analog-to-digital (ADC) value read from the soft pot. This information is stored in the val parameter. If we touch the soft pot towards the breadboard end, it will produce a lower value than if we touched it at the other end. The ADC value on the Arduino can be between 0 and 1023 (inclusive). So, we would read a value close to 10 if we touched it on the breadboard end and a value close to 1023 on the other end.

Since we divided up the soft pot’s length into 6 mm segments, we also need to divide up the values we might receive from the soft pot. Let’s say we touched the soft pot on the third segment (the one we labeled “E”), and the ADC value was 296 as a result. The first two if statements would return false, but the third one would be true, since 296 falls between 250 and 350. So, ‘e’ is returned as the note we pressed on the soft pot.

What You Should See

Once you have uploaded the code to the RedBoard, try lightly pressing on the soft potentiometer. You should hear some musical notes from the speaker!

Playing the keyboard instrument

Want to play a song? How about Twinkle, Twinkle, Little Star (‘C’ is the first ‘C’ on the left in this case):

C, C, G, G, A, A, G (hold)
F, F, E, E, D, D, C (hold)

What other songs can you play? Here are some ideas to get you started.

Troubleshooting

No Sound

Given the size and shape of the piezo buzzer it is easy to miss the right holes on the breadboard. Try double checking its placement. Additionally, check the wiring for the soft pot.

Can’t Press More than One Key

The soft potentiometer is incapable of detecting more than one press at a time. What happens if you try to press two keys at once?

Going Further

Taking the Next Steps

Now that you’ve built your keyboard and had a chance to play a song, we can look at taking the project a bit further.

Other Projects

Need more inspiration for other Arduino-based projects? See these tutorials:

Reaction Timer

Demonstrate mental chronometry with this simple reaction timer!

RedBoard Santa Trap

A fun holiday project to try for anyone looking to catch Santa on Christmas!

Alphanumeric GPS Wall Clock

This is a GPS controlled clock - a clock you truly never have to set! Using GPS and some formulas, we figure out what day of the week and if we are in or out of daylight savings time.

LED Cloud-Connected Cloud

Make a RGB colored cloud light! You can also control it from your phone, or hook up to the weather!

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

Shapeoko Assembly Guide

$
0
0

Shapeoko Assembly Guide a learn.sparkfun.com tutorial

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

Introduction

SparkFun’s Deluxe Shapeoko kit is a Carbide3D Shapoko 3 in fancy SparkFun red with our open source 3 axis mill driver, the Stepoko.

alt text

The full kit. In this picture, the Shapeoko parts have been assembled as per the Shapeoko guide, and the SparkFun kit parts are shown beside it.

Guide Content

This guide directs you to the Shapeoko assembly instructions, then goes through the final steps to add the electronics to the mill.

Required Materials

Suggested Reading

Stepoko guide - This guide talks about how the Stepoko control electronics works. Important information is also linked below.

Assembly

  1. Follow the Shapeoko assembly instructions until you get to the part where controller is added. There are a few differences, for instance the motors in this kit have equal length wires, but nothing too significant. Use the parts list from downloaded from the “Required Materials” section above rather than the list from the assembly guide.

    Set Aside Some Time It may take about four hours to complete the initial assembly. Once you’ve got it, continue on.
  2. Install the Shapeoko into the enclosure. There are 10 4-40 screws for this purpose, but you’ll only need 8. Use a number 1 phillips screwdriver.

    alt text

    To get the Stepoko into the enclosure, put the ‘port end’ in first.

    alt text

    Installing the 4-40 screws
  3. Get ready to install the controller. Test fit it first, but don’t install just yet, set it down such that the pad can be added, and then it can be rotated into position. Make sure the aluminum heatsink and extruded mill rail are clean and free of debris.

    alt text

    Test fitting the enclosure – the motor wires will go through the top

    alt text

    Here the enclosure is ready to rotate up onto the mill into the correct orientation. This picture is shown with the wires installed. Don’t worry if yours are not installed yet, that will be covered later.
  4. Peel one side’s protective sheet away and discard. Both sides will be removed, but just peel one for now.

    alt text

    Peeling the protective sheet. Once removed, the rigidity of the material changes completely
  5. Holding by the corners, lower the pad onto the exposed heat sink, and gently press into place. Generally, it just needs to be centered and overlapping the edge of the heat sink. It’s been sized so that the following two points can insure it’s in the correct position:

    • The long edge is flush with the enclosure’s edge, towards the motor wires.
    • The short edge is flush with the keyholed mounting hole.

    alt text

    Lowering the pad

    alt text

    Checking for proper alignment. Here, my thumb checks flushness on one edge while I point out the proper alignment near the mounting hole.
  6. Peel the second protective layer away.

    alt text

    Removing the protective sheeting
  7. Install the Stepoko controller. The pad will add thickness and cause the enclosure to sit off the mill, so don’t tighten the mounting bolts down too hard. Use threadlocker to keep the screw from backing out due to vibrations. Alternately, a flat washer that’s slightly thinner than the pad can be used here.

    alt text

    Applying threadlocker – Here, a bit too much is used. It only needs to be filling in the treads. Excess may run.

    alt text

    The finished installation. Notice that the enclosure is nice and even and not deformed along the mill.
  8. Install the enclosure to the rail with the terminal connections at the top. Use the extra M6x12mm bolts provided with the Shapeoko.

  9. Connect the X and Z axes to the Stepoko. For more information, check the Stepoko guide’s Hardware: Connecting the Motors section.

    alt text

    The X and Z axis are connected.
  10. Connect the Y axis. But wait! It has two motors that are wired in parallel.

    If two stepper motors are connected in parallel, they may not spin in the same direction because the internal polarities may not be the same. The solution to this problem is to transpose the colors of one pair of coil wires. This polarity/spin direction problem is compounded by the fact that the motors are mirrored on the mill and actually need to spin different directions.

    Watch the video below go get a basic idea, then work through these steps.

    • Connect short leads to the Y axis terminals.
    • Identify the coils.
    • Group one coil from each motor together by color, except with reversed polarities.
    • Twist the ends to test.
    • Try and move the mill in the Y axis. If it moves smoothly, solder the wires and apply heatshrink/electrical tape, or use wire nuts.
    • If the axis moved roughly, unlike the X and Z axes, filp one of the pairs of coils so that it has the same colors combined, but leave the other reversed. This is because the motor’s coils are not always wired the same internally.

    Take a quick look at this video to see, and hear, how the Y axis when wired incorrectly, and correctly.
  11. Set the motor drive currents. Make sure the trimpots are in the center for 1A service until you are more experienced. Or, read up on how the current setting works in the Stepoko Guide’s Hardware: Setting the current section.

    alt text

    The trimpots are centered for 1 A drive in this photograph.
  12. Mount the switch to a free hole on the gantry end plate and solder on leads.

    alt text

    Here the switch has been mounted and the switch wires are being measured. They go into the two terminals labled E-Stop.

    alt text

    Soldering on the leads.

    alt text

    All of the wires are added for this mill setup.
  13. Screw in the lid to the enclosure using a number 1 or 2 phillips.

    alt text
  14. Collect your wires and bind with twist ties or zip ties.

    alt text

    The Y axis wires have been twist tied together here. The X and Z axes are gently pulled out to see how long they are.

    alt text

    With the X axis moved ofer to one end, I can see that my bound wires have enough slack so that they won’t be pulled on when the carriage moves.
  15. Connect the power supply, power cord, and USB cord between your computer and the Stepoko

  16. Open up the Universal Gcode Sender, open the Stepoko’s serial port, and select the machine control tab. Set the switch to ‘ON’ and try to move the machine by computer control. If the axis move in the wrong directions to your liking (but of course, up should be positive Z), switch the direction bit field accordingly. Use the Stepoko guide’s Software: Machine Control section for more information about grbl, or check out grbl’s Github wiki for more information on changing settings.

  17. Measure know movements and calibrate each axis. See the Stepoko guide’s Firmware: Configuring grbl and Calibrating section for more info.

Finishing Touches

The cable carriers have been included in your kit to help with wire management, but it’s up to you to decide what cables to carry, and where you you would like them to be. They can go either way on an axis, and don’t need to be full length to get the job done.

This section shows installing a cable carrier for the gantry.

  1. Pull the wires through the carrier. A hooked wire, or taping on a straight wire, helps. When running multiple groups of similar colors through, mark each set differently with sharpie or tape.

    alt text

    Use a helper wire to thread the cable carriers. Here, 4 of the 8 wires have a tape wrap to indicate that they belong to the same motor

    alt text

    The wires are probably not long enough to pull through with a bend, so carefully work the ends free.
  2. Hold the assembly in place and move the gantry through the full range to make sure the cable carrier has unrestrained motion along the axis of movement. The cable carrier should be shortened if there’s not enough play in the wires, or the loop hangs too far off the mill.

  3. After you’ve located where the fixed end will be, cut a small piece of double-sided tape and firmly squish the carrier down. For these Shapeoko mills, make sure nothing crosses the center line in the extrusion.

    alt text

    Here, the tap is being dispensed directly onto the location and cut, right in place. Notice that it does not cross the center line.
  4. Check that the wires will reach the terminals, that the gantry can move along the full range, and that the roller bolt misses the cable carrier. Then connect the motor wires for the final time.

    alt text

    A view of the installed cable carrier. Also show, the strip of cable carrier on the enclosure is a convenient place to stuff fixed wires – just pull them in with your wire hook. This is made from extra bits of the other carriers from when they were shortened.

    alt text

    The roller clears the cable carrier with no problems! If this is not the case, simply peel up the cable carrier and try again.

Resources and Going Further

Here’s some links and projects you may find useful.

Or, head back to the The Stepoko and Shapeoko Landing page to see what accessories and tools are available.

Now that you have built your Shapeoko Mill, check out these other SparkFun tutorials to learn how to use the SparkFun Stepoko Control board.

Once you’re familiar with the Stepoko, create your first project by following along with the Shapeoko SparkFun Coaster.

Shapeoko Coaster Project

November 20, 2015

A step-by-step guide to cutting and engraving a coaster with the Shapeoko.

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

Viewing all 1123 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>