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

IoT Weight Logging Scale

$
0
0

IoT Weight Logging Scale a learn.sparkfun.com tutorial

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

Introduction

This tutorial will show you how to hack a bathroom scale to post weight data to a custom website that you create! The principles involved in this can easily be adapted to work with any kind of sensor data you choose: insolation, temperature, weather data, or anything else that you want to track over time and get a visualization.

Project shot

It uses an ESP32 Thing to read load cell data from an HX711 Load Cell Amplifier and display that data on a Serial 7-Segment Display as well as posting it to a Python-based website that can be hosted locally or on the cloud.

Required Materials

Hardware

To follow this project, you would will need the following materials. You may not need everything though depending on what you have. Add it to your cart, read through the guide, and adjust the cart as necessary.

Software

I’ve chosen to use a remotely hosted Linux server on Linode to host my website, but if you so choose you can host it locally using a Raspberry Pi 3 or other flavor of Linux-based computer. You’ll need to download and install the ESP32 support package–instructions are available on that page. The library for the HX711 amplifier can be found and installed through the Arduino Library Manager. I used the one titled “HX711_ADC” by Olav Kallhovd, so make sure you download the right one. I used Python 2.7, which should be the default if you follow my instructions. You’ll also need to install Flask, matplotlib, and (maybe) tkinter. I’ll go through the installation instructions on those later.

Tools

No special tools are required to follow this tutorial. You will need a soldering iron, solder, general soldering accessories, and a screwdriver to disassemble the scale.

Solder Lead Free - 15-gram Tube

TOL-09163
$3.50
2
Soldering Iron - 30W (US, 110V)

TOL-09507
$9.95
6

Suggested Reading

Before undertaking this project, there are a few tutorials that you may want to review.

How to Solder: Through-Hole Soldering

This tutorial covers everything you need to know about through-hole soldering.

Using the Serial 7-Segment Display

How to quickly and easily set up the Serial 7-Segment Display and the Serial 7-Segment Display Shield.

Raspberry Pi 3 Starter Kit Hookup Guide

Guide for getting going with the Raspberry Pi 3 Model B and Raspberry Pi 3 Model B+ starter kit.

ESP32 Thing Hookup Guide

An introduction to the ESP32 Thing's hardware features, and a primer on using the WiFi/Bluetooth system-on-chip in Arduino.

Load Cell Amplifier HX711 Breakout Hookup Guide

A hookup guide for the HX711 load cell amplifier breakout board

Using Flask to Send Data to a Raspberry Pi

In this tutorial, we'll show you how to use the Flask framework for Python to send data from ESP8266 WiFi nodes to a Raspberry Pi over an internal WiFi network.

Hardware Hookup

You’ll need to connect up the hardware before going any farther. We’ll walk you through it.

Connect Up the Scale

I bought a Taylor model 7058 scale for this project at my local Target store. I chose it because it was cheap and looked like it might have an LED display (it doesn’t). I had hoped to repurpose a significant amount of the internal hardware but in the end, all I was able to salvage was the body and load cells.

Start by removing the screws from the underside of the scale. The image below has red arrows pointing to the screws that need to be removed. Other screws do not need to come off and in fact, should not be removed.

Screws to be removed

Flip the scale over and lift the top plate off, carefully. The electronics are held in a box that is attached to the bottom plate by a couple of twisted tabs, marked in the image below with red arrows.

Electronics enclosure

Snip the wires off the PCB. I prefer to snip the wires and restrip them rather than desoldering as I feel it gives a cleaner end to the wire, leaving the wires less likely to fray. You can pitch the entire electronics subassembly– we won’t be reusing any of it.

Electronics

You’ll now need to reconnect the wires, some to one another, others to the amplifier. Check out the drawing below for the order in which to hook up the wires. The upper left sensor’s blue wire connects to the upper right sensor’s blue wire. The upper left sensor’s red wire connects to the lower left sensor’s red wire. The lower left sensor’s blue wire, to the lower right sensor’s blue wire, and the lower right sensor’s red wire, to the upper right sensor’s red wire. Red to red, blue to blue.

load sensor

My strategy is to strip perhaps 3-4mm of the end of the wire and twist the two wires together, then solder the bare ends and slip a small section of heat shrink tubing over the joint. The white wires will be connected to the amplifier, so don’t worry about them right now.

Wire reconnection

Connect Up the Electronics

Now that you’ve got the scale all ready to go, you can bring in the electronics. Below is a hookup diagram showing how to wire them all together.

Full hookup image

I chose to pop out the plastic window that the display had previously been behind so I could run the wires out the front and mount my electronics on the outside. You may want to try squeezing everything inside the case, as it will probably fit and will give a cleaner build. However, it does make accessing the power port on the ESP32 Thing more difficult for either powering or charging.

Calibrating the Scale

Note: This example assumes you are using the latest version of the Arduino IDE on your desktop. If this is your first time using Arduino, please review our tutorial on installing the Arduino IDE. If you have not previously installed an Arduino library, please check out our installation guide.

Before we go farther into the project, we need to calibrate our scale. I’ve modified the calibration sketch that comes with the HX711 library to display on the scale’s serial 7-segment display to make it slightly easier to use.

Upload Code to the ESP32

Here’s the calibration sketch:

language:cpp
#include <HX711_ADC.h>

//HX711 constructor (dout pin, sck pin)
HX711_ADC LoadCell(5, 4);
HardwareSerial Serial2(2); // Enable 3rd serial port on ESP32

long t;

void setup() {
  Serial.begin(115200);
  Serial2.begin(9600);
  Serial.println("Wait...");
  LoadCell.begin();
  long stabilisingtime = 2000; // tare preciscion can be improved by adding a few seconds of stabilising time
  LoadCell.start(stabilisingtime);
  LoadCell.setCalFactor(10000.0); // user set calibration factor (float)
  Serial.println("Startup + tare is complete");
}

void loop() {
  //update() should be called at least as often as HX711 sample rate; >10Hz@10SPS, >80Hz@80SPS
  //longer delay in scetch will reduce effective sample rate (be carefull with delay() in loop)
  LoadCell.update();

  //get smoothed value from data set + current calibration factor
  if (millis() > t + 250) {
    float i = fabs(LoadCell.getData());
    float v = LoadCell.getCalFactor();
    Serial.print("Load_cell output val: ");
    Serial.print(i);
    Serial.print("      Load_cell calFactor: ");
    Serial.println(v);

    // Create a string which is the integer value of the weight times 10,
    //  to remove the decimal point.
    String weight = String(int(i*10));
    Serial2.write(0x76); // Clear the display
    Serial2.print(weight); // Write out the weight value to the display

    // Identify which decimal point to set, and set it.
    int shiftBy = 5-weight.length();
    int decimalPoint = 0x08>>(shiftBy);
    Serial2.write(0x77);
    Serial2.write(decimalPoint & 0x0F);

    t = millis();
  }

  //receive from serial terminal
  if (Serial.available() > 0) {
    float i;
    char inByte = Serial.read();
    if (inByte == 'l') i = -1.0;
    else if (inByte == 'L') i = -10.0;
    else if (inByte == 'h') i = 1.0;
    else if (inByte == 'H') i = 10.0;
    else if (inByte == 't') LoadCell.tareNoDelay();
    if (i != 't') {
      float v = LoadCell.getCalFactor() + i;
      LoadCell.setCalFactor(v);
    }
  }

  //check if last tare operation is complete
  if (LoadCell.getTareStatus() == true) {
    Serial.println("Tare complete");
  }

}

It’s pretty simple. It reads the HX711 four times a second and prints the results both to a serial console and to the 7-segment display. Note that it tares the scale at boot, so don’t have any weight on the scale when you start it up!

Find the Calibration Factor

I prefer using a dedicated serial tool such as CoolTerm or a terminal program like Putty over the Arduino serial console for this step. You’re going to have to step through quite a lot of values and the Arduino console isn’t good for that.

The calibrate routine looks for the user to send characters over the serial console to adjust the calibration factor. The calibration factor starts at 10000 (arbitrarily), and must be increased or decreased from there until the weight reading is correct. Try increasing it first, by sending ‘H’ (for a 10-point increase) or ‘h’ (for a 1-point increase), and observe the weight reading. If the measurement gets closer to correct, keep increasing the calibration factor until the reading on the 7-segment display is true to the weight on the scale.

If the measurement gets farther from correct, try lowering the calibration factor by sending ‘L’ or ‘l’. Note that if you are using a terminal program or serial tool other than the Arduino IDE tool, you can probably just hold down the key to constantly sending characters and change the calibration factor quite quickly.

Write that Number Down!

You’ll want to record the final calibration factor so you can include it in the final version of the sketch.

ESP32 Example Code

The code for the ESP32 is relatively simple. It’s basically a mash-up of examples from the ESP32 core and the HX711 library.

First, it configures the hardware and software in the ESP32. This is where you’ll use the calibration factor you discovered on the previous section. Here, it’s set to 10920, which is what my scale needs. Replace that number with the one you discovered.

language:cpp
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <HTTPClient.h>
#include <HX711_ADC.h>

WiFiMulti wifiMulti;
HX711_ADC LoadCell(5,4);   //HX711 constructor (dout pin, sck pin)
long scaleTick, httpTick;
HardwareSerial Serial2(2); // Enable the third hw serial port on the ESP32

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

  Serial.println();
  Serial.println();
  Serial.println();

  // Give background processes a few seconds to complete
  for(uint8_t t = 4; t > 0; t--) 
  {
    Serial.printf("[SETUP] WAIT %d...\n", t);
    Serial.flush();
    delay(1000);
  }

  wifiMulti.addAP("ssid_goes_here", "password_goes_here");

  // Set up the HX711 library
  LoadCell.begin();
  LoadCell.start(10); // Start up the HX711 library with 10ms delay
  LoadCell.setCalFactor(10920); // user set calibration factor (float)
  Serial.println("Startup + tare is complete");
}

Next, it enters loop(). where it checks the weight every 250ms and keeps a running average of the weight over the last four cycles. If the average over the last four cycles is close enough (less than 0.1lb off) of the current reading, it posts the weight data to the internet. Some checking is done to make sure that a large-ish (greater than 30lbs) weight is present on the scale, and that only one update happens per stabilized weight (i.e. the weight returns to zero before another weight is posted to the website).

language:cpp
void loop() 
{
  static float history[4];
  static float ave = 0;
  static bool stable = false;
  static bool webUpdated = false;
  static float weightData = 0.0;

  // Update the website with weight data IF the weight data is stable AND the
  //  website hasn't been updated yet.
  if (stable && !webUpdated)
  {
    // Only try if the wireless network is connected
    if((wifiMulti.run() == WL_CONNECTED)) 
    {
      HTTPClient http;

      Serial.print("[HTTP] begin...\n");
      Serial.println(weightData);
      // Replace 0.0.0.0 in address with your IP address
      String address = "http://0.0.0.0:5000/post_weight/";
      // Create a string with one decimal point of the average of the weights
      //  collected
      String weight = String(weightData, 1);
      // cat the two together
      String fullAddress = String(address + weight);
      // Connect to the server with the address you've created
      http.begin(fullAddress);

      Serial.print("[HTTP] GET...\n");

      // start connection and send HTTP header
      int httpCode = http.GET();
      // httpCode will be negative on error
      if(httpCode > 0) 
      {
        // HTTP header has been send and Server response header has been handled
        Serial.printf("[HTTP] GET... code: %d\n", httpCode);

        // file found at server, response 200
        if(httpCode == HTTP_CODE_OK) 
        {
          // clear the stable flag as the data is no longer valid
          stable = false;
          // Set the webUpdated flag as we've successfully updated the website
          webUpdated = true;
          Serial.println("Web updated");
          // Dim the LED display for 500ms, then turn it back on
          Serial2.write(0x7a);
          Serial2.write(0);
          delay(500);
          Serial2.write(0x7a);
          Serial2.write(255);
        }
      } 
      else 
      {
        Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
      }

      http.end();
    }
  }

  // Check the weight measurement every 250ms
  if (millis() - scaleTick > 250)
  {
    scaleTick = millis();
    // Read from the HX711. Must do this before attempting to use data!
    LoadCell.update();
    // We take the abs of the data we get from the load cell because different
    //  scales may behave differently, yielding negative numbers instead of 
    //  positive as the weight increases. This can be handled in hardware by
    //  switching the A+ and A- wires, OR we can do this and never worry about it.
    weightData = abs(LoadCell.getData());
    // Calculate our running average
    history[3] = history[2];
    history[2] = history[1];
    history[1] = history[0];
    history[0] = weightData;
    ave = (history[0] + history[1] + history[2] + history[3])/4;

    // IF the average differs from the current by less than 0.3lbs AND
    //  the average weight is greater than 30 pounds AND
    //  we haven't recently updated the website, set the stable flag so
    //  we know that the weight is stable and can be reported to the web
    if ((abs(ave - weightData) < 0.1) && 
        (ave > 30) && 
        !webUpdated)
    {
      stable = true;
    }

    // IF we've updated the website AND
    //  the average weight is close to zero, clear the website updated flag
    //  so we are ready for the next weight reading
    if (webUpdated && ave < 1)
    {
      webUpdated = false;
    }

    Serial.print("Load_cell output val: ");
    Serial.println(weightData);

    // Create a string which is the integer value of the weight times 10,
    //  to remove the decimal point.
    String weight = String(int(weightData*10));
    Serial2.write(0x76); // Clear the display
    Serial2.print(weight); // Write out the weight value to the display

    // Identify which decimal point to set, and set it.
    int shiftBy = 5-weight.length();
    int decimalPoint = 0x08>>(shiftBy);
    Serial2.write(0x77);
    Serial2.write(decimalPoint & 0x0F);
  }
}

Web Code

The web application is developed under Flask, which is a light web framework allowing Python applications to be deployed on the web. Here, we’ll get into the directory structure and file structure of the Flask app. We’re going to assume that you’re going into this with a naive installation of Linux: perhaps a new Linode server, or a new Raspberry Pi. We’re also going to assume that you have a console window open to whatever server you’re going to use and that the server is connected to the Internet.

Install Flask

The first step is to install Flask. Simply type the following:

language:bash
sudo pip install flask

That should install flask automatically.

Install Tkinter and Matplotlib

You’ll now need to install Matplotlib, so you can generate plots of your collected data. First, you need to make sure that Tkinter is installed. It probably is if you’re working on any kind of server that is expected to have a desktop option (like a Raspberry Pi). In the case of something like Linode, where your primary interface is expected to be a command line, Tkinter may not be installed. Use the following command:

language:bash
sudo apt-get install python-tk

That will install Tkinter. Next we can install Matplotlib.

language:bash
sudo pip install matplotlib

That should install Matplotlib and all its dependencies.

Create the Directory Structure

The Flask app we’re going to create has a directory structure that allows all the various pieces to be segregated into functional groups. Here’s the structure you want to keep it neat and tidy:

website
└── app
    ├── images
    └── templates

As we go through the rest of the tutorial, we’ll populate these directories with the appropriate files. Note that the top-level directory (website) can be located wherever you please and named, but I like to leave it in my home directory for ease of access. We’re also going to assume that you followed this template for the rest of the tutorial, so it’s to your benefit to do so.

Add the FLASK_APP Variable to Your Path

By adding the FLASK_APP variable to the path, we allow Flask to be run from a very simple command, which saves us time in the long run. Type:

language:bash
export FLASK_APP=~/website/website.py

This of course assumes that you created the directory named website in your home directory. If not, change the path accordingly.

You probably want to add this line to your .bashrc file, so you don’t have to type this command in every time you log into the server.

Create Your First Files

Unsurprisingly, our first file is going to be called website.py and is going to be located in the top-level website directory. The contents of the file are very simple:

language:bash
from app import app

We’ll create the app class that we’re importing in a minute.

Next, create the config.py file in the same place. This file is used to store site configuration information, but we’ll only be storing one little piece of info in it.

language:python
import os

class Config(object):
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'

The SECRET_KEY is used by Flask to verify the signature of cookies to ensure that they haven’t been tampered with by some third party. We won’t make use of it, but it’s good practice to set it up.

Create Your App Files

Now it’s time to create the meaty parts of the project, the files that actually do something. These files will go in the app directory.

Start with the init.py file. This is a super important file which allows us to put our actual app in the app directory and have python treat it as a module that can be imported:

language:python
from flask import Flask
from config import Config

app = Flask(__name__)
app._static_folder = 'images'
app.config.from_object(Config)

from app import routes

We first import Flask, which is (obvi) our overall Flask support object. From the config file, we created earlier, we import the Config class, which stores configuration data for flask, although ours is tragically underutilized. We then create an object of the Flask class named app, which will be imported throughout the rest of the program. app._static_folder_ tells Flask where to expect static files (such as images) to be served from. “Static” is here somewhat of a misnomer, as the files in that directory can change, they just are expected to not be templates to be rendered. Lastly, we configure our Flask object with the Config object we imported earlier.

Let’s look at our routes.py file. It goes in the app directory, and looks like this:

language:python
from flask import render_template, send_from_directory
from app import app
from weight import add_weight_point
from plot_weight import plot_weight

@app.route('/')
@app.route('/index')
def index():
    return render_template('index.html', title='Home')

@app.route('/images/<path:path>')
def send_image(path):
    return send_from_directory('images', path)

@app.route('/post_weight/<string:weight>')
def post_weight(weight):
    add_weight_point(weight)
    plot_weight()
    return "weight posted"

The routes.py file is the secret sauce that allows our app to know what to do when a request comes in from a remote client. At the top, we import all the various bits and bobs that make our project work. We import render_template and send_from_directory from flask to support routes that we make for rendering templates and displaying images. We import the app object that we created in init.py, and then the add_weight_point and plot_weight functions that we’ll create in a little while.

The decorators @app.route('/') and @app.route('/index') tell the Flask app what to do when a request for either of those paths comes in. In this case, we would choose to render a template called index.html. We’ll cover templates a little later, but for now, just know that this is the document that gives a webpage its appearance.

The @app.route('/images/<path:path>') decorator is of particular interest because for the first time, we see a path with a variable in it. This route serves up any file requested from the images directory. This is important because Flask isn’t a full-featured web server, so it doesn’t know what to do with requests that it has no route for.

The third and final route, @app.route('/post_weight/<string:weight>'), is interesting because it’s a purely server-side function. It does return a response (the string “weight posted”), but its primary function is to take the string passed to it and concatenate it to the weight file, then plot the data in the weight file.

Next, we create the supporting files, to which we outsource the recording of data points and the plotting of data on a chart. We’ll look at weight.py first, which does the recording portion:

language:python
from datetime import datetime
import pytz

def add_weight_point(weight):
    file_name = "weight"
    try:
        with open(file_name, 'a') as f:
            f.write(weight + ", ")
            tz = pytz.timezone('America/Denver')
            local_now = datetime.now(tz)
            dt_string = str(local_now.date()) + ' ' +  str(local_now.time())
            f.write(dt_string + "\n")
    except:
        print "Weight sad :-("
        pass

if __name__ == "__main__":
    add_weight_point("0.0")

We need datetime and pytz to create timezone-aware date and time values for when we post our data. The meat of the function is enclosed in a try/except clause, mostly to make debugging easier during development, but it could prove helpful in deployment too. We open our file in append mode, which automatically places the cursor at the end of the file, then plop in the weight value (which was received as a string from the calling function, our route handler in the prior file) with a comma to provide separation for readability. We then create a timezone object for my timezone (‘America/Denver’), and fetch the local date and time (as a datetime object). The local time and date are converted to strings and appended to the file. Finally, we provide a directive to how to handle the case where this file is called as the main file (i.e., run by itself, for test purposes): call the add_weight_point() with a string of “0.0”.

Finally, before you can run the application, you need to create the file that stores the weight data. This is easily done with this command:

touch weight

The final code file we create is plot_weight.py. This file uses Matplotlib to create a .png file of a graph of all the data in our weight data file.

language:python
from datetime import datetime
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

def plot_weight():
    file_name = "weight"
    weight_data = []
    date_data = []
    with open(file_name, 'r') as f:
        file_data = f.readlines()
        for line in file_data:
            line = line.strip().split(', ')
            line = [line[0], datetime.strptime(line[1],
                                               "%Y-%m-%d %H:%M:%S.%f")]
            weight_data.append(float(line[0]))
            date_data.append(line[1])

    fig = plt.figure()
    plt.plot(date_data, weight_data)
    plt.xticks(rotation = 75)
    fig.savefig('images/plot.png', bbox_inches='tight')

if __name__ == "__main__":
    plot_weight()

The import section is fairly self explanatory, except for the line matplotlib.use("Agg"). This line forces Matplotlib to ignore the fact that no X server is available for plotting. Without it, the Tkinter GUI library will throw an error when you try to plot, even if you’re plotting to an output file. The rest of the file is pretty easy to understand: import the data file into a one-line-per-element list, then create two separate lists for weight data, one of float values and one of datetime objects. It creates a pyplot figure, plots the data, rotates the labels on the x-axis so they don’t overlap, and then saves the figure to an image.

Create the HTML Templates for Displaying Data

As mentioned previously, one of the beautiful things about Flask is that it can render templates for displaying pages. This means that you can have one template (say, base.html) that handles the page header and footer material while other pages render into that template.

We’re going to start by placing a base.html file in our templates directory. Here’s the content of that file.

language:html
<html>
  <head>
    {% if title %}
    <title>{{ title }} - A Website</title>
    {% else %}
    <title>A Website</title>
    {% endif %}
    {% block head_content %}{% endblock %}
  </head>
  <body style="background-color:#42dff4">
    {% block body_content %}{% endblock %}
  </body>
</html>

I’m not going to explain the html portions of this document, just the templating that makes it different. There are three templating concepts in play here: variables, if/else statements, and blocks. You can see that we create an if/else statement which checks the variable title to see if it is defined. If it is defined, we set the title of the page accordingly. If not, we use a default title. If you scroll back up and look at our routes.py file, you can see that when we rendered that template, we passed in the title variable, set to “Home”. The other templating concept is that of a text “block”. To illustrate how that works, I’m going to need to pull in the contents of our other html template, also created in the templates folder: index.html.

language:html
{% extends "base.html" %}

{% block head_content %}
{% endblock %}

{% block body_content %}
  <img src="images/plot.png" alt="Plotted data" />
{% endblock %}

First, you can see the “extends” statement. That tells Flask that this file should be viewed through the lens of base.html, and that the two together create a single document. Now check out the block statements. The “head_content” block is empty–nothing will be created there. However, in the “body_content” block, there is a link to the image created by plot_weight.py. When Flask goes to render the index.html template, it will “draw” first base.html, then it will pull all the block content from index.html into the appropriate places in base.html. You can see how this can be extremely powerful, allowing you to render websites in which 10% of the content is generated by a base template and the other 90% comes from specific subpages that you wish to display.

Deploy!

If you’ve been following along, your Linux server should be prepped and ready to have your website deployed! To launch your app all you have to do is run this command:

language:bash
flask run -h 0.0.0.0

That uses that FLASK_APP variable that we set up earlier to determine where the application to be launched is and launches it. The -h 0.0.0.0 switch tells it that you want the app to be visible to the outside world. If you’re running this on a Raspberry Pi, it should be visible to any computer on the same network as the Raspberry Pi, but probably not the whole internet. If you’re running on a Linode (or other cloud service) server, then you should be able to access the web page from anywhere.

There’s a problem, though: once you disconnect your console from the server, the Flask app process gets killed and the page will no longer be accessible. To get around that, we use the “no hangup” command, telling the server to run the process in the background and not kill it when the console disconnects. To do this, enter the command thus:

language:bash
nohup flask run -h 0.0.0.0 &

Now the task will run in the background and you can disconnect from the server without affecting it. To terminate the process, you have to do a little more work. First, you must find the process id for your app. To do this, use the following command:

language:bash
pgrep flask

That will return the PID for the current running flask instance. To then stop that process, type:

language:bash
kill <PID>

Replace <PID> with the process ID that you found in the previous step. That will stop the process. You’ll need to stop and restart the process any time you make any changes to any of the files other than the image file.

Resources and Going Further

For more information, check out the resources below:

  • GitHub Project Repo - IoT weight logging scale project repo.
  • Linode - High performance SSD Linux servers for cloud hosting.
  • GitHub ESP32 Repo - ESP32 Arduino core files and support packages.
  • Flask Framework - Official Flask website.
  • Simple Flask Tutorial - This basic Flask tutorial will walk you through taking Flask a little bit farther than we have here.
  • Complex Flask Tutorial - This more advanced tutorial walks you through far more complex tasks with Flask, leading up to creating a Twitter clone that you can host yourself!

Need some inspiration for your next project? Check out some of these related tutorials:

SparkFun Blocks for Intel® Edison - Base Block

A quick overview of the features of the Base Block.

General Guide to SparkFun Blocks for Intel® Edison

A general guide for using SparkFun Blocks for Intel® Edison in your next project!

ESP8266 Thing Hookup Guide

An overview of SparkFun's ESP8266 Thing - 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.

Getting Started with the Tessel 2

Get your Tessel 2 up and running by blinking and LED, the Hello World of embedded electronics.

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


Gator:bit Hookup Guide

$
0
0

Gator:bit Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Gator:bit is a development board for BBC micro:bit. Almost every pin on the micro:bit is broken out to alligator clippable pads so you can get the most out of it. Gator:bit comes equipped with five addressable LEDs, a built-in buzzer (speaker) as well as a power management system that gives you access to 3.3V and 5V. Gator:bit can be powered from 2.7V - 9V giving you quite a range of powering options.

SparkFun gator:bit

DEV-14484
$19.95

Without any external hardware Gator:bit is still an exploratory development board for micro:bit. Whether it is data visualization using the on board addressable LEDs, capacitive touch sensing on pins 0, 1, & 2, or creating musical works of art using the built-in speaker we’ve got it covered with the with the Gator:bit.

With some alligator clips and extra hardware you’ll be able to explore inputs like sensors, potentiometers, and buttons and control outputs like lights, motors, and speakers.

Required Materials

Here are some products that will help you get started with the Gator:bit:

Suggested Materials

In addition to the above, here are some products to get you started with building circuits to control inputs and outputs using the Gator:bit:

Copper Tape - Conductive Adhesive, 5mm (50ft)

PRT-13827
$3.95
Multicolor Buttons - 4-pack

PRT-14460
$1.50
SparkFun LED Starter Kit

KIT-13234
$29.95
2
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

COM-11507
$0.95
2
Mini Photocell

SEN-09088
$1.50
7
Temperature Sensor - TMP36

SEN-10988
$1.50
16
Reed Switch - Insulated

COM-10601
$1.95
Tilt Sensor - AT407

SEN-10289
$1.95

Suggested Reading

If you aren’t familiar with the following concepts, we recommend checking out these tutorials before continuing.

What is a Circuit?

Every electrical project starts with a circuit. Don't know what a circuit is? We're here to help.

Voltage, Current, Resistance, and Ohm's Law

Learn about Ohm's Law, one of the most fundamental equations in all electrical engineering.

What is Electricity?

We can see electricity in action on our computers, lighting our houses, as lightning strikes in thunderstorms, but what is it? This is not an easy question, but this tutorial will shed some light on it!

Light-Emitting Diodes (LEDs)

Learn the basics about LEDs as well as some more advanced topics to help you calculate requirements for projects containing many LEDs.

Hardware Overview

Gator:Bit with Micro:Bit

Details:

  • micro:bit card edge connector
  • Input voltage: 2.7V - 9V
  • 5 built in addressable LEDs
  • Built in buzzer
  • 5V output
  • 3.3V output
  • 7 protected input/output pins
  • 3 pins for SPI communication
  • 2 pins for I2C

Powering your Gator:bit

There are 2 ways of powering your gator:bit, either from the JST battery terminal or the alligator clippable pads labeled “VIN”. Any voltage input between 2.7V and 9V will be regulated to 3.3V to power the micro:bit, the speaker, and for use by any of the alligator clippable pins. 5V is also regulated from the input to power the LEDs and any off-board hardware you would like to use like servo motors.

However you choose to power your boards, you must select your powering option on the switch labeled Power In on the bottom right side of the board. Choose BATT if you are using the JST terminal or select TAB if if you are using the alligator tabs with another power source. You will notice an arrow that runs from Power In to the master POWER switch near the card edge connector. If you are providing power from either the JST connector or from a clipped source that master switch should be placed down at PWR IN.

If you are not using the JST terminal or alligator clips to provide power, the gator:bit can be used with a USB on the micro:bit. If you leave the master switch set to PWR IN while using a USB cable, you will be powering the gator:bit from the micro:bit’s 3.3V output. You will have full use of gator:bit with the exception of the use of the 3.3V/5V power out. If the master switch is up to USB, the voltage coming in from the micro:bit will go through the voltage regulators and give you full access to the gator:bit and any peripherals.

Power options highlighted

Power options

Input Pins

The point of gator:bit is to give you access to as much GPIO as possible from the micro:bit, safely. Not only are pins 0, 1, 2, 8, 16, 5 (Button A), and 11 (Button B) broken out, but they are also protected against over voltage and over current/short circuit. Pins 0, 1, & 2 are ADC pins and are also the capacitive touch pins. Pins 8, 16, 5, and 11 are digital pins capable of read and write.

Highlighted Pin Tabs

Input pins

The gator:bit also provides access to pins 13, 14, 15, 19 & 20. These are digital pins that can be used to read and write digital signals. Pins 13, 14, & 15 are also SPI communication pins giving you the ability to use SparkFun’s SPI sensors with the gator:bit. Pins 19 & 20 are I2C communication pins which extend the use of the micro:bit to include all of SparkFun’s I2C sensors.

Read/Write Digital Ports

Read/Write digital ports

Output

The gator:bit gives you access to more micro:bit pins and it also gives you access to 3.3V and 5V. Your servo action is about to get a little cleaner and you’ll be able to easily power peripheral hardware.

In order to use the voltage out tabs, the VOUT switch needs to be switched on. Having the option to turn it off is great when when you don’t need it.

VOUT Switch Highlighted

VOUT switch

On the right side of the board there are two “OUT” pins. One for 5V and one for 3.3V. You will know when the output voltage is available because two red LEDs will turn on right above the pad. You can use either of the two ground pads since all ground is connected.

VOUT Ports Highlighted

VOUT Ports

Now let’s look at the fun kind of output, light and sound! On the bottom left is a buzzer. We chose a small speaker on purpose. You’ll be able to explore creating digital music and then listen to it right on the gator:bit. You can easily attach a larger speaker when you are ready to show off your work.

You’ll notice another switch here. The speaker is attached to pin 0, so if you want to play music the music switch needs to be on and you won’t be able to use pin 0. Conversely, if you want to use pin 0 th music switch needs to be switched off.

Speaker and Music switch highlighted

Speaker and music switch

LEDs! Addressable LEDs! Connected to pin 12 are 5 addressable LEDs with the first LED on the left. The Neopixel makecode package is an excellent way to control these. We have a few examples using the package coming up.

Highlighted LEDS

LEDs!

Programming Environments

There are several programming environments to use your micro:bit and gator:bit with.

MakeCode

Makecode is a web application based on block programming. The blocks then directly convert to Javascript; you can switch back and forth for ease of inspection. To upload your program to the micro:bit you download the project and drag and drop it on the micro:bit.

A quick start guide on MakeCode is the best way to become familiar with blocks, packages, downloading and running programs on the micro:bit.

Get Started with MakeCode!

From the start you are presented with the basic building blocks on a program. on start is where your setup is, variable declarations, and any other start up messages or images. forever is your looping function. If you want to blink an LED you’d turn an LED on for some amount of time and off for some amount of time the loop would allow that to repeat forever.

MakeCode screen shot

Click the image to get a closer look.

On the left hand side there is a simulation of the program with the micro:bit and the package list. Once you’ve clicked on a package list, you’ll be provided with the blocks associated with that package.

Input Packages Highlighted

Click the image to get a closer look.

Since the blocks are based on Javascript and you can switch between looking at a program in blocks and Javascript, Makecode is a great way to start programming fast and learn another language as you go.

Makecode javascript highlighted

Click the image to get a closer look.

EduBlocks

Similar to MakeCode there is another web and block based programming environment called EduBlocks. EduBlocks translates directly to Python 3.

Using the built in sample program you can explore how to use the blocks and load the program to the micro:bit.

EduBlocks Sample Program

Click the image to get a closer look.

By clicking on the “Blocky” tab on the right the block code is converted to Python 3.

Example block of Python 3

Click the image to get a closer look.

Another great way to start programming fast and learn another language as you go.

Others

micro:bit also has a Python Editor for Micropython. Micropython is a subset of Python 3 that was made specifically for microcontrollers like the micro:bit!

The micro:bit can also be programmed in Arduino. Even better, since the micro:bit has bluetooth and radio it works with a neat app called Blynk. You can create programs in Arduino then send and receive data via app. Sending data can even update the micro:bit to customize output in real time like lights.

Example Project: LED Animations

Did we mention those mounting holes on the gator:bit were made to be compatible with with the single LEGO piece? From one baseplate we’ve built a rack for the gator:bit, a battery enclosure, and along the bottom an alligator clip cable management system. When you are done learning all about microcontrollers, radio and bluetooth communication, and data collection and visualization, you can hang your baseplate up and keep everything organized.

Lego rack for gator:bit

This program starts out with a rainbow pattern across the LEDs and then turns the LEDs off sequentially from the left. Once they have all turned off, a new animation will start sequentially from the left; the LEDs will turn blue but will fill the previous LEDs with a random color rather than turning off.

The brightness is turned down to 75 to save your eyes and your battery life!

Makecode for LED patterns

Click the image to get a closer look at the project.

Example Project: Button Melody Player

This project makes use of the speaker and buttons A and B. This project is easily extendable by using alligator clips on pins 5 and 11 to trigger the button-press event using external hardware like buttons or reed switches.

Setup image of button melody player

At the start of the program an eighth note is displayed on the 5x5 LED matrix. When button A or B is pressed a video game type melody is played. You can choose from several melodies or make one of your own. By adding a few more buttons and using the “is pressed” function on pins 0, 1, or 2 you could create a 5 button drum machine or synthesizer.

Example of "is pressed" block

This function can be found in the “input” package in makecode.

Example of 5x5 LED eighth note

A closer look at the button Melody Player MakeCode project.

Resources and Going Further



For additional SparkFun tutorials, check out some of these related micro:bit tutorials:

SparkFun Inventor's Kit for micro:bit Experiment Guide

This guide contains all the information you will need to explore the twelve circuits of the SparkFun Inventors Kit for micro:bit.

micro:climate Kit Experiment Guide

A weather station kit that is built on top of the inexpensive, easy-to-use micro:bit and Microsoft MakeCode.

micro:bit Breakout Board Hookup Guide

How to get started with the micro:bit breakout board.

Try exploring micro:bit with cardboard circuits!


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

12V/5V Power Supply Hookup Guide

$
0
0

12V/5V Power Supply Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The 12V/5V (2A) power supply is great for powering a microcontroller and an LEDs. In this tutorial, we will replace the power supply’s molex connector with two male barrel jacks adapters.

Power Supply - 12V/5V (2A)

TOL-11296
$9.95
5

Required Materials

To follow along with this tutorial, you will need the following materials. You may not need everything though depending on what you have. Add it to your cart, read through the guide, and adjust the cart as necessary.

Tools

You will need a soldering iron, solder, general soldering accessories, and the following tools.

Digital Multimeter - Basic

TOL-12966
$14.95
18
Hook-Up Wire - Assortment (Solid Core, 22 AWG)

PRT-11367
$16.95
28
Solder Lead Free - 100-gram Spool

TOL-09325
$7.95
7
Flush Cutters - Hakko

TOL-11952
17
Wire Strippers - 30AWG (Hakko)

TOL-12630
$9.95
3
Weller WLC100 Soldering Station

TOL-14228
$44.95
Diagonal Cutters

TOL-08794
$1.95
2

Suggested Reading

If you aren’t familiar with the following concepts, we recommend checking out these tutorials before continuing.

How to Solder: Through-Hole Soldering

This tutorial covers everything you need to know about through-hole soldering.

Connector Basics

Connectors are a major source of confusion for people just beginning electronics. The number of different options, terms, and names of connectors can make selecting one, or finding the one you need, daunting. This article will help you get a jump on the world of connectors.

How to Power a Project

A tutorial to help figure out the power requirements of your project.

Working with Wire

How to strip, crimp and work with wire.

How to Use a Multimeter

Learn the basics of using a multimeter to measure continuity, voltage, resistance and current.

Hardware Overview

The power supply’s pinout is shown below. The connector’s molding will have numbers associated with the output to help identify the connection. You will also notice that the connector is polarized with the two chamfered corners.

Molex Connector Pinout with Labels

Pinout Table

The following table describes the molex connector’s pinout and what color the wire may look like.

Molex Pinout 12V/5V Power Supply Notes
1 +12V"Red"
2 N/C May Not Be Not Connected
3 GND "Yellow"
4 +5V"Black (or White)"

Hardware Hookup

Cut the cable about 1-2 inches from the molex connector.

Cut cable

Cut into sheath with the flush cutter. Pull it back just enough so that you have enough room to work with the wires. Be careful not to cut yourself!

Cut Sheath

Strip the power supply’s three wires. The wires are stranded so feel free to tin the wires by adding solder to the tips.

Tin Wires

Then cut and strip a piece of hookup wire. Solder it to the ground wire.

Refrence Ground Wire

Braid the wire and insert into a barrel jack connector. Secure the wires in the screw terminal with a Phillips head. Feel free to add some heat shrink or electrical tape to the connection at this point.

Tighten Screw Terminals

Test the Output

Power the power supply and test with a multimeter to verify the voltages. Usually power supplies are center positive so make sure that the wires were inserted correctly. Adjust as a necessary for your system.

Test outputs

Label the Output

Using a Sharpie, clearly label the barrel jack connector’s voltage relative to the output. Feel free to add an additional barrel jack when not in use.

Label Barrel Jacks

Power Your Circuit!

Connect the power supply to your circuit and power it up! I personally use the power supply as a tool for basic testing. Usually the 12V side is connected to an Arduino’s barrel jack. The 5V output is used for more power hungry loads such as the the RGB LED Matrix or a few meters of addressable (WS2812B, APA102, etc) LEDs.

RGB LED Matrix 32x64 Powered with the 12V/5V (2A) Power supply

Arduino Mega 2560 and 32x64 RGB LED Matrix Powered by the 12V/5V Power Supply

Troubleshooting

Certain power supplies have a lot of noise. While 12V/5V power supply works great with a microcontroller and a LED strip, it may not work as well when you attach a capacitive touch sensor to the system. The power supply lacks proper filtering and causes the potentiometer to have a lot of latency. You can try to add additional circuitry to fix it since the current power supply has a lot of noise. However, it would be easier to use two separate power supplies or a more robust power supply such as a Meanwell.

PWM Lighting Controller

Example PWM Lighting Controller from the Touch Potentiometer Hookup Guide

Resources and Going Further

Now that you’ve successfully got your 12V/5V power supply up and running, it’s time to incorporate it into your own project!

For more information, check out the resources below:

Need some inspiration for your next project? Check out some of these related tutorials that uses the 12V/5V (2A) power supply.

RGB Panel Hookup Guide

Make bright, colorful displays using the 32x32 and 32x16 RGB LED matrix panels. This hookup guide shows how to hook up these panels and control them with an Arduino.

Large Digit Driver Hookup Guide

Getting started guide for the Large Digit display driver board. This tutorial explains how to solder the module (backpack) onto the back of the large 7-segment LED display and run example code from an Arduino.

How to Build a Remote Kill Switch

Learn how to build a wireless controller to kill power when things go... sentient.

Building a Safe Cracking Robot

How to crack an unknown safe in under an hour.

Or check out some of these blog posts about power supplies


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

LIDAR-Lite v3 Hookup Guide

$
0
0

LIDAR-Lite v3 Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The LIDAR-Lite Series - the v3 and v3HP - are compact optical distance measurement sensors, which are ideal for drones and unmanned vehicles.

LIDAR-Lite v3

SEN-14032
$129.99
18
LIDAR-Lite v3HP

SEN-14599
$149.99

LIDAR is a combination of the words “light” and “RADAR.” Or, if you’d like, a backronym for “LIght Detection and Ranging” or “Laser Imaging, Detection, and Ranging.” At it’s core, LIDAR works by shooting a laser at an object and then measuring the time it takes for that light to return to the sensor. With this, the distance to the object can be measured with fairly good accuracy.

By sweeping or spinning a LIDAR unit, systems can create detailed distance maps. Survey equipment, satellites, and aircraft can be equipped with complex LIDAR systems to create topographic maps of terrain and buildings. Luckily, Garmin™ has created a user-friendly LIDAR unit for your robotics and DIY needs!

Note that these use a Class 1 Laser, if you are concerned about your safety (in short: A Class 1 laser is safe under all conditions of normal use).

CLASS 1 LASER PRODUCT CLASSIFIED EN/IEC 60825-1 2014. This product is in conformity with performance standards for laser products under 21 CFR 1040, except with respect to those characteristics authorized by Variance Number FDA-2016-V-2943 effective September 27, 2016.

What is the difference between the LIDAR-Lite v3 and the LIDAR-Lite v3HP? Let’s ask Shawn Hymel!

Required Materials

To follow along with this project tutorial, you will need the following materials:

Suggested Reading

If you aren’t familiar with the following concepts, we recommend checking out these tutorials before continuing.

Installing an Arduino Library

How do I install a custom Arduino library? It's easy! This tutorial will go over how to install an Arduino library using the Arduino Library Manager. For libraries not linked with the Arduino IDE, we will also go over manually installing an Arduino library.

How to Use a Breadboard

Welcome to the wonderful world of breadboards. Here we will learn what a breadboard is and how to use one to build your very first circuit.

What is an Arduino?

What is this 'Arduino' thing anyway?

Installing Arduino IDE

A step-by-step guide to installing and testing the Arduino software on Windows, Mac, and Linux.

Hardware Overview

Functionally, the LIDAR-Lite v3 and the LIDAR-Lite v3HP are quite similar. The primary differences are listed here:

Specs LIDAR-Lite v3 LIDAR-Lite v3HP
Update Rate500 Hz> 1kHz
Current Consumption (idle)105 mA65 mA
Current Consumption (acquisition)130 mA85 mA
CasingNoneIPX7 rated casing

Case

The LIDAR-Lite v3 has two tubes on the front that contain a transmitter (laser) and receiver. You’ll want to face these toward your target.

Front of LIDAR-Lite v3

On the back, you’ll find 4 mounting holes that are designed to accept #6 or M3.5 screws or bolts.

Back of LIDAR-Lite v3

Wires

The LIDAR-Lite v3 has 6 wires that can be used to communicate with the sensor.

LIDAR-Lite v3 pinout

NOTE:This is looking at the back of the unit

ColorPinDescription
Red5VPower (5V)
OrangePWR ENPower enable (internal pullup)
YellowMODEMode control (for PWM mode)
GreenSCLI2C clock
BlueSDAI2C data
BlackGNDGround

Power

Both the LIDAR-Lite v3 as well as the LIDAR-Lite v3HP units require between 4.5V to 5.5V of DC power to operate (nominally, 5V). The LIDAR-LITE v3 can draw up to 135 mA of current during continuous operation (105 mA at idle). Contrarily, the v3HP unit draws up to 85 mA of current during continuous operation (65 mA at idle). To maintain a level voltage, Garmin recommends putting a 680 μF capacitor between power (5V) and ground (GND) as close to the LIDAR unit as possible.



Hardware Assembly

Follow the diagram below to connect the LIDAR unit to a RedBoard or other Arduino-compatible board. The LIDAR-Lite v3 can communicate over I2C as well as use a pulse-width modulated (PWM) signal to denote measured distances. For this guide, we will show how to use I2C to communicate with the LIDAR unit.

LIDAR-Lite v3 to Arduino hookup

Click on the image to enlarge it

Note: Garmin recommends a 680 μF, but anything near that value will work. I used a 1000 μF capacitor in this example. Make sure to add the electrolytic capacitor correctly to the circuit since it has a polarity.

Software

Garmin maintains an Arduino library to make working with the LIDAR-Lite very easy. Visit the GitHub repository, or click the button below to download the library.

Download the Garmin LIDAR-Lite v3 Arduino library

Note: This example assumes you are using the latest version of the Arduino IDE on your desktop. If this is your first time using Arduino, please review our tutorial on installing the Arduino IDE. If you have not previously installed an Arduino library, please check out our installation guide.

Open a new Arduino sketch, and copy in the following code:

language:c
/**
 * LIDARLite I2C Example
 * Author: Garmin
 * Modified by: Shawn Hymel (SparkFun Electronics)
 * Date: June 29, 2017
 * 
 * Read distance from LIDAR-Lite v3 over I2C
 * 
 * See the Operation Manual for wiring diagrams and more information:
 * http://static.garmin.com/pumac/LIDAR_Lite_v3_Operation_Manual_and_Technical_Specifications.pdf
 */

#include <Wire.h>
#include <LIDARLite.h>

// Globals
LIDARLite lidarLite;
int cal_cnt = 0;

void setup()
{
  Serial.begin(9600); // Initialize serial connection to display distance readings

  lidarLite.begin(0, true); // Set configuration to default and I2C to 400 kHz
  lidarLite.configure(0); // Change this number to try out alternate configurations
}

void loop()
{
  int dist;

  // At the beginning of every 100 readings,
  // take a measurement with receiver bias correction
  if ( cal_cnt == 0 ) {
    dist = lidarLite.distance();      // With bias correction
  } else {
    dist = lidarLite.distance(false); // Without bias correction
  }

  // Increment reading counter
  cal_cnt++;
  cal_cnt = cal_cnt % 100;

  // Display distance
  Serial.print(dist);
  Serial.println(" cm");

  delay(10);
}

Upload the program, and open a Serial Monitor. You should see distance measurements (in cm) being printed.

Measuring distance with LIDAR

Resources and Going Further

Now that you’ve successfully got your LIDAR up and running, it’s time to incorporate it into your own project!

For more information, check out the resources below:

Want to know more about how LIDAR works? Check out this great youtube video:

Need some inspiration for your next project? Check out some of these related tutorials:

Large Digit Driver Hookup Guide

Getting started guide for the Large Digit display driver board. This tutorial explains how to solder the module (backpack) onto the back of the large 7-segment LED display and run example code from an Arduino.

ReconBot with the Tessel 2

Build a robot with the Tessel 2 that you can control from a browser on your phone or laptop.

Building an Autonomous Vehicle: The Batmobile

Documenting a six-month project to race autonomous Power Wheels at the SparkFun Autonomous Vehicle Competition (AVC) in 2016.

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

SparkFun Arduino ProtoShield Hookup Guide

$
0
0

SparkFun Arduino ProtoShield Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Heads Up! This tutorial is for the latest version of the SparkFun Arduino ProtoShield. If you have an older version, please consult the retired Arduino ProtoShield Quickstart Guide

The SparkFun Arduino ProtoShield PCB and ProtoShield kit lets you customize your own Arduino shield using whatever custom circuit you can come up with! This tutorial will go over its features, hardware assembly, and how to use shield.

SparkFun Arduino ProtoShield - Bare PCB

DEV-13819
$4.95
SparkFun ProtoShield Kit

DEV-13820
$9.95

Suggested Materials

To follow along with this project tutorial, you will need the following materials. Depending on what you have, you may not need everything listed here. Add it to your cart, read through the guide, and adjust the cart as necessary.

Tools

You will need a soldering iron, solder, general soldering accessories, and the tools listed below for prototyping.

Solder Lead Free - 100-gram Spool

TOL-09325
$7.95
7
Wire Strippers - 30AWG (Hakko)

TOL-12630
$9.95
3
Needle Nose Pliers

TOL-08793
$1.95
1
Weller WLC100 Soldering Station

TOL-14228
$44.95
Diagonal Cutters

TOL-08794
$1.95
2

Suggested Reading

If you aren’t familiar with the following concepts, we recommend checking out these tutorials before continuing.

How to Solder: Through-Hole Soldering

This tutorial covers everything you need to know about through-hole soldering.

Arduino Shields

All things Arduino Shields. What they are and how to assemble them.

What is an Arduino?

What is this 'Arduino' thing anyway?

Installing Arduino IDE

A step-by-step guide to installing and testing the Arduino software on Windows, Mac, and Linux.

Using the BlueSMiRF

How to get started using the BlueSMiRF and Bluetooth Mate Silvers.

How to Work w/ Jumper Pads and PCB Traces

Handling PCB jumper pads and traces is an essential skill. In this tutorial, you will learn how to cut a PCB trace and add a solder jumper between pads to reroute connections. You will also learn how to repair a trace with the green wire method if a trace is damaged.

Suggested Viewing

Hardware Overview

There is a lot going with the ProtoShield so it is useful to know what side we are referencing when soldering components to the board. We will refer to the top side based on the board’s name on the upper right hand corner. The bottom will be the side with the jumpers.

Top ViewBottom View

Stackable Headers for Arduino Uno R3 Footprint

The Arduino ProtosShield is based off the Arduino R3’s footprint. Headers can be installed on the pins located closest to the edge of the board. You will notice that the location of the headers are highlighted in a rectangular silkscreen. For those using the stackable headers included in the kit, make sure to insert the header from the top side and solder from the bottom.

Arduino Uno R3 Footprint

These pins are also broken out on the other side of its labeling. You will notice that the 1x10 header on the upper right side of the board is slightly offset from the Arduino R3 footprint. Don't worry, this was intentional so that you can place the board on a standard breadboard!

Arduino R3 Footprint Broken Out

Prototyping Area

Next up is the sea of plated through holes. Look at all that great space for prototyping projects!

Prototyping Area

Solderless Mini-Breadboard

Do you have a small circuit on a mini-breadboard connected to your RedBoard or Arduino Uno? The ProtoShield has a spot to place a mini-breadboard on top to keep everything together. Peel the adhesive off the mini-breadboard, align it to the silkscreen, and stack it on!

SolderLess Mini-Breadboard

Solderable-Like Breadboard

Once you are done prototyping your circuit on the mini-breadboard, there is an option to solder the circuit directly to the board for a more secure connection. The bottom half of this area was designed with a breadboard in mind. You will not notice too much on the top side. Flip the board over and you will see open jumper pads between each through hole to make a connection like a breadboard. Once you add a component, simply add a solder jumper between holes to make a connection. For those that prefer the standard prototyping pads, we left the other side as is.

Solderable-Like Breadboard (Top View)Solderable-Like Breadboard w/ Open Jumpers (Bottom View)

ICSP (NC)

Need to access the Arduino’s ICSP pins? The pins are broken out if you do not want to remove the shield every time you need the ICSP pins or if you decide to stack another shield on top of the ProtoShield. You will need add two 1x3 stackable headers.

SPI Pins (Not Connected)

Power

There are a few locations along the outside of the board for power and ground. Let's focus on the power rails in the prototyping area.

5V Rail

Just below the silkscreen for the mini-breadboard is a 5V rail. This is connected to the 5V pin from your Arduino.

5V Rail

VDD Rail (NC)

Need a different voltage? We squeezed a VDD rail just below. It is currently not connected to anything. We left it up to the user to connect to Arduino's 3.3V pin or another regulated voltage (i.e. 2.8V or 1.8V).

VDD Rail

GND Rail

Need to ground more circuits? There are few more ground connections on the board as indicated by the image below.

Ground Rail

Reset Button

Stacking a shield on an Arduino can make it hard to reset the microcontroller. Like other Arduino shields, the reset button has been rerouted on the ProtoShield.

Reset Button

Software Serial UART Port

The SparkFun Arduino ProtoShield breaks out a software serial UART port. The pins are arranged in such a way as to connect to our BlueSMiRF if you decide to go wireless.

Software Serial UART

If you decide that you want to connect a different serial UART device or use different pins for serial, we added closed jumpers on the back. Simply cut the traces and reroute the connection by adding wires to the headers.

Software Serial UART Jumper Pins

Oh Snap! ProtoSnap-able Prototyping Hardware

The board includes prototyping hardware that is based on the ProtoSnap design. When you are finished testing and want to use bigger components, simply snap off the bottom of the board using pliers.

ProtoSnap-able

3mm LEDs (NC)

When viewing the board from the top, there are two locations for 3mm LEDs and their 330Ω current limiting resistors.

3mm LEDs (Not Conencted)

Momentary Pushbutton (NC)

There is a spot for a momentary pushbutton and 10kΩ pull up resistor on the other side of the LEDs.

Momentary Pushbutton (Not Connected)

Hardware Assembly

Headers

Grab a female stackable header and slide it from the top side of the ProtoShield. With your soldering hand, pull the header with your index finger and thumb toward the edge of the board. Using your other hand, push against the header using your index finger and grip the board with your thumb. Hold the header down with your middle finger.

Grab the soldering iron with your soldering hand and tack on one pin. Repeat for each header.

Tack on One Pin on the Header and Repeat

Buttons

Insert the buttons for reset and prototyping. You may need to bend the buttons to fit into the through holes. Careful not to snap off the prototyping area! Hold the button against the board and tack some solder on one pin.

Tack on the Buttons

LEDs

Find the 3mm LED's anode side and align it with its silkscreen labeled with a “” sign. Slide the LED in from the top side and tack on a pin. Repeat for the second LED.

Align the LED and Tack on a Pin

Resistors

The kit includes resistors with two different values. There is one 10k&ohm; resistor [color band = BROWN, BLACK, ORANGE, GOLD ] that is used as a pull-up resistor. The two 330&ohm; resistors [color band = ORANGE, ORANGE, BROWN, GOLD] are used to limit current to the LEDs.

10k&ohm; Pull-Up Resistor330&ohm; Current Limiting Resistor

Let's start with the pull-up resistor. Bend the 10kΩ resistor's terminals.

Bend Resistor

Then slide the pins where it says “10k”.

Add the 10kΩ Pull-Up Resistor

Bend the terminals to hold the resistor in place for soldering. The resistor can get hot to the touch when holding the component down during soldering. At this point, feel free to grab a small piece of cardboard to hold the resistor down. When you are ready, tack one of the 10k&ohm; resistor's pins. Repeat for the 330&ohm; resistors.

Check Alignment Before Soldering Away!

At this point, it would be good to check the alignment of the components. Make sure that they are flush against the board and they are in its correct location. Did you add solder for the components on the bottom side? All of the components included in the kit should be soldered on the side of the jumpers.

Everything good? Solder away! This is the fun part.

Solder All the Pins Down

Cut Excess Leads

Grab a flush cutter and trim off excess leads connected to the prototyping hardware. Careful not to cut off the stackable headers!

Cut Off Excess Leads

Finished ProtoShield

If you used water soluble flux, clean the board off. Otherwise, bask in the glow of your new ProtoShield for Arduino! Your board should look similar to the images below with the terminals soldered and cut.

Finished ProtoShield

Customize

So what do you do from here? There are a few options! We left this up to the user to choose depending on personal preference. You can stick a mini-breadboard on the shield for prototyping small circuits. Additional headers can be added on however you would like for serial UART or in the prototyping area. For a lower profile, you can also strip hookup wire and solder cables against the plated through holes.

For those sandwiching the ProtoShield with another shield, you can solder two 1x3 stackable headers for the ICSP pins. If you choose this route, you will need to go with a lower profile, using wires to connect the circuit.

Close Up of ICSP Pins w/ Stackable HeadersProtoShield w/ Stackable Headers

Finished Prototyping?

If you are finished prototyping, you can remove the mini-breadboard and solder your custom circuit to the prototyping area for a more secure connection. Want to use a different LED or a bigger button in your project? You can snap off the prototyping area using needle nose pliers and replace it with the hardware of your choice!

Big Dome Pushbutton - Red

COM-09181
$9.95
14
Metal Pushbutton - Momentary (16mm, Red)

COM-11966
$4.95
3
NovelKeys Big Switch - Tactile

COM-14583
$30.00
Super Bright LED - Red 10mm

COM-08862
$1.50
1

Example Code

Note: The following examples assumes you are using the latest version of the Arduino IDE on your desktop. If this is your first time using Arduino, please review our tutorial on installing the Arduino IDE.

Blinking LED

Let's connect L1 to pin 13 using a wire. Assuming that you soldered to L1, connect it to pin 13.

Prototyping Hardware Arduino
L113

Copy the code below and upload to your Arduino!

language:c
/*BLINKING AN LED

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

  This sketch was written by SparkFun Electronics,
  with lots of help from the Arduino community.
  This example is based on the blinking an LED
  example in the SparkFun Inventor's Kit v3.3.

  This code is completely free for any use.
  Visit https://learn.sparkfun.com/tutorials/sik-experiment-guide-for-arduino---v33/experiment-1-blinking-an-led
  for more information.
  Visit http://www.arduino.cc to learn about the Arduino.

  Version 2.0 6/2012 MDG
******************************************************************************/


// The LED is connected to digital pin 13
// Change the pin number depending on 
// what L1 is connected to.
const int L1 = 13;

void setup()
{
  pinMode(L1, OUTPUT);  //Set L1 to output
}

void loop()
{
  digitalWrite(L1, HIGH);   // Turn on the LED
  delay(1000);                     // Wait for one second
  digitalWrite(L1, LOW);    // Turn off the LED
  delay(1000);                     // Wait for one second
}

LED labeled as L1 should begin blinking.

Blink

Fading LED

Let's connect L2 to pin 6 and to fade in and out. Assuming that you soldered to L2, connect it to pin 6.

Prototyping Hardware Arduino
L26

Copy the code below and upload to your Arduino!

language:c
/* Fading LED

  Use for-loops to smoothly vary the brightness of an LED

  This sketch was written by SparkFun Electronics,
  with lots of help from the Arduino community.
  This example is based on the Fading LEDs example
  in the LilyPad Development Board Activity Guide.

  This code is completely free for any use.
  Visit https://learn.sparkfun.com/tutorials/lilypad-development-board-activity-guide/4-fading-leds
  for more information
  Visit http://www.arduino.cc to learn about the Arduino.

******************************************************************************/

// Create integer variable for the LED pin we'll be using:
const int L2 = 6;

// Create a new integer variable called brightness:
int brightness;

void setup()
{
  // Set the LED pins to be output:
  pinMode(L2, OUTPUT);
}

void loop()
{
  // The two "for loops" below will make a LED fade on and off in a "breathing" pattern.

  // Now we'll have the program automatically change the value of brightness
  // using a command called "for".

  // for is like a tiny version of loop. The for command has several parts:
  // 1. something to do before starting (brightness = 0)
  // 2. a test to decide whether to keep going (brightness <= 255)
  // 3. a block of commands to run (everything within the {} below the for)
  // 4. a command to run before doing it again (brightness = brightness + 1)

  // Here's a for command which will start brightness at 0, check to see if it's less than
  // or equal to 255, run the commands after it, then add one to brightness and start over:

  for (brightness = 0; brightness <= 255; brightness = brightness + 1)
  {
    // Within the loop, we'll use brightness variable to control the brightness of the LEDs:

    analogWrite(L2, brightness);

    // NOTE that not all pins work with analogWrite!
    // The ones with a "~" in front of them will change brightness,
    // the others will only turn on if brightness > 128.
    // Both types are used above, run the code and note the difference between them.

    // The delay command controls the speed - if you make the delay larger,
    // it will slow down the loop. Smaller, and it will run faster:

    delay(5);
  }

  // What if we want the LED to start at full brightness and fade to black?
  // We can easily set up the for loop to run in reverse:

  for (brightness = 255; brightness >= 0; brightness = brightness - 1)
  {
    analogWrite(L2, brightness);
    delay(5);
  }
}

LED labeled as L2 should begin fading in and out. Try connecting and redifining the LED to another pin on your Arduino to see if you can still fade.

Blink

Momentary Push Button

Let's connect SW2 to pin 2 to read a push button. For feedback, we will be using both of the LEDs in our prototyping hardware. Assuming that you soldered to SW2, L2, and L1, connect it to their respective pins on 2, 6, and 13.

Prototyping Hardware Arduino
SW22
L26
L113

Copy the code below and upload to your Arduino!

language:c
/*Momentary Push Button

  Use momentary pushbuttons for digital input

  This sketch was written by SparkFun Electronics,
  with lots of help from the Arduino community.
  This example is based on the push button
  example in the SparkFun Inventor's Kit v3.3

  This code is completely free for any use.
  Visit https://learn.sparkfun.com/tutorials/sik-experiment-guide-for-arduino---v33/experiment-5-push-buttons
  for more information.
  Visit http://www.arduino.cc to learn about the Arduino.

  Version 2.0 6/2012 MDG
  Version 2.1 9/2014 BCH
****************************************************************/

const int SW2 = 2;  // pushbutton 1 pin
const int L1 =  13;    // LED pin
const int L2 =  6;     // LED pin

int button1State;  // variables to hold the pushbutton states

void setup()
{
  // Set up the pushbutton pins to be an input:
  pinMode(SW2, INPUT);
  // Set up the LED pin to be an output:
  pinMode(L1, OUTPUT);
  pinMode(L2, OUTPUT);
}

void loop()
{
  button1State = digitalRead(SW2);

  // if SW2 is pressed
  if (button1State == LOW) {
    digitalWrite(L1, HIGH);  // turn the LED on
    digitalWrite(L2, HIGH);  // turn the LED on
  }
  else {
    digitalWrite(L1, LOW);  // turn the LED off
    digitalWrite(L2, LOW);  // turn the LED off
  }
}

Pressing on the button should light up both LEDs simultaneously. Removing your finger from the button should turn them off.

Push Button LEDs

Bluetooth Serial Passthrough

Let's try to send a character between two BlueSMiRF Silvers (i.e. the RN42s). In this example, we will need two bluetooths, ProtoShields, and Arduinos. Assuming that the boards are soldered, connect the BlueSMiRFs to the Software Serial UART port. We will be using the default connection to software serial pins 10 and 11. Simply align the silkscreen as indicated in the hookup table below.

BlueSMiRF Silver ProtoShield Software Serial UART port
RX-IRXI (D11)
TX-OTXO (D10)
GNDGND (GND)
VCCVCC (5V)

We will also be using the same connection to the prototyping hardware.

Prototyping Hardware Arduino
SW22
L26
L113

Power both up, copy the code below, and upload to both Arduinos!

language:c
/*
  Example Bluetooth Serial Passthrough Sketch
  modified by: Ho Yun "Bobby" Chan
  date: May 17, 2018
  by: Jim Lindblom
  date: February 26, 2013
  SparkFun Electronics
  license: Public domain

  This example sketch converts an RN-42 bluetooth module to
  communicate at 9600 bps (from 115200), and passes any serial
  data between Serial Monitor and bluetooth module.
****************************************************************/

#include <SoftwareSerial.h>

int bluetoothTx = 10;  // TX-O pin of bluetooth mate, Arduino D10
int bluetoothRx = 11;  // RX-I pin of bluetooth mate, Arduino D11

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);// (Arduino SS_RX = pin 10, Arduino SS_TX = pin 11)

void setup()
{
  Serial.begin(9600);  // Begin the serial monitor at 9600bps

  bluetooth.begin(115200);  // The Bluetooth Mate defaults to 115200bps
  bluetooth.print("$");  // Print three times individually
  bluetooth.print("$");
  bluetooth.print("$");  // Enter command mode
  delay(100);  // Short delay, wait for the Mate to send back CMD
  bluetooth.println("U,9600,N");  // Temporarily Change the baudrate to 9600, no parity
  // 115200 can be too fast at times for NewSoftSerial to relay the data reliably
  bluetooth.begin(9600);  // Start bluetooth serial at 9600
}

void loop()
{
  if (bluetooth.available()) // If the bluetooth sent any characters
  {
    // Send any characters the bluetooth prints to the serial monitor
    Serial.print((char)bluetooth.read());
  }
  if (Serial.available()) // If stuff was typed in the serial monitor
  {
    // Send any characters the Serial monitor prints to the bluetooth
    bluetooth.print((char)Serial.read());
  }
  // and loop forever and ever!
}

Arduino ProtoShield Bluetooth

Discovering, Pair, and Autoconnecting Bluetooths

Once uploaded,

  • open the Arduino Serial Monitor set at 9600 baud with No line ending
  • send $$$ and hit the Send button to set the bluetooth in command mode
  • change the Arduino Serial Monitor from No Line Ending to Newline
  • send the autoconnect command sm,3
  • send the inquiry scan command i to scan for the other bluetooth in range

You should see something similar to the output below.

language:bash
CMD
AOK
Inquiry, COD=0
Found 1
000666643FBF,RN42-3FBF,1F00
Inquiry Done

The other RN42 bluetooth that was in range came up with address of 000666643FBF. You should see something similar when connecting a RN-41 or RN-42. Type the following command and change the address to the one that you obtained:

  • c,000666643FBF and hit the Send button

This will pair and connect both bluetooths together. The address will be saved in memory and auto connect every time there is a power cycle. Open a serial terminal (since you can only have one Arduino Serial Monitor open at a time) set at 9600 baud and connect the other Arduino/ProtoShield/BlueSMiRF. Sending any character from the Arduino Serial Monitor should pop up on the serial terminal and vice versa!

Combining It All to Send a Message!

Let's send a simple message between the two bluetooths now that they are configured to autoconnect. Copy the code below, and upload to both Arduinos!

language:c
/*
  Example Serial Bluetooth Messenger
  by: Ho Yun "Bobby" Chan
  SparkFun Electronics
  date: May 16, 2018
  license: Public domain

  This example sketch converts an RN-42 bluetooth module to
  communicate at 9600 bps (from 115200). Assuming that the
  two bluetooths are paired and configured to autoconnect,
  a message is sent with the push of a button. Any 
  received characters from the other bluetooth will display 
  on the serial monitor. 

  This sketch was written by SparkFun Electronics.
  This example is based on the Example Bluetooth Serial 
  Passthrough Sketch by Jim Lindblom.

  This code is completely free for any use.
  Visit https://learn.sparkfun.com/tutorials/using-the-bluesmirf
  for more information.
****************************************************************/

#include <SoftwareSerial.h>

const int SW2 = 2;  // pushbutton 1 pin
const int L1 =  13;    // LED pin for push button
const int L2 =  6;     // LED pin for received character

int button1State;  // variables to hold the pushbutton states

int bluetoothTx = 10;  // TX-O pin of bluetooth mate, Arduino D10
int bluetoothRx = 11;  // RX-I pin of bluetooth mate, Arduino D11

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);// (Arduino SS_RX = pin 10, Arduino SS_TX = pin 11)

void setup()
{
  // Set up the pushbutton pins to be an input:
  pinMode(SW2, INPUT);
  // Set up the LED pin to be an output:
  pinMode(L1, OUTPUT);
  pinMode(L2, OUTPUT);

  Serial.begin(9600);  // Begin the serial monitor at 9600bps

  bluetooth.begin(115200);  // The Bluetooth Mate defaults to 115200bps
  bluetooth.print("$");  // Print three times individually
  bluetooth.print("$");
  bluetooth.print("$");  // Enter command mode
  delay(100);  // Short delay, wait for the Mate to send back CMD
  bluetooth.println("U,9600,N");  // Temporarily Change the baudrate to 9600, no parity
  // 115200 can be too fast at times for NewSoftSerial to relay the data reliably
  bluetooth.begin(9600);  // Start bluetooth serial at 9600
}

void loop()
{
  button1State = digitalRead(SW2);

  //Send a character
  if (button1State == LOW) //if SW2 is pressed
  {
    // Send characters to bluetooth to transmit
    bluetooth.println("Hi!");
    digitalWrite(L1, HIGH);  // turn the LED on
  }
  else {
    digitalWrite(L1, LOW);  // turn the LED off
  }

  // If the bluetooth received any characters, print to the serial monitor
  if (bluetooth.available())
  {
    // Send any characters the bluetooth prints to the serial monitor
    Serial.print((char)bluetooth.read());
    digitalWrite(L2, HIGH);  // turn the LED on
  }
  else {
    digitalWrite(L2, LOW);  // turn the LED on
  }
  // and loop forever and ever!
}

Pressing a button on one of the Arduinos (as indicated by the blue mini-breadboard) should send a message and light up the LED labeled as L1 on the transmitting node. The receiving node (as indicated by the green mini-breadboard) will light up the LED labeled as L2 and print a message (in this case “Hi!”) to a serial monitor or serial terminal. The other Arduino will to the same when you press on its button.

Sending a Saved Message

Resources and Going Further

Now that you’ve successfully got your protoshield for Arduino up and running, it’s time to incorporate it into your own project!

For more information, check out the resources below:

Need some inspiration for your next project? Check out some of these related tutorials:

8-Pin SOIC to DIP Adapter Hookup Guide

Assembly and application of the 8-pin SOIC-to-DIP adapter.

Discrete Semiconductor Kit Identification Guide

Get to know the contents of the SparkFun Discrete Semiconductor Kit.

Capacitor Kit Identification Guide

Learn how to identify and use a variety of capacitors using the SparkFun Capacitor Kit.

Reading and Writing Serial EEPROMs

EEPROM is a great way to add extra memory to your microcontroller project. Wait 'til you see how easy it is to use!

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

IoT Power Relay

$
0
0

IoT Power Relay a learn.sparkfun.com tutorial

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

Introduction

In this tutorial, we’ll show you how to host a webpage on the ESP32 Thing that will allow you to set times for a power relay to be turned on or off.

picture of the completed project

It utilizes our ESP32 Thing, IoT Power Relay, and the Qwiic Micro OLED screen to create a smart outlet that can maintain a weekly schedule for powering any AC powered load you want to cycle regularly.

Required Materials

Hardware

To follow this project, you will need the following materials. Depending on what you have, you may not need everything on this list. Add it to your cart, read through the guide, and adjust the cart as necessary.

Software

You will need the Arduino IDE with the ESP32 software support package installed. In addition, you’ll need to download the IoT_Power_Relay code from GitHub. Visit the links to access the installs and code as well as more information on installing board support for the ESP32 in Arduino.

Tools

You will need a good soldering iron, solder, general soldering accessories, and a screw driver to follow along.

Solder Lead Free - 15-gram Tube

TOL-09163
$3.50
2
Soldering Iron - 30W (US, 110V)

TOL-09507
$9.95
6
SparkFun Mini Screwdriver

TOL-09146
$0.95
3

Suggested Reading

Before undertaking this project, there are a few tutorials that you may want to review.

How to Solder: Through-Hole Soldering

This tutorial covers everything you need to know about through-hole soldering.

ESP32 Thing Hookup Guide

An introduction to the ESP32 Thing's hardware features, and a primer on using the WiFi/Bluetooth system-on-chip in Arduino.

Hardware Hookup

Base Plate

You’ll need to use a snappable protoboard to create a base plate to work from. Snap it to a size that will cover the ESP32 without obscuring the antenna–20 holes by 10 holes. We want to solder down male pins to the underside of the base plate, as shown below. Note the use of a breadboard as a fixture to hold the pins perpendicular to the plate.

Soldering the headers to the base plate using a breadboard as a fixture

You’ll also need to solder down the wires used to connect to the IoT Relay box. I like to use the cheap jumper wires we sell for this purpose, as the plastic ferrule on the ends provides strain relief.

Jumper wires soldered to base plate for trigger signal

Qwiic Connector

Since we don’t have a Qwiic connector handy, we’ll use our Qwiic adapter board to provide a Qwiic-compatible connector. Solder the header down as shown below. It should be directly centered on the base plate.

Header for Qwiic adapter in place on base plate

Once you’ve soldered down the header (you’ll need to remove the base plate from the breadboard to access the underside of it), you can solder the adapter to the header on the top side of the board.

Qwiic adapter in place on header

Route the Signals

Route the two wires you soldered on earlier to GND and pin 5 (9th pin down on the right hand side, if the edge that will be closest the antenna is on top).

We’ll also need to route the signals to the Qwiic adapter – 3.3V, GND, SDA and SCL. SDA and SCL are broken out to pins 21 and 22, respectively, on the ESP32 Thing. When you’re done, you should have something that looks like this:

Signals routed to proper pins on the base plate

ESP32 Thing

We want female headers on our Thing board to mate with the male headers on the base plate. You’ll need to cut to length the female headers from the wishlist. Remember that you’ll lose one pin to the cutting, so you need two pieces of the full size header. In the picture below, note how I’m using the base plate to hold the headers perpendicular to the ESP32 board for soldering.

Soldering the female headers to the ESP32

You should now have something that looks a lot like this picture:

The final ESP32 board and base plate board assembled and ready to go

Fitting It All Together

It might help to mount the IoT Relay and ESP32 Thing to some kind of base, such as a piece of plywood or even corrugated cardboard, before finishing the assembly. I didn’t do that, so I could continue to manipulate the hardware for pictures.

Pull the screw terminal out of the side of the IoT Relay. You won’t be able to screw down the wires without doing this.

Grabbing the screw terminal

It takes a significant amount of force to pull the screw terminal free of the box, and you may find that you need a pair of pliers or something similar to get it free

Screw terminal free of the box

You may now screw the wires you attached to the base plate into the screw terminal block. Note the polarity markings on the IoT Relay box. Make sure you connect the ‘-’ terminal to GND and the ‘+’ terminal to the wire routed to pin 5 on the ESP32 Thing.

Wires screwed into the terminal block and the terminal block back in the box

Now, place the base plate onto the ESP32 Thing. Be careful of the orientation, making sure that the Qwiic connector is on the end farthest from the antenna.

Base

Finally, connect the Micro OLED to the Qwiic connector. You’ll probably want to affix that to the base along with the ESP32 Thing and the IoT Relay box. I suggest hot glue.

Final assembly of all the parts

ESP32 Example Code

Note: This example assumes you are using the latest version of the Arduino IDE on your desktop. If this is your first time using Arduino, please review our tutorial on installing the Arduino IDE. If you have not previously installed an Arduino library, please check out our installation guide.

With Arduino installed, please make sure you also download and install the ESP32 software support package.

ESP32 Software Support Package GitHub

And lastly, download the IoT_Power_Relay GitHub repo which contains the firmware you’ll be uploading to the ESP32.

IoT_Power_Relay GitHub Repo

Now that we have our basics, let’s go over the code that will be programmed onto the ESP32!

Core Code

This is the core code, in the TeleSitter.ino main file.

The includes section holds all the library references needed for this project. time.h is the ESP32 native time library, while TimeLib.h is the Arduino time library. We use both of them because time.h does graceful NTP server synchronization, while TimeLib.h is better for tracking current time and reacting to it.

Preferences.h is the ESP32 non-volatile memory support module.

language:c
#include <WiFi.h>
#include "PageContent.h"
#include "time.h"
#include <Preferences.h>
#include "TimeLib.h"
#include "SFE_MicroOLED.h"
#include <Wire.h>

Next, we set up a few constant strings: SSID, WiFi password, and the address of the ntpServer we wish to use. “pool.ntp.org” is an open NTP project great for things like this.

language:c
const char* ssid      = "ssid_goes_here";
const char* password  = "wifi_password_goes_here";
const char* ntpServer = "pool.ntp.org";

We use global variables to track the times that we turn on and off our power switch. In the full code, there are four variables for each day. Only Monday’s variables are shown here.

language:c
int mHoursOn = 8;
int mMinutesOn = 0;
int mHoursOff = 0;
int mMinutesOff = 0;

Here we set up defines for our project. We use pin 5 for controlling the switch because it has an LED on it, making testing easy. The MicroOLED library requires a reset pin to be defined, even if it isn’t used, and requires a note on the status of the jumper on the back of the MicroOLED board. We leave the jumper set to ‘1’, which is the default that it ships with.

language:c
#define CTRL_PIN 5
#define OLED_RESET 10 // Not used, but needed for initialization
#define DC_JUMPER 1   // Default value. If you didn't change the jumper
                      //  on the PCB, this is what you want.

Next we create objects that will be used throughout the code. The port number for the server is passed to the constructor; 80 is the default port for http requests and that number shouldn’t be changed.

language:c
WiFiServer server(80);
MicroOLED oled(OLED_RESET, DC_JUMPER);
Preferences alarmTimes; 

setup(). Does typical setup-y things like printing debugging messages during startup, configuring the serial port and pins, etc.

language:c
void setup()
{
  Serial.begin(115200);
  pinMode(CTRL_PIN, OUTPUT);  // Also has a blue LED on the ESP32 Thing

  // We start by connecting to a WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

During setup, we try to connect to WiFi. It’s been my experience that if the WiFi doesn’t connect within 10-15 seconds, it’s probably not going to, and the smartest thing to do is reset the ESP32. This section of the code handles that.

language:c
  int wifiCounter = 0;
  while (WiFi.status() != WL_CONNECTED) 
  {
    delay(500);
    Serial.print(".");
    if (++wifiCounter > 30) ESP.restart();
  }

  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

During normal operation, we can’t count on the user to have a computer attached to the ESP32. Thus, we provide the OLED to tell the user what the current IP address is.

  // Initialize the OLED and display the IP address
  oled.begin();
  oled.clear(PAGE);
  oled.setCursor(0,0);
  oled.print(WiFi.localIP());
  oled.display();

The ESP32 has an odd way of storing data in non-volatile memory. You must create a region (“TeleSitter”, here), and then issue a begin() call to the library. Note that the second parameter to begin() must, per the documentation, always be false.

language:c
  // Initialize the NVM storage handler and fetch the cached
  //  alarm time information.
  alarmTimes.begin("TeleSitter", false);
  getAlarmTimes();

  // Enable the server functionality.
  server.begin();

Timekeeping initialization. Read the comments for more information on how and why the timekeeping is done the way it is.

language:c
  // We use two different timekeeping services, the ESP32 built-in
  //  and the one from the Arduino TimeLib. Why? Because the ESP32
  //  based one gets its time from an NTP server and it's unclear
  //  which functions it uses that ping the NTP server, so we want
  //  to avoid excessive NTP checks.

  // Preeeetty sure configTime() pings the NTP server. Parameters
  //  are GMT offset in seconds, DST offset in seconds, and NTP
  //  server address.
  configTime((-7*3600), 0, ntpServer);
  // A tm struct holds time info. It can be current local time, as
  //  here, or an arbitrary time, as used elsewhere.
  struct tm timeinfo;
  // Unclear as to whether getLocalTime() populates the tm struct
  //  solely from the local clock or from the NTP server. Thus, we
  //  avoid calling it too often by setting the Arduino timekeeping
  //  with it at boot time, then using the Arduino timekeeping for
  //  most of our timekeeping duties.
  getLocalTime(&timeinfo);
  // Set the Arduino library timekeeping to currrent time derived
  //  from the NTP server. We have to add 1 to the month as returned by
  //  the ESP32 module, as Arduino numbers months starting from 1 and ESP
  //  numbers starting from 0. Also, add 1900 to the year, as Arduino stores
  //  the full year number and ESP stores it as an offset from year 1900.
  setTime(timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec, 
          timeinfo.tm_mday, timeinfo.tm_mon+1, timeinfo.tm_year + 1900);
  // Check to see if DST is in effect. This function relies upon
  //  having the Arduino timekeeping set. We'll repeat this check
  //  once a day at 3am and reset the Arduino clock accordingly.
  if (dstCheck()) configTime((-7*3600), 3600, ntpServer);
  else configTime((-7*3600), 0, ntpServer);
  // Fetch the current time into timeInfo again. This is now DST
  //  correct local time.
  getLocalTime(&timeinfo);
  // Set the Arduino clock to DST correct local time.
  setTime(timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec, 
          timeinfo.tm_mday, timeinfo.tm_mon+1, timeinfo.tm_year + 1900);
}

loop(). Starts out by doing a health check on the WiFi connection. IF the WiFi connection is lost, the ESP32 will reboot.

language:c
void loop(){

  // Health check. If we've lost our wifi connection, restart
  //  the ESP to (hopefully) reconnect without user noticing.
  if (WiFi.status() != WL_CONNECTED) 
  {
    Serial.println("WiFi dropped; rebooting");
    delay(100);
    ESP.restart();
  }

Every pass through loop, we check our alarm status to see if we should turn the output on or off. We’ll talk about what exactly is involved in the alarm checking later.

language:c
  checkAlarm();

Check if it’s 0300 local time or not. If it is, we go through the clock setting process again. We only do this once a day because our clock is good enough to keep time over 24 hours fairly accurately and because we don’t want to accidentally activate rate limiting on the NTP server. We do it at 0300 because that is a good time to catch the DST shift.

language:c
  if (hour() == 3 && minute() == 0 && second() == 0)
  {
    struct tm timeinfo;
    getLocalTime(&timeinfo);
    setTime(timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec, 
            timeinfo.tm_mday, timeinfo.tm_mon + 1, timeinfo.tm_year + 1900);
    // Check to see if DST is in effect. 
    if (dstCheck()) configTime((-7*3600), 3600, ntpServer);
    else configTime((-7*3600), 0, ntpServer);
    getLocalTime(&timeinfo);
    setTime(timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec, 
            timeinfo.tm_mday, timeinfo.tm_mon + 1, timeinfo.tm_year + 1900);
  }

This code was taken more or less directly from the example code provided with the ESP32 library. It handles incoming requests by serving up the webpage that we will create later, then checking what the nature of the request is and taking some action based on that. Note that, regardless of the request, the webpage is served back.

language:c
  WiFiClient client = server.available();   // listen for incoming clients
  if (client) {                             // if you get a client,
    Serial.println("New Client.");          // print a message out the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected())              // loop while the client's connected
    {            
      if (client.available())               // if there's bytes to read from the client,
      {             
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        if (c == '\n')                      // if the byte is a newline character
        {                    
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) 
          {

We split the response into several blocks, to make editing easier, and unlike the original example, we make our webpage in constants defined elsewhere. Note the use of printf() in the body printing section. That allows us to push variables from our code to the webpage.

language:c
           client.print(pageContentHead);
            client.printf(pageContentBody, mHoursOn, mMinutesOn, mHoursOff, mMinutesOff,
                                           tHoursOn, tMinutesOn, tHoursOff, tMinutesOff,
                                           wHoursOn, wMinutesOn, wHoursOff, wMinutesOff,
                                           rHoursOn, rMinutesOn, rHoursOff, rMinutesOff,
                                           fHoursOn, fMinutesOn, fHoursOff, fMinutesOff,
                                           sHoursOn, sMinutesOn, sHoursOff, sMinutesOff,
                                           nHoursOn, nMinutesOn, nHoursOff, nMinutesOff);
            // Print out the current time and date. This is useful for debugging
            //  as it's the only way to check the internal server clock.
            client.printf("%d:%02d:%02d<br>", hour(), minute(), second());
            client.printf("%d/%d/%d %d<br>", day(), month(), year(), weekday());
            client.print(pageContentFoot);
            break;
          } 
          else                // if you got a newline, then clear currentLine:
          {    
            currentLine = "";
          }
        } 
        else if (c != '\r')   // if you got anything else but a carriage return character,
        {
          currentLine += c;      // add it to the end of the currentLine
        }

We expect to get a few types of response from the client that connects to this device. These can be differentiated by the text in the response. For instance, a request for the path reset should trigger a reset of the alarm times, and an HTTP get request that starts with a question mark indicates an incoming string of data that is to be parsed into alarm times.

language:c
        if (currentLine.endsWith("GET /reset"))
        {
          resetAlarmTimes();
        }
        if (currentLine.endsWith("HTTP/1.1"))
        {
          if (currentLine.startsWith("GET /?"))
          {
            parseIncomingString(currentLine);
            storeAlarmTimes();
          }
        }
      }
    }
    // close the connection:
    client.stop();
    Serial.println("Client Disconnected.");
  }
}

Lastly, we have a few chunks of code that don’t really belong anywhere else, so we stick them at the end of the main code.

language:c
void turnOn()
{
  digitalWrite(CTRL_PIN, HIGH);
}

void turnOff()
{
  digitalWrite(CTRL_PIN, LOW);
}

void printTitle(String title, int font)
{
  int middleX = oled.getLCDWidth() / 2;
  int middleY = oled.getLCDHeight() / 2;

  oled.clear(PAGE);
  oled.setFontType(font);
  // Try to set the cursor in the middle of the screen
  oled.setCursor(middleX - (oled.getFontWidth() * (title.length()/2)),
                 middleY - (oled.getFontWidth() / 2));
  // Print the title:
  oled.print(title);
  oled.display();
  delay(1500);
  oled.clear(PAGE);
}

Alarm Handling Code

Alarms.ino handles the checking of the alarm times: whether or not the output should be turned on. It calculates the time of the day, in seconds, then calculates the times the output should be on or off depending upon the day of the week. It then does a comparison of those times and takes the appropriate action.

language:c
void checkAlarm()
    {
      int dow = weekday();
      int secsOfDay = hour()*3600 + minute()*60 + second();
      int timeOn, timeOff;
      switch(dow)
      {
        case 1: // Sundays
          timeOn = nHoursOn*3600 + nMinutesOn*60;
          timeOff = nHoursOff*3600 + nMinutesOff*60;
          break;
        case 2: // Mondays
          timeOn = mHoursOn*3600 + mMinutesOn*60;
          timeOff = mHoursOff*3600 + mMinutesOff*60;
          break;
        case 3: // Tuesdays
          timeOn = tHoursOn*3600 + tMinutesOn*60;
          timeOff = tHoursOff*3600 + tMinutesOff*60;
          break;
        case 4: // Wednesdays
          timeOn = wHoursOn*3600 + wMinutesOn*60;
          timeOff = wHoursOff*3600 + wMinutesOff*60;
          break;
        case 5: // Thursdays
          timeOn = rHoursOn*3600 + rMinutesOn*60;
          timeOff = rHoursOff*3600 + rMinutesOff*60;
          break;
        case 6: // Fridays
          timeOn = fHoursOn*3600 + fMinutesOn*60;
          timeOff = fHoursOff*3600 + fMinutesOff*60;
          break;
        case 7: // Saturdays
          timeOn = sHoursOn*3600 + sMinutesOn*60;
          timeOff = sHoursOff*3600 + sMinutesOff*60;
          break;
      }
      if (timeOn > timeOff)
      {
        if (secsOfDay > timeOn) turnOn();
        else if (secsOfDay > timeOff) turnOff();
      }
      else
      {
        if (secsOfDay > timeOff) turnOff();
        else if (secsOfDay > timeOn) turnOn();
      }
    }

Non-Volatile Memory Functionality

NVM.ino handles the various accesses to non-volatile memory that must be managed. This includes setting and resetting the alarm times and loading the alarm times into memory upon startup.

Again, I’ve removed redundant code for the additional days of the week to make things a little simpler to follow.

resetAlarmTimes() simply sets the on time to 0800 and the off time to 0000 and then stores it to NVM.

language:c
void resetAlarmTimes()
    {
      mHoursOn = 8;
      mMinutesOn = 0;
      mHoursOff = 0;
      mMinutesOff = 0;
      storeAlarmTimes();
    }

storeAlarmTimes() takes the current global alarm time variables and stores them into NVM. Note that storage into NVM is dependent upon data type; we use putInt() because our time data is of type int.

language:c
void storeAlarmTimes()
{
  alarmTimes.putInt("mHoursOn", mHoursOn);
  alarmTimes.putInt("mMinutesOn", mMinutesOn);
  alarmTimes.putInt("mHoursOff", mHoursOff);
  alarmTimes.putInt("mMinutesOff", mMinutesOff);
}

getAlarmTimes() is the opposite of storeAlarmTimes(). Note the use of getInt() here to correspond to putInt() earlier.

language:c
void getAlarmTimes()
{
  mHoursOn = alarmTimes.getInt("mHoursOn", 8);
  mMinutesOn = alarmTimes.getInt("mMinutesOn", 0);
  mHoursOff = alarmTimes.getInt("mHoursOff", 0);
  mMinutesOff = alarmTimes.getInt("mMinutesOff", 0);
}

Parse Input from Client

The client responds to a button press by sending a large string of values to the ESP32 Thing. We need to parse those values out into their appropriate hour and minute times. The code in ParseInput.ino does just that.

language:c
void parseIncomingString(String str)
    {
      String str0 = "mHoursOn=";
      String str1 = "&mMinutesOn=";
      mHoursOn = extractInteger(str, str0, str1);
      str0 = str1;
      str1 = "&mHoursOff=";
      mMinutesOn = extractInteger(str, str0, str1);
      str0 = str1;
      str1 = "&mMinutesOff=";
      mHoursOff = extractInteger(str, str0, str1);
      str0 = str1;
      str1 = "&tHoursOn=";
      mMinutesOff = extractInteger(str, str0, str1);

      str0 = str1;
      str1 = "&tMinutesOn=";
      tHoursOn = extractInteger(str, str0, str1);
      str0 = str1;
      str1 = "&tHoursOff=";
      tMinutesOn = extractInteger(str, str0, str1);
      str0 = str1;
      str1 = "&tMinutesOff=";
      tHoursOff = extractInteger(str, str0, str1);
      str0 = str1;
      str1 = "&wHoursOn=";
      tMinutesOff = extractInteger(str, str0, str1);

      str0 = str1;
      str1 = "&wMinutesOn=";
      wHoursOn = extractInteger(str, str0, str1);
      str0 = str1;
      str1 = "&wHoursOff=";
      wMinutesOn = extractInteger(str, str0, str1);
      str0 = str1;
      str1 = "&wMinutesOff=";
      wHoursOff = extractInteger(str, str0, str1);
      str0 = str1;
      str1 = "&rHoursOn=";
      wMinutesOff = extractInteger(str, str0, str1);

      str0 = str1;
      str1 = "&rMinutesOn=";
      rHoursOn = extractInteger(str, str0, str1);
      str0 = str1;
      str1 = "&rHoursOff=";
      rMinutesOn = extractInteger(str, str0, str1);
      str0 = str1;
      str1 = "&rMinutesOff=";
      rHoursOff = extractInteger(str, str0, str1);
      str0 = str1;
      str1 = "&fHoursOn=";
      rMinutesOff = extractInteger(str, str0, str1);

      str0 = str1;
      str1 = "&fMinutesOn=";
      fHoursOn = extractInteger(str, str0, str1);
      str0 = str1;
      str1 = "&fHoursOff=";
      fMinutesOn = extractInteger(str, str0, str1);
      str0 = str1;
      str1 = "&fMinutesOff=";
      fHoursOff = extractInteger(str, str0, str1);
      str0 = str1;
      str1 = "&sHoursOn=";
      fMinutesOff = extractInteger(str, str0, str1);

      str0 = str1;
      str1 = "&sMinutesOn=";
      sHoursOn = extractInteger(str, str0, str1);
      str0 = str1;
      str1 = "&sHoursOff=";
      sMinutesOn = extractInteger(str, str0, str1);
      str0 = str1;
      str1 = "&sMinutesOff=";
      sHoursOff = extractInteger(str, str0, str1);
      str0 = str1;
      str1 = "&nHoursOn=";
      sMinutesOff = extractInteger(str, str0, str1);

      str0 = str1;
      str1 = "&nMinutesOn=";
      nHoursOn = extractInteger(str, str0, str1);
      str0 = str1;
      str1 = "&nHoursOff=";
      nMinutesOn = extractInteger(str, str0, str1);
      str0 = str1;
      str1 = "&nMinutesOff=";
      nHoursOff = extractInteger(str, str0, str1);
      str0 = str1;
      str1 = " HTTP/1.1";
      nMinutesOff = extractInteger(str, str0, str1);
    }

    int extractInteger(String str, String sub0, String sub1)
    {
      int index0 = 0;
      int index1 = 0;
      index0 = str.indexOf(sub0) + sub0.length();
      index1 = str.indexOf(sub1);
      return str.substring(index0, index1).toInt();
    }

Check for Daylight Saving Time

In much of the world clocks are set back by one hour and forward by one hour once per year. In most of the US, this is done (forward) on the second Sunday in March and (back) on the first Sunday in November. dstCheck.ino contains code I wrote for SparkFun’s Big GPS clock to automate handling of DST changes.

language:c
// This code was lifted more or less whole-hog from the SparkFun Big GPS Clock
//  project. I wrote that too.

bool dstCheck()
{
  //Serial.println("DST Check");
  // As of 2007, most of the US observes DST between the 2nd Sunday morning in
  //  March and the 1st Sunday morning in November. DST in the US changes by
  //  time zone, so at 2am local time on the 2nd Sunday in March, we increase
  //  the offset from UTC by one hour.

  // We can bail out if month is < 3 or > 11.
  if ( (month() < 3) || (month() > 11) )
  {
    return false;
  }

  // We can also bail out if month is > 3 and < 11.
  if ( (month() > 3) && (month() < 11) )
  {
    return true;
  }

  // Okay, edge cases, March and November. We can do a couple more low-math
  //  checks to quickly decide whether the date is a possible one.
  // For November, the date of the first Sunday *must* be less than 8, so if
  //  the date is greater than 8, we can return false.
  if (month() == 11)
  {
    if (day() > 7)
    {
      return false;
    }
    // Otherwise, we need to figure out whether we've seen the first Sunday
    //  yet.
    TimeElements firstOfNovTE;
    firstOfNovTE.Day = 1;
    firstOfNovTE.Month = 3;
    firstOfNovTE.Year = year();
    firstOfNovTE.Hour = 0;
    firstOfNovTE.Minute = 0;
    firstOfNovTE.Second = 0;
    time_t firstOfNov = makeTime(firstOfNovTE);
    int8_t firstDayOfNov = weekday(firstOfNov);
    int8_t firstSundayOfNov = (9 - firstDayOfNov) % 7;
    // If we *haven't* seen the first Sunday yet, we are in DST still.
    if (day() < firstSundayOfNov)
    {
      return true;
    }

    // If it's *after* the first Sunday, we aren't in DST anymore.
    if (day() > firstSundayOfNov)
    {
      return false;
    }

    // If we're here, it's the first Sunday of November right now, and we only
    //  need to know if the current hour is < 2; at 0200 MST, DST ends.
    if (hour() < 2)
    {
      return true;
    }
    return false;
  }

  // For March, dates less than 8, or greater than 13 are automatically out.
  if (month() == 3)
  {
    if (day() < 8)
    {
      return false;
    }
    if (day() > 13)
    {
      return true;
    }

    // Otherwise, we need to figure out whether we've see the second Sunday
    //  yet. 
    // TimeElements is a struct, but we have to initialize it in the long-form, due
    //  to limitations of the compiler used by the Arduino IDE.
    TimeElements firstOfMarTE;
    firstOfMarTE.Day = 1;
    firstOfMarTE.Month = 3;
    firstOfMarTE.Year = year();
    firstOfMarTE.Hour = 0;
    firstOfMarTE.Minute = 0;
    firstOfMarTE.Second = 0;
    time_t firstOfMar = makeTime(firstOfMarTE);
    int8_t firstDayOfMar = weekday(firstOfMar);
    int8_t secondSundayOfMar = ((9 - firstDayOfMar) % 7) + 7;

    // If we *haven't* seen the second Sunday yet, we aren't in DST yet.
    if (day() < secondSundayOfMar)
    {
      return false;
    }

    // If it's *after* the second Sunday, we are in DST now.
    if (day() > secondSundayOfMar)
    {
      return true;
    }

    // If we're here, it's the second Sunday of November right now, and we only
    //  need to know if the current hour is < 2; at 0200 MST, DST starts.
    if (hour() < 2)
    {
      return false;
    }
    return true;
  }
  return false; // We *should* never get here, but we need to return something
                //  or chaos ensues.
}

Web Page Content

PageContent.h declares three different page content chunks: a header, a body, and a footer. Those are merely our demarcations and don’t actually correspond to HTML concepts with the same name.

Header

The header is defined as type String. It contains the http response code information, content type information, and all of the html header information up to and including the opening tag for the page’s body content. It also includes some CSS to format the page. Note the use of backslashes to escape the newline at the end of each line. An alternative is to surround each line in its own set of double quotes, but I find this easier to read.

language:html
String pageContentHead = 
"HTTP/1.1 200 OK\r\n\
Content-type:text/html\r\n\
\r\n\
<!DOCTYPE html> <html>\
<style>\
input[type=text] {\
  width: 20px;\
}\
form {\
  font-family: monospace;\
}\
table, th, td {\
  text-align: left;\
  border: 5px;\
}\
</style>\
<head>\
<title>TeleSitter</title>\
</head>\
<body>";

Body

The body text is defined as a character array. This is to facilitate use of the printf() command later to insert values into the body text.

I’ve again trimmed the content here to remove duplicated code. Normally, there would be a table entry for every day of the week, along with a time validater for each day. I’ve left only the Monday table entry and validater as an example. The validater uses client-side Javascript to check the times and make sure they make sense before sending a response to the server. If you try to put invalid time information into any of the fields, you’ll get an error and the server won’t be contacted.

language:html
char pageContentBody[] =
    "<form id=\"timeForm\">\
    <table>\
    <tr>\
    <th>Day</th><th>On Time</th><th>Off Time</th>\
    </tr>\
    <tr>\
    <td>Monday</td>\
    <td><input type=\"text\" name=\"mHoursOn\" value=\"%d\">:<input type=\"text\" name=\"mMinutesOn\" value=\"%02d\"></td>\
    <td><input type=\"text\" name=\"mHoursOff\" value=\"%d\">:<input type=\"text\" name=\"mMinutesOff\" value=\"%02d\"></td>\
    </tr>\
    <tr>\
    </table>\
    <button type=\"button\" onClick=\"submitTimes()\">Submit</button><br>\
    <a href=\"/reset\">Reset times</a><br>\
    </form>\
    <p id=\"responseText\"></p>\
    <script>\
    function submitTimes() {\
      var hrs, mins, text;\
      \
      hrs = document.forms[\"timeForm\"][\"mHoursOn\"].value;\
      mins = document.forms[\"timeForm\"][\"mMinutesOn\"].value;\
      if (!validateHrs(hrs)) return;\
      if (!validateMins(mins)) return;\
      hrs = document.forms[\"timeForm\"][\"mHoursOff\"].value;\
      mins = document.forms[\"timeForm\"][\"mMinutesOff\"].value;\
      if (!validateHrs(hrs)) return;\
      if (!validateMins(mins)) return;\
      text = \"Times valid!\";\
      document.getElementById(\"timeForm\").submit();\
      document.getElementById(\"responseText\").innerHTML = text;\
    }\
    \
    function validateMins(mins) {\
      if (isNaN(mins) || mins < 0 || mins > 59) {\
        return false;\
      }\
      return true;\
    }\
    \
    function validateHrs(hrs) {\
      if (isNaN(hrs) || hrs < 0 || hrs > 23) {\
        return false;\
      }\
      return true;\
    }\
    \
    </script>";

Footer Text

Not much to see here, just closing up the HTML.

language:html
String pageContentFoot =
"</body>""</html>\r\n";

What You'll See

Open a web browser and type in the address from the micro OLED screen. This is what you’ll see when you load the webpage served by the ESP32 in your web browser.

TeleSitter page screenshot

You can update each day’s times individually and submit the times using the submit button. To make things a little easier to code, times are in 24-hour format. The current date and time according to the clock on the ESP32 are also displayed.

Try adding a device like a lamp to the “normally OFF” outlet. Anything scheduled to be on as indicated by the time should be powered and vice versa. If you are remotely powering the ESP32 Thing, try adding a USB power supply to the “always ON” outlet.

Resources and Going Further

For more information, check out the resources below:

  • W3Schools - This is a great website to help you learn more about writing for the web. I figured out most of how to write the page in this tutorial using W3School’s excellent tutorials.
  • Simple WiFi Server Example - The original example that I started with for this project. It may be easier to start with this if you want to customize the server.
  • ESP32.com– Great forums, where you can discuss ESP32 news, get help, or show off your project.
  • ESP-IDF – IoT Development Framework– If you want to take your development environment up a step from Arduino, this should be your first step into ESP32 software development. Some notes on the IDF:
    • The IDF is well-documented. Check out the set up guides (for Windows, Mac or Linux) for help getting your environment set up. For help with the API’s and data structures, check out esp32.info.
    • There are a handful of example applications, including a BLE Advertising example, which works as a proof-of-concept for the ESP32’s Bluetooth support.
    • Use the ESP-IDF project template, once you’re ready to start creating applications of your own.
  • ESP32 Software Support Package
  • GitHub Repo - Project repo for the TeleSitter.

Check out these other great projects:

LED Cloud-Connected Cloud

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

Photon Remote Temperature Sensor

Learn how to build your own Internet-connect, solar-powered temperature collection station using the Photon from Particle.

ESP8266 Powered Propane Poofer

Learn how Nick Poole built a WiFi controlled fire-cannon using the ESP8266 Thing Dev Board!

IoT Industrial Scale

What does a baby elephant weigh? How much impact force does a jump have? Answer these questions and more by building your very own IoT industrial scale using the SparkFun OpenScale.

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

Adapting LilyPad Development Board Projects to the LilyPad ProtoSnap Plus

$
0
0

Adapting LilyPad Development Board Projects to the LilyPad ProtoSnap Plus a learn.sparkfun.com tutorial

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

Introduction

The LilyPad ProtoSnap Plus is an update and re-envisioning of the successes of the LilyPad Development Board, one of our most popular e-textile products. After many discussions with educators using the LilyPad Development Board in their programs and classrooms, our development team created a new board designed with new features and updates for improved ease of use for both students and facilitators. This guide will provide an overview of the changes made during the development of the LilyPad ProtoSnap Plus and how to adapt existing code or curriculum from the LilyPad Development for use with the ProtoSnap Plus.

Labeled side-by-side comparison of LilyPad Development Board and LilyPad ProtoSnap Plus

New Features in the ProtoSnap Plus

Clear, Visual Layout— The silver traces connecting LilyPad boards together to illustrate their electrical connections are a key feature of the ProtoSnap series. The new LilyPad ProtoSnap Plus includes easy-to-follow traces for students to use as a guideline for their design projects before breaking them apart and during programming lessons. In the LilyPad Development Board, many of these traces were hidden or difficult to see and point out during a lesson.

Labeled LilyPad ProtoSnap Plus

LilyPad USB Plus— Many users prefer the LilyPad USB over other formats and have been asking for an update to the Development Board to include one. SparkFun’s product team created the LilyPad USB Plus with added features including a built-in RGB LED and LED bar graph, as well as two additional power (+) and ground (-) sew tabs for ease of use.

LilyPad USB Plus with tabs labeled

The LilyPad USB Plus

Updated Labeling— Each sew tab on the LilyPad USB Plus includes a symbol (~) at the center indicating PWM capability or analog-to-digital converter (ADC) for quick reference for users during prototyping. This eliminates the need to look at documentation or datasheets while teaching and building. These labels are also included on the bottom of the LilyPad boards. The labeling extends to board names clearly beside the hardware on the ProtoSnap board for quick identification when teaching or exploring.

More LEDs— One of the most compelling early activities when learning to program is to create blinking light patterns with Arduino. Students can create quite complex programs using just an LED and their imagination. The LilyPad ProtoSnap Plus replaces the five white LEDs and tri-color LED offered on the original LilyPad Development Board with four pairs of colored LEDs (yellow, red, blue, green), an RGB LED, and six white LEDs in a bar graph configuration. Building the RGB and white LEDs onto the LilyPad USB Plus microcontroller freed up sew tabs to connect other LilyPad boards and eliminated additional sewn connections.

Close Up of Built-In LEDs

Expansion Ports— To increase flexibility of the new ProtoSnap Plus, four expansion ports were added that allow students to explore different sensor and output options not available pre-wired on the board, including I2C boards.

Example Sensor Connected to Expansion Port

For a full overview of the LilyPad ProtoSnap Plus and its features, check out the LilyPad ProtoSnap Plus Hookup Guide.

LilyPad ProtoSnap Plus Hookup Guide

October 5, 2017

The LilyPad ProtoSnap Plus is a sewable electronics prototyping board that you can use to learn circuits and programming with Arduino, then break apart to make an interactive fabric or wearable project.

Board Comparison Chart

Below is a table that lists the components available on each of the boards. Note that in the ProtoSnap Plus, some boards have been removed. These can easily be hooked up again using the Expansion Ports on tabs A9, 10, and 11.

LilyPad Development Board ComponentLilyPad Development Board PinLilyPad ProtoSnap Plus PinNotes
LilyPad Vibe Board (+)3N/AThe ProtoSnap Plus does not include a vibe board.
LilyPad Tri-Color LEDRed LED: 9
Green LED: 11
Blue LED: 10
Red LED: 12
Green LED: 13
Blue LED: 14
The ProtoSnap Plus replaces a standalone tri-color LED with a built-in RGB LED on the LilyPad USB at the center of the board.
LilyPad ButtonA5A4
LilyPad Switch2A92 is a hidden tab on the Development Board.
LilyPad Temperature Sensor (S)A1N/AThe ProtoSnap Plus does not include temperature sensor.
LilyPad Light Sensor (S)A6A2The ProtoSnap Plus uses an updated light sensor.
LilyPad Buzzer (+)7A37 is a hidden tab on the Development Board
5 LilyPad LEDs (+)White LED 1: 5
White LED 2: 6
White LED 3: A2
White LED 4: A4
White LED 5: A3
Yellow LED pair: A5
Red LED pair: 6
Green LED pair: A7
Blue LED pair: A8
The LilyPad ProtoSnap Plus replaces the 5 white LEDs with pairs of colored LEDs. It also includes an LED bar graph of white LEDs built into the LilyPad USB Plus on pins 15-20.

Adapting and Uploading Code to the ProtoSnap Plus

Code written for the LilyPad Development Board can be adapted for use with the ProtoSnap Plus with a few simple changes.

First, identify if the parts are pre-wired and included on the LilyPad ProtoSnap Plus using the Board Comparison Chart. Simply update the pin number assigned in your Development Board code to the coordinating connection on the ProtoSnap Plus.

To test boards not included on the ProtoSnap Plus, use alligator clips to connect them from one of the three Expansion Ports at the right edge of the board.

Alligator Test Leads - Multicolored (10 Pack)

PRT-12978
$2.95
3

LilyPad Vibe Board

Connect the positive (+) tab of the LilyPad Vibe Board to one of the Expansion Ports and reassign the pin number in your code. We recommend using Expansion Port 10 if you wish to use PWM with the vibe board.

LilyPad Vibe Board

DEV-11008
$5.95

LilyPad Tri-Color LED

The LilyPad USB Plus at the center of the ProtoSnap Plus has a built-in RGB LED that can be used in place of the LilyPad Tri-Color LED. Note that the Tri-Color LED included on the LilyPad Development Board was a common anode while the RGB on the USB Plus is a common cathode, so your code may have to be adapted slightly to function the same.

LilyPad Tri-Color LED

DEV-08467
$2.95
2

Note on Common Anode vs Common Cathode

The color channels on the Tri-Color LED LED are all connected through a common anode (positive) pin. Unlike some other RGB LEDs, this configuration means that to light up the LED you need to ground the individual red, green, and blue LEDs instead of sending them power. For simple circuit hookups, this means you need to connect the R, G, or B sew tabs to ground (-) and in code set them to LOW (for digital output) or 0 (for analog output) to turn them on.




The RGB LED on the tri-color LED has 4 connections: red, green, blue channels, and a common anode pin. If you look closely you can see the individual LEDs inside the package.

External Tri-Color LED

You may also connect a Tri-Color LED to the three Expansion Ports. Only Expansion Port 10 has PWM functionality, so fading the LEDs can only happen on one of the RGB channels in this hookup method.

LilyPad Temperature Sensor

Connect the S tab of an external LilyPad Temperature Sensor to Expansion Port A9 and reassign the pin number associated with the temperature sensor in your code to A9.

LilyPad Temperature Sensor

DEV-08777
$3.95

Uploading Code

Before uploading your code to the ProtoSnap Plus, you will need to select a new board from the Board menu. The LilyPad Development Board uses a LilyPad Arduino while the LilyPad ProtoSnap Board uses a LilyPad USB Plus. If you keep LilyPad Arduino selected, it will display an error upon upload. Refer to the LilyPad ProtoSnap Plus Hookup Guide for full instructions on how to add support for the board and upload code to the USB Plus.

Arduino IDE Board Selection

Resources and Going Further

For more information related to LilyPads, check out the resources below:

Choosing a LilyPad Arduino for Your Project

Not sure which LilyPad Arduino is right for you? We'll discuss the features of each and help you decide.

Getting Started with LilyPad

An introduction to the LilyPad ecosystem - a set of sewable electronic pieces designed to help you build soft, sewable, interactive e-textile projects.

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

Variable Load Hookup Guide - Revised

$
0
0

Variable Load Hookup Guide - Revised a learn.sparkfun.com tutorial

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

Introduction

SparkFun’s Variable Load board is designed to allow users to draw a specific amount of current from a voltage source. It can be used to test stability of the power supply under various loads, battery lifetime, safety cutoffs, and other design elements of power supplies under test.

The Variable Load can test supplies of up to 30V at currents ranging from a few mA to 4A. For safety, the total load power is limited to 15W, and even at 15W the heatsink gets very hot. The Variable Load is designed to be extensible, with headers for a basic character-based LCD so it can be used without a connection to a PC.

SparkFun Variable Load Kit

KIT-14449
$39.95
1

Required Materials

Everything you need to follow this hookup guide is included in the kit, except for the heat sink thermal compound linked below. If you want to add an LCD, any of our 5V character LCDs will work, as linked below. You’ll also need some male header pins. You may not need everything though depending on what you have. Add it to your cart, read through the guide, and adjust the cart as necessary.

Break Away Headers - Straight

PRT-00116
$1.50
20
Basic 16x2 Character LCD - Black on Green 5V

LCD-00255
$13.95
10
USB micro-B Cable - 6 Foot

CAB-10215
$4.95
9
Basic 16x2 Character LCD - White on Black 5V

LCD-00709
$15.95
10
Basic 16x2 Character LCD - RGB Backlight 5V

LCD-10862
$14.95
2
Basic 16x2 Character LCD - Yellow on Blue 5V

LCD-00790
$14.95
1
Heatsink Compound

PRT-09599
$1.95

Required Tools

For assembly of this kit, you will need standard soldering tools. Any soldering iron of reasonable quality and solder should work fine. To mount the transistor to the heat sink, a Phillips head screwdriver is required.

SparkFun Mini Screwdriver

TOL-09146
$0.95
3

Assembly

We recommend following this guide for easy assembly of the kit.

Install the Heat Sink

This may seem a little backwards, but there’s a reason for this. We want to make sure that the hole in the heat sink is at the right height for the hole in the transistor to mate with it, and the heat sink is of fixed height, so we want to install it first.

Heat sink nubs

Note that soldering these nubs down takes patience and a willingness to get things pretty hot. If you don’t heat the nubs up enough, the solder won’t flow over them nicely and you’ll get a gloppy, goopy cold solder joint. Heating the nubs takes time, of course, because they’re attached to a heat sink! Persist and don’t become discouraged if the solder won’t flow onto the nubs at first. Give it lots of time. If you have one, a large, hoof-type soldering iron tip is the best bet for heating up the nubs for a good joint.

Soldering nubs

Note too that there are no exposed copper pads on the PCB. This is okay, as the solder will flow over the nubs and down through the holes, forming a tight fit.

Nubs soldered

Install the Terminal Block

This is a good time to install the terminal block. Notice which side of the board it is installed on, and the orientation of the terminal block with the silkscreen.

Terminal block

Soldering it down should be a fairly straightforward endeavor.

Install the Transistor On the Heat Sink

Apply a small amount of thermal grease to the back of the transistor. This will improve heat transfer to the heat sink.

Thermal grease

Then, insert the 3/8" 4-40 machine screw through the hole in the transistor. Insert the legs of the transistor into the holes on the PCB and slide the pins down until the screw fits through the hole on the heat sink.

Thread the 4-40 nut onto the screw where it protrudes through the heat sink.

Nut threaded onto screw

Tighten down the nut until it is snug. A screwdriver will help with this process. Do not overtighten the screw. It only needs to be a little tighter than finger tight. Then, flip the board and solder the transistor pins to the board.

Screw placed

Attach the standoffs to the corners of the board.

Standoff assembly

Finally, connect a micro-B cable to the Variable Load and your computer to get started.

Optional: Install the LCD Assembly

If you’re going to use the Variable Load with the optional LCD, now is the time to attach it.

Start by installing the header on the LCD. Observe the image below for proper orientation.

Header in LCD

I like to tack down one pin first. Then melt the solder on that pin with one hand and use the other to make sure the header is at a right angle to the board. After soldering down all the pins, you can insert the header into the Variable Load board and repeat the process. Solder down the headers like the image below.

LCD mated to variable load board

The LCD is now in place and should just work when powered up. Connect a micro-B USB cable to the Variable Load and your computer to get started.

LCD Showing Output

Operation

The Variable Load board is designed to work with one of two output modes. Either using a:

  • Console on a PC for Feedback
  • Basic 16x2 Character LCD

In either case, the capacitive touch buttons on the front of the Variable Load PCB can be used to change the settings.

General Operation

The primary method for controlling the Variable Load is the set of capacitive touch buttons on the front of the board. There are four buttons: up arrow, down arrow, “Enter” and “Back”. The up and down arrow keys will adjust the current set point up or down in steps determined by the present set point. The higher the set point, the larger the step size. The “Enter” key turns the load on or off without affecting the set point, and the “Back” button resets the set point to zero.

Capacitive Touch Buttons

There is an LED visible from the front of the board which will tell you whether the load is enabled or disabled at any given time.

Load Status LED

The voltage limit for the board is 40V. Exceeding this level may cause damage to the circuits on board. The current limit is 4A, and the board will not in any case let you set a current draw above 4A. There is also a wattage limit of 15W, which is calculated in live time. Normally, the current draw remains the same as the voltage is increased, but if the voltage is increased beyond a point where the product of the voltage and current exceeds 15W, the output will be disabled until the voltage drops to a safe point again.

Using a Console for Output

Start by checking out our serial terminal basics tutorial. This will get you up and running with a serial terminal. Open a serial terminal program (i.e. PuTTY) to connect.

You’ll need to identify the port name of the Variable Load board when it is connected. There are a few methods of determining which port the Variable Load Board is connected to.

One method to determine which port the Variable Load board is on, I recommend using the Arduino IDE. Under the “Tools” menu, there is a sub-menu for “Port”. Since we had connected the USB cable to a computer’s COM port already, make note of the items on the listed port names. Then unplug the micro-B USB cable from your computer. Give it a few seconds, then re-open that sub-menu to see what item has disappeared. By process of elimination, we can determine the port name that the Variable Load has enumerated to. Reconnect the cable to verify. The port name should reappear as the same name in the sub-menu. Remember, the Arduino IDE’s Serial Monitor will not work with the Variable Load board.

Windows

If you don’t have the Arduino IDE installed and don’t want to install it, you can find the same information using built in tools. Under Windows, open up your device manager (if you don’t know how to do this, do a search online for OS specific information on how to do it since it’s slightly different under various versions of Windows). Take note of the devices on the list, then unplug the Variable Load and see which port on the list disappears. The port which disappeared from the list is the one you want.

Windows device manager

Mac

Using a Mac OS, you’ll need to open a terminal window. To figure out which port the Variable Load has connected to, type this command:

language:bash
ls /dev/cu.usbserial-*

This will return a list of USB-Serial converter ports on the system. Take note of the devices on the list, then unplug the Variable Load and see which port on the list disappears. The port which disappeared from the list is the one you want. You can then connect to the port in question by typing this command:

language:bash
screen /dev/cu.usbserial-XXXXXXXX 115200

where the XXXXXXXXX is replaced by information gleaned from the first command.

Linux

Under Linux, the process is similar to Mac OS, only use this command to identify the serial port:

language:bash
ls /dev/ttyUSB*

You may use screen command to connect to the Variable Load:

language:bash
screen /dev/ttyUSBX 115200

Again, the “X” should be replaced with information gleaned from the ls command above. If you receive an error about screen not being installed, you can install screen by typing this command:

language:bash
sudo apt-get install screen

Then re-enter the above command to connect via screen.

The Console

This is what the console will look like when you’ve connected to the Variable Load. It reports five values:

  • I Source– the actual current being drawn from the source
  • I Limit– the current limit set for the load
  • V Source– the current load voltage at the Variable Load board
  • V Min– the current minimum voltage before the load cuts out
  • mA Hours– the number of milliamp hours drawn from the source since it was last reset

The console as viewed with the variable load connected

The console may be used to set two values: I limit and V min. To set I limit, type “I” followed by a decimal value and then hit the Enter key. To set the V min voltage, type “V” and then a decimal value and hit the enter key.

The console can also be used to enable or disable the supply. Simply type “E” followed by the enter key to toggle the supply on or off. It can also be used to reset the amount of energy drawn from the supply (the mAh number)–type “R” and hit Enter.

Finally, the console is used to put the device into bootloadable mode. Enter “B” and then hit the Enter key and the board will reset itself into bootloader mode. The bootloader host application within PSoC Creator can then be used to load new code onto the board.

Using the LCD

The LCD output is very similar to the console, except slightly less verbose to fit the data on it. You can use the console and the LCD at the same time, but that sort of defeats the purpose of using the LCD. When using the LCD alone, you’ll have to rely on the buttons on the board to control the set point.

LC Showing Output

Changing the Firmware

All of the firmware is available on the GitHub page for the product. You can customize the firmware as you need using the bootloader on the board, without having to use a programming cable, so long as your board has the most updated firmware. Boards shipped prior to 24 May 2018 do not have a bootloader on them.

PSoC Creator

Download and unzip the files from the GitHub repository for the Variable Load board.

Download GitHub Repository for Variable_Load (ZIP)

Open the Variable_Load.cyprj project file in PSoC Creator. Under the build configuration, set it to Release mode.

Select Release Mode

In the menu bar, select Build > Build All Projects to generate the files for the project. The one that we are interested in is the application file for the bootloader (Variable_Load.cyacd) which will be used later.

Build All Projects

Entering Bootloader Mode

To place the board in bootloader mode, open a console connected to the board and type “B” and hit Enter. The console will lose its connection and the board will reenumerate with a different port number. You can now bootload the board.

Using the Bootloader Host Application

To open the bootloader host application, open the “Tools” menu in PSoC Creator and select “Bootloader Host…”.

Where to find the bootloader host menu item in creator

This window will appear. Select the new COM port number for your board in the list.

The bootloader host application window

Baud rate, data bits, stop bits and parity can all be left as-is. So can “Active application”, and the “Security key” box can be left unchecked. Click the “” button next to the file to bring up the file selection dialog.

The application file for the bootloader is of type “*.cyacd” and it can be found in the firmware directory under “…/CortexM3/ARM_GCC_541/Release”, assuming you are using PSoC Creator 4.2 with a build configuration set in Release mode.

The path to the bootloader app file

The *.cyacd file will automatically be generated whenever the project is built. Note that using the “Program” button in the main PSoC Creator menu bar does not work for bootloaded projects!

The last step in the bootloading process is to click the “Program” button in the button bar at the top of the Bootloader Host window. You should see messages indicating a successful programming scroll past in the text window at the bottom of the window.

Where to find the program button

Resources and Going Further

Now that you’ve successfully got your Variable Load Kit up and running, it’s time to incorporate it into your own project!

For more information, check out the resources below:


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


PIC-Based Serial Enabled Character LCD Hookup Guide

$
0
0

PIC-Based Serial Enabled Character LCD Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The PIC-based serial enabled character LCD (a.k.a. SerLCD) backpack is a simple and cost effective solution for interfacing to character Liquid Crystal Displays (LCDs) based on the HD44780 controller. The backpack simplifies the number of wires needed and allows your project to display all kinds of text and numbers.

SparkFun Serial Enabled LCD Backpack

LCD-00258
$16.95
4

The SerLCD backpack can also be found on a variety of serial enabled character LCDs with different color schemes, sizes, and input voltages. In this tutorial, we will connect to a serial enabled LCD and send ASCII characters to the display using an Arduino microcontroller.

Required Materials

To follow along with this tutorial, you will need the following materials at a minimum. Depending on what you have, you may not need everything on this list. Add it to your cart, read through the guide, and adjust the cart as necessary.

Tools

You may need a soldering iron, solder, and general soldering accessories, and screw driver depending on your setup.

Solder Lead Free - 100-gram Spool

TOL-09325
$7.95
7
Pocket Screwdriver Set

TOL-12891
$3.95
3
Weller WLC100 Soldering Station

TOL-14228
$44.95

Suggested Reading

If you aren’t familiar with the following concepts, we recommend checking out these tutorials before continuing.

How to Solder: Through-Hole Soldering

This tutorial covers everything you need to know about through-hole soldering.

Serial Communication

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

What is an Arduino?

What is this 'Arduino' thing anyway?

Installing Arduino IDE

A step-by-step guide to installing and testing the Arduino software on Windows, Mac, and Linux.

Logic Levels

Learn the difference between 3.3V and 5V devices and logic levels.

ASCII

A brief history of how ASCII came to be, how it's useful to computers, and some helpful tables to convert numbers to characters.

Hardware Overview

SerLCD v2.5 has some new features that make the SerLCD even more powerful and economical:

  • PIC microcontroller utilizes onboard UART for greater communication accuracy
    • The PIC16LF88 is populated on the SerLCD backpack
    • The PIC16F88 is populated on the built-in serial enabled LCDs
  • Adjustable baud rates of 2400, 4800, 9600 (default), 14400, 19200 and 38400
  • Operational backspace character
  • Incoming buffer stores up to 80 characters
  • Backlight transistor can handle up to 1A and can be connected to external loads
  • Pulse width modulation of backlight allows direct control of backlight brightness and current consumption
  • User definable splash screen

PIC-Based Serial Controller

Using the serial enabled controller, it is easy to connect to any microcontroller that has a serial UART port such as an Arduino, AVR, PIC, etc. The SerLCD supports 16 and 20 character-wide screens with 2 or 4 lines of display.


Redboard Connected to a Basic Character LCD in ParallelRedBoard Connected to Serial Enabled LCD

Input Voltage (VDD) and Logic Levels

Depending on your LCD’s specs, the input voltage may be 3.3V or 5V. For the LCDs listed below, the input voltage for the backpack must be 3.3V even though the silkscreen says 5V. The logic levels will be the same as the input voltage.

The LCDs listed below require an input voltage of 5V. Higher than 5.5V will cause damage to the PIC, LCD, and backlight (if attached). At 5V, the SerLCD uses 3mA with the backlight turned off and ~60mA with the backlight activated. The following LCDs do not have a SerLCD backpack.

Basic 16x2 Character LCD - Black on Green 5V

LCD-00255
$13.95
10
Basic 16x2 Character LCD - White on Black 5V

LCD-00709
$15.95
10
Basic 16x2 Character LCD - RGB Backlight 5V

LCD-10862
$14.95
2
Basic 16x2 Character LCD - Yellow on Blue 5V

LCD-00790
$14.95
1

The following LCDs have a backpack built into the board.

Serial Enabled 16x2 LCD - White on Black 5V

LCD-09395
$24.95
9
Serial Enabled 20x4 LCD - Black on Green 5V

LCD-09568
$29.95
19
Serial Enabled 16x2 LCD - Red on Black 5V

LCD-09394
$24.95
2

Contrast Control

The SerLCD and built-in serial LCDs comes equipped with a 10k potentiometer to control the contrast of the LCD. This is set during assembly and testing but may need correcting for your specific LCD module. Temperature and supply voltage can affect the contrast of the LCD. While powered, simply adjust the potentiometer with a screw driver.

SerLCD BackpackSerial Enabled LCD 16x2Serial Enabled LCD 20x4

Hi-Current Control Pin

The SerLCD v2.5 uses a general purpose, 1000mA NPN transistor to control the LCDs backlight. If you purchased the SerLCD module, you may use this pin as a general purpose, high power control pin. If you issue the backlight on/off command to the SerLCD or built-in serial LCD, the BL pin on the board can also be used to power / control other circuits with a maximum current of 1000 mA. This is usually the last pin on the top row of the LCD. Check your datasheet for proper pin outs.

SerLCD BackpackSerial Enabled LCD 16x2Serial Enabled LCD 20x4

Hardware Hookup

Assembling the SerLCD Backpack

Insert the SerLCD backpack’s long end of the headers through the back of a basic LCD. Solder the header on the top side of the LCD. The LCD should look like the images below after the terminals are cleaned (assuming that you are using water-soluble flux). If you are using the through holes under the screw terminals, make sure to solder to the pins before assembling the backpack to the basic LCD.

Top ViewBottom View

Connecting to an Arduino

To power and control a serial enabled LCD, you will need three pins. There are two rows of headers broken out on the backpack and built-in serial enabled LCDs. They are electrically identical, so you can use either one. The SerLCD backpack comes pre-populated with a 3-pin screw terminal. Simply insert M/M jumper wire to each of the screw terminals and tighten. You can also solder directly to the plated through holes on the bottom of the backpack.

Screw TerminalsPlated Through Holes

Instead of a screw terminal, the built-in serial enabled LCDs come pre-populated with a 3-pin polarized JST connector. The JST to breadboard jumper would be the easiest to connect to an Arduino. The cable only connects one way; press it in until it clicks. JST connectors are designed to be very snug; don’t pull on the wires to disconnect it, see our tutorial on the proper way to disconnect JST cables.

Input for Serial Enabled LCD 16x2Input for Serial Enabled LCD 20x4

Hookup Table

There are only three connections you need to make to the LCD. Check your LCD’s pinout before connecting to your Arduino. If you look closely at the LCD’s with the JST connector, the input voltage (VDD) and Rx are in different locations on the board depending on how it was populated.

Serial Enabled LCD Pinout Arduino Pin Description
RXD11Serial UART receive input to the display.
9600 baud (default), 8 bits, 1 stop, no parity.
GNDGNDGround for the power supply.
VDD3.3V or 5VPower supply, this should be either +3.3V or +5V
depending on the specs of your LCD.

Firmware Overview

Baud Rate

Set the serial interface to: 9600 baud, 8 bits of data, 1 start bit, 1 stop bit, and no parity (9600,8,1,1,N). This can be changed or updated using the following command set. However, be aware that if you change the communication protocol, you may not be able to re-connect or control the device until your microcontroller’s baud rate matches.

Data & Display Information

All settings are stored on onboard EEPROM and loaded during power up. To display data on the SerLCD and built-in serial enabled LCDs, you simply send ASCII-formatted characters using a serial interface which matches the communication protocol. This means that if you pass the ASCII character ‘r’ to the module, an ‘r’ will be displayed on the LCD at the next cursor position.

Configuration & Command Set

There are two reserved control characters used to control and configure various features on the LCD. The control characters are 0xFE and 0x7C. Sending a control character followed by a command will allow you to control the cursor, backlight, and other features on the SerialLCD. A complete table of commands are shown below in hexadecimal and decimal value in brackets. Either representation is acceptable when sending a control or command character. The HD44780 LCD controller is very common. The extended commands for this chip include but are not limited to those described in table. Please refer to the HD44780 datasheet for more information.

Control Character Command Character Description
0xFE [ 0d254 ]0x01 [ 0d1 ]Clear Display
0x14 [ 0d20 ]Move Cursor Right 1 Space
0x10 [ 0d16 ]Move Cursor Left 1 Space
0x1C [ 0d28 ]Scroll Right 1 Space
0x18 [ 0d24 ]Scroll Left 1 Space
0x0C [ 0d12 ]Turn Display On / Hide Cursor
0x08 [ 0d8 ]Turn Display Off
0x0E [ 0d14 ]Underline Cursor On
0x0D [ 0d13 ]Blinking Cursor On
0x80 + n [ 0d128 + p ]Set Cursor Position,
where n is the hexadecimal position and
p is the decimal value of the position
0x7C [ 0d124 ]0x03 [ 0d3 ]20 Characters Wide
0x04 [ 0d4 ]16 Characters Wide
0x05 [ 0d5 ]4 Lines
0x06 [ 0d6 ]2 Lines
0x09 [ 0d9 ]Turn Splash Screen On/Off
0x0A [ 0d10 ]Set Splash Screen
0x0B [ 0d11 ]Set to 2400 Baud
0x0C [ 0d12 ]Set 4800 Baud
0x0D [ 0d13 ]Set 9600 Baud (Default)
0x0E [ 0d14 ]Set 14400 Baud
0x0F [ 0d15 ]Set 19200 Baud
0x10 [ 0d16 ]Set 38400 Baud
0x80 [ 0d128 ]Backlight Off
0x9D [ 0d157 ]Backlight Full On
0x12 [ 0d18 ]Reset to Default Baud While
LCD's Splash Screen is Still Active

SerLCD Command Set

Clear Screen and Set Cursor Position

Clear display and set cursor position are the two commands that are used frequently. To clear the screen, send the control character 0xFE followed by 0x01. Clearing the screen resets the cursor position back to position 0 (i.e. the first character on the first line).

To set the active cursor position, send the control character 0xFE followed by 0x80 + n, where n is an offset in hexadecimal as described in the tables below. In this case, it would be easier to use the decimal value for setting the cursor position (0d128) with the viewable cursor position (p) and then send the value.

16 Character Displays
Line Number Viewable Cursor Positions
10-15
264-79
316-31
480-95
20 Character Displays
Line Number Viewable Cursor Positions
10-19
264-83
320-39
480-103

Example of Setting the Cursor Position

Say we want to the place a character on the third character position of the second line in a 16x2 character display. The cursor position is not what you would expect. Notice that the last character on line 2 jumps from 15 to 64 on the next line? To do this we need to:

  • Add 0x80 to the viewable cursor position as stated earlier. Since we are trying to add a hexadecimal value with a decimal, you would need to convert a value to the same representation. Since we know that 0x80 is also 0d128, we will just stick with decimal. Therefore, the third character on the second line in decimal is: 128 + 66 = 194.
  • Now that we know the position, send the command character 0xFE to tell the SerLCD you want to send a command followed by the number 194. If you are comfortable converting back to hexadecimal, you can also send 0x42.
  • The cursor should now be sitting in the third position of the second line. Sending any other character will display on the LCD starting at this position.

Setting Up the LCD Size

The SerLCD backpack’s firmware includes settings to interface for the following types of LCDs:

  • 16x2
  • 16x4
  • 20x2
  • 20x4

If you purchased the SerLCD backpack module by itself, you will have to configure the module to the type of LCD it is going to be, or is currently attached. To set the type of LCD the SerLCD module is attached to, transmit the control character 0x7C followed with either 0x03, 0x04, 0x05, or 0x06 as explained in the SerLCD Command Set above. These commands set the LCD character width and number of lines. These settings are used to correctly wrap the cursor to keep it within the viewable screen. The type of LCD is saved to EEPROM after each change.

If you purchased the built-in serial enabled LCD, it has already been configured to work with that specific LCD. You should not have to configure anything.

Changing the Baud Rate

The backpack and built-in serial enabled LCD defaults to 9600 baud, but they can be set to a variety of baud rates.

If the serial enabled LCD gets into an unknown state or you otherwise can’t communicate with it, try sending a “CTRL-R” (0x12) character at 9600 baud while the splash screen is active (during the first 500 ms of boot-up) and the unit will reset to 9600 baud.

Backlight Brightness

The SerLCD v2.5 provides you with control of the backlight to one of 30 different brightness levels. To control the backlight, send the control character 0x7C followed by a number from 0x80 to 0x9D. Sending a 0x80 sets the backlight to off and 0x9D sets the backlight to fully on.

This is handy when power consumption of the unit must be minimized. By reducing the brightness, the overall backlight current consumption is reduced.

Splash Screen

The SerLCD and built-in serial enabled LCD displays a splash screen by default. This splash screen verifies that the unit is powered, working correctly, and that the connection to the LCD is correct. The splash screen is displayed for 500 ms during boot-up and may be turned off if desired.

PIC-Based Serial Enabled Character LCD Tutorial-04 Splash Screen

Setting Splash Screen

A new addition to the V2.5 firmware is the ability for the user to set their own splash screen (2 lines). To do this, just set the top 2 lines as you would like them to appear, send the control character 0x7C followed by “CTRL-J” (0x09) to save it to memory. To test, just cycle power.

Turning Splash Screen On/Off

To disable the splash screen, send the control character 0x7C to the unit followed by “CTRL-J” (0x0A). Every time this command is sent to the unit, the splash screen display option will toggle. If the splash screen is currently being displayed, sending the 0x7C and 0x0A characters will disable the splash screen during the next boot, and sending the 0x7C and 0x0A characters again will enable the splash screen.

Extended Command

When testing the extended LCD command 0x0C, the command used all three of the following commands:

  • Turn Visual Display On
  • Underline Cursor Off
  • Blinking Box Cursor Off

So if you had the cursor/blinking box on and turned the visual display off, the cursor/blinking box would not remain on after after issuing the 0xFE control and 0x0C command value to turn the screen back on.

Example Code

Note: This example assumes you are using the latest version of the Arduino IDE on your desktop. If this is your first time using Arduino, please review our tutorial on installing the Arduino IDE. If you have not previously installed an Arduino library, please check out our installation guide.

For simplicity, we will be using an Arduino microcontroller. In this example, we connected a serial enabled LCD to the RedBoard programmed with Arduino (basically an Arduino Uno with an ATmega328P).

Example 1: Hello World!

Copy and paste these sketch into your Arduino IDE.

language:c
// SparkFun Serial LCD example 1
// Clear the display and say "Hello World!"

// This sketch is for Arduino versions 1.0 and later
// If you're using an Arduino version older than 1.0, use
// the other example code available on the tutorial page.

// Use the Software Serial library to create a new "soft" serial port
// for the display. This prevents display corruption when uploading code.
#include <SoftwareSerial.h>

// Attach the serial enabld LCD's RX line to digital pin 11
SoftwareSerial LCD(10, 11); // Arduino SS_RX = pin 10 (unused), Arduino SS_TX = pin 11 

void setup()
{
  LCD.begin(9600); // set up serial port for 9600 baud
  delay(500); // wait for display to boot up
}

void loop()
{
  // move cursor to beginning of first line
  LCD.write(254); 
  LCD.write(128);

  // clear display by sending spaces
  LCD.write(""); 
  LCD.write("");

 // move cursor to beginning of first line
  LCD.write(254); 
  LCD.write(128);

  LCD.write("Hello, world!");


// move cursor to beginning of second line
LCD.write(254);
LCD.write(192);

LCD.write("Less is more!^_^");

  while(1); // wait forever
}

When you power up the board, you’ll briefly see a SparkFun splash screen, and then the display will go blank. To send text to the board, wait 1/2 second (500ms) after power up for the splash screen to clear, then send text to the display through your serial port. The display understands all of the standard ASCII characters (upper and lowercase text, numbers, and punctuation), plus a number of graphic symbols and Japanese characters. See the HD44780 datasheet for the full list of supported characters.

If you send data that goes past the end of the first line, it will skip to the start of the second line. If you go past the end of the second line, the display will jump back up to the beginning of the first line.

Here's what you should see after uploading the code to your Arduino. Try changing the text with a different message!

Tutorial-03 Hello World

Example 2: Move the Cursor

A common LCD technique is to repeatedly display changing numbers such as RPM or temperature in the same place on the display. You can easily do this by moving the cursor before sending your data.

To move the cursor, send the special character (0xFE), followed by the cursor position you’d like to set. Each cursor position is represented by a number, see the table below to determine the number in decimal to send for a serial enabled LCD set to 16x2:

Position 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Line 1128129130131132133134135136137138139140141142143
Line 2192193194195196197198199200201202203204205206207

For example, if you want to move to the beginning of the second line, send the control character 0xFE and command character 0d192.

Here’s a slightly more complex example showing how to display data at fixed points on the display, plus the use of sprintf() to convert numbers to strings (this right-justifies the numbers with leading spaces, which keeps them from “jumping around” if the number of digits changes):

language:c
// SparkFun Serial LCD example 2
// Format and display fake RPM and temperature data

// This sketch is for Arduino versions 1.0 and later
// If you're using an Arduino version older than 1.0, use
// the other example code available on the tutorial page.

// Use the Software Serial library to create a new "soft" serial port
// for the display. This prevents display corruption when uploading code.
#include <SoftwareSerial.h>

// Attach the serial enabld LCD's RX line to digital pin 11
SoftwareSerial LCD(10, 11); // Arduino SS_RX = pin 10 (unused), Arduino SS_TX = pin 11

void setup()
{ 
  LCD.begin(9600); // set up serial port for 9600 baud
  delay(500); // wait for display to boot up

  // cursor to beginning of first line
  LCD.write(254); 
  LCD.write(128);

  // clear display + legends
  LCD.write("RPM:            "); 
  LCD.write("TEMP:           ");
} 

int temp, rpm;
char tempstring[10], rpmstring[10]; // create string arrays

void loop() 
{ 
  temp = random(1000); // make some fake data
  rpm = random(10000);

  sprintf(tempstring,"%4d",rpm); // create strings from the numbers
  sprintf(rpmstring,"%4d",temp); // right-justify to 4 spaces

  LCD.write(254); // cursor to 7th position on first line
  LCD.write(134);

  LCD.write(rpmstring); // write out the RPM value

  LCD.write(254); // cursor to 7th position on second line
  LCD.write(198);

  LCD.write(tempstring); // write out the TEMP value

  delay(1000); // short delay
}

You should see something similar to the image below. Try reading a sensor and displaying the values on the screen!

Move Cursor RPM Temp

SerLCD Demo

This is an extensive example sketch that shows you how to create a scrolling marquee, create a timer, display sensor data, and control the backlight. Copy and paste the following example to the Arduino IDE. Upload the example to your Arduino to test!

language:c
/***********************************************************************
  SerLCD Demo Example Code
  Written by: Joel Bartlett @ SparkFun Electronics
  Date: December 20, 2012 
  Modified by: Ho Yun "Bobby" Chan @ SparkFun Electronics 
  Date: May 3, 2018

  This code uses the information presented in the SerLCD Datasheet 
  to create an Arduino example using the SerLCD from SparkFun Electonics. 
  Each of the SerLCD's capabilities is broken up into seperate functions
  within the sketch. Simply call each function with the correct parameters
  to get the desired result form the LCD screen. 

  This code was developed for the Arduino IDE v102

  To use, connect the following pins
      VDD -> 5V
      GND -> GND
      LCD RX -> Arduino TX (pin 11)

    ***Don't forget to disconnect the LCD's RX pin from the TX pin of 
the Arduino's UART line while programming!***

  You can also check out the SerLCD library from Arduino 
http://playground.arduino.cc/Code/SerLCD

  If you need to reprogram often, or need the UART for another device,
  you can use the Software Serial libary to create a 
  seperate UART for the LCD.
  Arduino IDE -> Sketch -> Import Library ->Software Serial

  To declare a new UART using SoftwareSerial, insert this line:
  SoftwareSerial NAME(x,y); // RX, TX
  where Name is the name of the new UART, x is the RX pin, and y is the TX     pin.

  "THE BEER-WARE LICENSE"
  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.
************************************************************************/
#include <SoftwareSerial.h>

SoftwareSerial LCD(10, 11); // Arduino SS_RX = pin 10 (unused), Arduino SS_TX = pin 11

//-------------------------------------------------------------------------------------------
void setup()
{
LCD.begin(9600);// all SerLCDs come at 9600 Baud by default
}
//-------------------------------------------------------------------------------------------
void loop()
{
  scrollingMarquee();
  tempAndHumidity();
  counter();
  backlight();
  cursors();
}
//-------------------------------------------------------------------------------------------
void clearScreen()
{
  //clears the screen, you will use this a lot!
  LCD.write(0xFE);
  LCD.write(0x01); 
}
//-------------------------------------------------------------------------------------------
void selectLineOne()
{ 
  //puts the cursor at line 0 char 0.
  LCD.write(0xFE); //command flag
  LCD.write(128); //position
}
//-------------------------------------------------------------------------------------------
void selectLineTwo()
{ 
  //puts the cursor at line 0 char 0.
  LCD.write(0xFE); //command flag
  LCD.write(192); //position
}
//-------------------------------------------------------------------------------------------
void moveCursorRightOne()
{
  //moves the cursor right one space
  LCD.write(0xFE); //command flag
  LCD.write(20); // 0x14
}
//-------------------------------------------------------------------------------------------
void moveCursorLeftOne()
{
  //moves the cursor left one space
  LCD.write(0xFE); //command flag
  LCD.write(16); // 0x10
}
//-------------------------------------------------------------------------------------------
void scrollRight()
{
  //same as moveCursorRightOne
  LCD.write(0xFE); //command flag
  LCD.write(20); // 0x14
}
//-------------------------------------------------------------------------------------------
void scrollLeft()
{
  //same as moveCursorLeftOne
  LCD.write(0xFE); //command flag
  LCD.write(24); // 0x18
}
//-------------------------------------------------------------------------------------------
void turnDisplayOff()
{
  //this tunrs the display off, but leaves the backlight on. 
  LCD.write(0xFE); //command flag
  LCD.write(8); // 0x08
}
//-------------------------------------------------------------------------------------------
void turnDisplayOn()
{
  //this turns the dispaly back ON
  LCD.write(0xFE); //command flag
  LCD.write(12); // 0x0C
}
//-------------------------------------------------------------------------------------------
void underlineCursorOn()
{
  //turns the underline cursor on
  LCD.write(0xFE); //command flag
  LCD.write(14); // 0x0E
}
//-------------------------------------------------------------------------------------------
void underlineCursorOff()
{
  //turns the underline cursor off
  LCD.write(0xFE); //command flag
  LCD.write(12); // 0x0C
}
//-------------------------------------------------------------------------------------------
void boxCursorOn()
{
  //this turns the box cursor on
  LCD.write(0xFE); //command flag
  LCD.write(13); // 0x0D
}
//-------------------------------------------------------------------------------------------
void boxCursorOff()
{
  //this turns the box cursor off
  LCD.write(0xFE); //command flag
  LCD.write(12); // 0x0C
}
//-------------------------------------------------------------------------------------------
void toggleSplash()
{
  //this toggles the splash screen
  //if off send this to turn on
  //if on send this to turn off
  LCD.write(0x7C); //command flag = 124 dec
  LCD.write(9); // 0x09
}
//-------------------------------------------------------------------------------------------
int backlight(int brightness)// 128 = OFF, 157 = Fully ON, everything in between = varied      
{
  //this function takes an int between 128-157 and turns the backlight on accordingly
  LCD.write(0x7C); //NOTE THE DIFFERENT COMMAND FLAG = 124 dec
  LCD.write(brightness); // any value between 128 and 157 or 0x80 and 0x9D
}
//-------------------------------------------------------------------------------------------
void scrollingMarquee()
{
//This function scroll text across the screen on both lines
  clearScreen(); // it's always good to clear the screen before moving onto a new print
  for(int j = 0; j < 17; j++)
  {
    selectLineOne();
    for(int i = 0; i < j;i++)
      moveCursorRightOne();
    LCD.print("SPARK");
    selectLineTwo();
    for(int i = 0; i < j;i++)
      moveCursorRightOne();
    LCD.print(" FUN");
    delay(500); // you must have a delay, otherwise the screen will print and clear before you can see the text
    clearScreen();
  }
}
//-------------------------------------------------------------------------------------------
void counter()
{
  //this function prints a simple counter that counts to 10
  clearScreen();
  for(int i = 0; i <= 10; i++)
  {
    LCD.print("Counter = ");
    LCD.print(i, DEC);
    delay(500);
        clearScreen();
  }
}
//-------------------------------------------------------------------------------------------
void tempAndHumidity()
{
  //this function shows how you could read the data from a temperature and humidity 
  //sensor and then print that data to the SerLCD.

  //these could be varaibles instead of static numbers 
  float tempF = 77.0; 
  float tempC = 25.0;
  float humidity = 67.0;

  clearScreen();
  selectLineOne();
  LCD.print(" Temp = ");
  LCD.print((long)tempF, DEC);
  LCD.print("F ");
  LCD.print((long)tempC, DEC);
  LCD.print("C");
  selectLineTwo();
  LCD.print(" Humidity = ");
  LCD.print((long)humidity, DEC); 
  LCD.print("%");
  delay(2500);
}
//-------------------------------------------------------------------------------------------
void backlight()
{
  //this function shows the different brightnesses to the backlight can be set 
      clearScreen();
  for(int i = 128; i < 158; i+=2)// 128-157 are the levels from off to full brightness
  {
    backlight(i);
    delay(100);
    LCD.print("Backlight = ");
    LCD.print(i, DEC);
    delay(500);
    clearScreen();
  }
}
//-------------------------------------------------------------------------------------------
void cursors()
{
  //this function shows the different cursors avaiable on the SerLCD
  clearScreen();

  boxCursorOn();
  LCD.print("Box On");
  delay(1500);
  clearScreen();

  boxCursorOff();
  LCD.print("Box Off");
  delay(1000);
  clearScreen();

  underlineCursorOn();
  LCD.print("Underline On");
  delay(1500);
  clearScreen();

  underlineCursorOff();
  LCD.print("Underline Off");
  delay(1000);
  clearScreen();
}

Alternative Libraries

Alternatively, you can use the SerLCD library found on the Arduino.cc website.

Arduino.cc - serLCD Library

If you are using Linux, you may want to try this library instead.

serLCD Library for Linux (ZIP)

Troubleshooting

Random Character

If the display is powered up without the RX line connected to anything, the display may fill with strange characters. This is because the display is receiving random noise on the disconnected line. If you connect the RX line to a true TX port, this will not happen.

Faded Characters on Display

If the display is unreadable or washed out, the contrast may need to be adjusted. Send some text to the display (see the first example sketch above), then use a miniature Phillips screwdriver to gently turn the contrast trimpot labeled VR1 on the back of the display until the text is as clear as possible (please be gentle with the trimpot). This display also has a backlight that can be adjusted for best readability, see the LCD datasheet for information.

Bricked LCD

If you are seeing two rows of ASCII blocks (i.e. █ ) or random characters, it’s possible that you might have bricked the serial enabled LCD by putting it into an unknown state. This is a common problem if you are uploading code to the Arduino while another device is connected to the same hardware UART line (i.e. pin 0 and 1). Some systems like Arduino send bootloader information out the serial port when the system starts up. This will cause the LCD to output random characters usually on the screen or not even show anything on the screen. If this is a problem, make sure to use a software defined serial pin to create a TX pin that doesn’t get used during startup.

Bricked Serial Enabled LCD 20x4Bricked Serial Enabled LCD 16x2

Recovering from Unknown State: Software Reset

If the Serial LCD gets into an unknown state and you are not able to communicate with it anymore, just write 0x12 in the loop so that it is constantly sending the hex value to the screen when the LCD’s splash screen is active (or when the LCD is powered) to reset the unit back to 9600 baud as explained earlier. The screen will temporarily revert to 9600 baud until power is cycled. This is to allow you to regain control of the display if you set it to an unknown baud rate. Make sure to also change the baud rate in the EEPROM.

The old datasheet in section 3.4 indicates that you need to send a command character 0x7C in hexadecimal. If you look at the ASCII table for the non-printing control characters (CTRL-K through CTRL-P), there are hex values for the different baud rates that you would need to send to the LCD.

Non-Printing Control Characters Command Character Description
<control>K0x0B [ 0d11 ]Set to 2400 Baud
<control>L0x0C [ 0d12 ]Set 4800 Baud
<control>M0x0D [ 0d13 ]Set 9600 Baud (Default)
<control>N0x0E [ 0d14 ]Set 14400 Baud
<control>O0x0F [ 0d15 ]Set 19200 Baud
<control>P0x10 [ 0d16 ]Set 38400 Baud
<control>R0x12 [ 0d18 ]Reset to Default Baud While
LCD's Splash Screen is Still Active

All you have to do is create a new void function similar to the one below and call it when you are running the Arduino sketch file like this:

language:c
void changeBaud(){
  LCD.write(0x7C);// special command byte
  LCD.write(0x0D); //change current baud to 9600 baud
}

Here’s some code with Arduino to try and unbrick the PIC16F88 on the serial enabled LCDs. This sometimes works and there is a higher probability of recovering your LCD if you still are able to see the splash screen.

SerLCD Software Reset Example

Recovering from Unknown State: PICkit Programmer

The last resort is to use the PICkit 3 programmer and reupload the firmware on the LCD using MPLAB. If you are trying to recover a bricked serLCD backpack, you will need a few of the following materials listed below to connect to the programming header. The built-in serial enabled LCD will have standard 0.1" spaced headers so the IC hooks will not be necessary as long as there is contact with the pins during programming.

Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

PRT-11026
$1.95
20
Break Away Headers - 40-pin Male (Long Centered, PTH, 0.1")

PRT-12693
$0.75
1
MPLAB PICkit 3

PGM-09973
$49.95
3

Using MPLAB X IDE v2.30

For this example, we will be using MPLAB X IDE V2.30 for Windows. Head over to MicroChip’s archived downloads to download and install.

MPLAB X IDE Download Archives

Also, make sure to download the hex file specific for your LCD to recover. We will be using the .hex file linked for the serial enabled LCD backpack below. If you are using the ones with the built-in serial, you will need to unzip the folder before using the file.

Download
serlcd-v2_6_2line_10MHz (HEX)
Download
serlcd-v2_7_2line_10MHz (ZIP)
Download
serlcd-v2_7_4line_10MHz (ZIP)

Once installed, select File > Import > Hex/ELF… (Prebuilt) File.

Import Hex/ELF

Click on the Browse… button and head to the location where the .hex file is stored on your computer. This will probably be in your recent downloads. Select the file and click on the Open button. This will automatically provide the path for the Prebuilt Filename which is …/serlcd-v2_6_2line_10MHz.hex.

Browse for hex file

Then type in the Device field: PIC16F88. If you have a PIC16LF88 that is populated on the SerLCD backpack, this is the same device that you would select. The programmer will not notice a difference between the two PICs. Once selected, click on the Next > button.

Select Device or Microcontroller

Click Finish to save as a project.

Save Project

Connect the PICkit 3 to your computer using the USB cable. At this point, make the connection from the PICkit 3 to the programming pins of the LCD. Power the target (your PIC16LF88) from a separate power supply like an Arduino using wires. The PICkit 3 may not have enough power to power the target.

If you are using a 3.3V LCD, make sure to read the note highlighted in red below.

The PICkit 3 programmer’s pinout is listed on page 15 of PICkit 3 user manual. To connect, start by connecting the LCD’s programming header indicated by the polarity marker and move toward the other side.

PICkit 3 Programmer Connector Pinout Notes
VPPIndicated by an Arrow, connect to pin "1" or a straight bar "¯"
VDD Target3.3V or 5V depending on your LCD
VSS (GND)Ground
PGDData
PGCClock
LVPNot Connected on SerLCD backpack

If you are using a 5V LCD, you can connect to the backpack with jumper wires (specifically wires with small pins) like the images shown below. When reflashing, the target voltage and GND pins were connected to the screw terminal. The PIC16LF88 can be reflashed as long as the pins are held in place during programming. Make sure the pins are not touching the LCD underneath.

Jumper Wires Between PICkit3 and SerLCD BackpackMake Sure the Pins are Not Touching the LCD Underneath

For those with the built-in serial enabled LCD programming pins, you could just connect using header pins by aligning the arrow to the pin “1”.

Tutorial-07 PICkit3 Programmer Reflash

Then click on the icon’s drop down menu that looks like the software is downloading to a PIC chip (i.e. the button next to the Run Project button) and select Make and Program Device Programmer to Go PICkit3 (Project serlcd-v2_6_2line_10MHz).

Program Button to Flash

A message will pop up if you did not select the correct programmer.

ICD 3 not found. The last tool used for this project is unavailable. Please select the tool that you want to use to debug or program from the following list of available tools.

Select PICkit 3 in the tree and click the OK button.

Select Correct Programmer

The software will pop up with this message:

If you followed the steps earlier to configure the PICkit 3 for a 3.3V LCD or are using a 5V LCD, click OK.

Caution

From there, the hex file should begin flashing on the chip and the program will run immediately after displaying this output:

language:c
*****************************************************

Connecting to MPLAB PICkit 3...
Firmware Suite Version.....01.28.90 *
Firmware type..............Midrange

Target voltage detected
Target device PIC16F88 found.
Device ID Revision = 8

The following memory area(s) will be programmed:
program memory: start address = 0x0, end address = 0x4ab
configuration memory

Device Erased...

Programming...
Programming/Verify complete 

You should see this output at the bottom of the MPLAB X IDE.

Programming Complete

Power cycle the screen. Congrats! We have recovered the LCD! Or, at least for a 16x2 character LCD… The firmware we flashed was set for the 16 characters and 2 lines. The next step is to configure the PIC for a 20x4 character LCD. To do this, we just need to send the control and command flags to adjust the width and lines. Place this your Arduino’s setup() function after setting your Arduino’s software serial port.

language:c
void set_20x4(){//set character LCD as 20x4
  LCD.write(0x7C); //command flag
  LCD.write(0x03);     //20 char wide
  LCD.write(0x7C); //command flag
  LCD.write(0x05);     //4 lines
  /*NOTE: Make sure to power cycle the serial enabled LCD 
  after re-configuring the # char and lines.*/
}

Power cycle the screen and run the demo example to see if everything is working as expected. Ok, now we have recovered your 20x4 serial enabled LCD!

More Examples of Setting Cursor Position

As stated earlier, to set the LCD’s cursor position, you would send the command character/flag. Then send additional number related to the cursor’s position on the LCD screen. This example goes over how to set the cursor position for a 20x4 serial enabled LCD. Just add 128 to the cursor’s position as stated on page 3 of the datasheet to place the cursor at the correct coordinates.

For example, if you are trying to place the cursor at (line 3, position 0), you would send the command character 0xFE and the associated coordinates. Looking at the datasheet, for the 20x4 serial enabled LCD screen, it looks like 128+20 = 148 . Therefore:

language:c
selectLineThree(){
    LCD.write(0xFE); //command flag
    LCD.write(148); //line 3 , position 0
}

As another example, if you are trying to place the cursor at (line 4, position 0), you would send the command character 0xFE and the associated coordinates. Looking at the datasheet, for the 20x4 serial enabled LCD screen, it looks like 128+84= 212. Therefore:

language:c
selectLineFour(){
    LCD.write(0xFE); //command flag
    LCD.write(212); //line 4 , position 0
}

Using the Serial Enabled LCD on an Atmega32U4’s Hardware UART

If you are using the serial enabled LCD with an Atmega32U4-based Arduino (like a Pro Micro, Arduino Leonardo, Arduino LilyPad USB etc), you might need to add a small delay in the setup before you can get it working with the hardware UART (pins 0 and 1). Here’s an example:

language:c
///test example using ATmega32U4's hardware UART and delay
void setup() {
  delay(2000);//add delay so the ATmega32U4 can have a second before sending serial data to the LCD
  Serial1.begin(9600);//set up the hardware UART baud
}

void loop() {
  Serial1.print("print something");//send something to the serial enabled LCD
  delay(50);
}

Software Serial for Arduino Due

Unfortunately, you are not able to use the serial enabled LCDs with an Arduino Due due the differences in how change interrupts are used for the ARM processor. The software serial library is not included in the Arduino Due’s tree:

Arduino.cc Forums - Software Serial for Arduino Due?

Try using the other hardware serial UARTs that are not connected to the Arduino Due’s programming pins for uploading. Make sure to adjust the code for the hardware serial UARt.

Changing Width and Character Lines

To adjust the default width and character lines, there is some code listed in this example based on the datasheet to configure the serial enabled LCD.

SerLCD Example Update Character Lines

Resources and Going Further

Now that you’ve successfully got your serial enabled LCD up and running, it’s time to incorporate it into your own project!

For more information, check out the resources below:

Need some inspiration for your next project? Check out some of these related tutorials:

OLED Display Hookup Guide

A simple hookup guide to get you started with the OLED LCD.

Graphic LCD Hookup Guide

How to add some flashy graphics to your project with a 84x48 monochrome graphic LCD.

PicoBuck Hookup Guide V12

The PicoBuck board is a high-efficiency three-channel constant-current LED driver.

SparkFun LED Array (8x7) Hookup Guide

Getting started with the Charlieplexed 8x7 LED array.

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

Qwiic Real Time Clock Module (RV-1805) Hookup Guide

$
0
0

Qwiic Real Time Clock Module (RV-1805) Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The Qwiic Real Time Clock (RTC) module is a Qwiic-enabled breakout board for the RV-1805 module! The RTC is ultra-low power (running at about 22 nA in its lowest power setting) so it can use a supercapacitor for backup power instead of a normal battery. This means infinite charge and discharge cycles without any degradation to the “battery” (in this case, a supercapacitor). The breakout board is also a part of SparkFun’s Qwiic system, so you won’t have to do any soldering to figure out what time it is.

SparkFun Real Time Clock Module - RV-1805 (Qwiic)

BOB-14558
$14.95

In this hookup guide, we’ll take advantage of the Arduino IDE to automatically set the time of the RTC to the compiler time. Once we have the time set, we’ll set the alarm to a time of our choice and have it generate a signal on the interrupt pin. We’ll also look at how charged the RTC is so we know when to unplug the RTC from power (when it’s full of course). Finally, we’ll look at how to store other data into the RTC so we can keep important variables safe when our system loses power. We’ll also go over how to extend the battery life of your RTC by adding an external battery.

Required Materials

To get started, you’ll need a microcontroller to control everything in your project.

SparkFun RedBoard - Programmed with Arduino

DEV-13975
$19.95
29
SparkFun ESP32 Thing

DEV-13907
$19.95
52
Raspberry Pi 3

DEV-13825
$39.95
90
Particle Photon (Headers)

WRL-13774
$19.00
28

Now to get your microcontroller into the Qwiic ecosystem, the key will be one of the following Qwiic shields to match your preference of microcontroller:

SparkFun Qwiic Shield for Arduino

DEV-14352
$5.95
SparkFun Qwiic HAT for Raspberry Pi

DEV-14459
$4.95
1
SparkFun Qwiic Shield for Photon

DEV-14477
$4.95

You will also need a Qwiic cable to connect the shield to your RTC, choose a length that suits your needs.

Qwiic Cable - 200mm

PRT-14428
$1.50
Qwiic Cable - 500mm

PRT-14429
$1.95
Qwiic Cable - 100mm

PRT-14427
$1.50
Qwiic Cable - 50mm

PRT-14426
$0.95

Finally, if your application requires that your RTC be without power for over a month, we’d recommend using the optional battery and battery holder to extend the time that the RTC will remain active without power.

Coin Cell Battery - 12mm (CR1225)

PRT-00337
$1.95
2
Coin Cell Battery Holder - 12mm (PTH)

PRT-07948
$1.50

Suggested Reading

If you aren’t familiar with our new Qwiic system, we recommend reading here for an overview. We would also recommend taking a look at the hookup guide for the Qwiic Shield if you haven’t already. Brushing up on your skills in I2C is also recommended, as all Qwiic sensors are I2C.

How to Solder: Through-Hole Soldering

This tutorial covers everything you need to know about through-hole soldering.

I2C

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

Qwiic Shield for Arduino & Photon Hookup Guide

Get started with our Qwiic ecosystem with the Qwiic shield for Arduino or Photon.

Hardware Overview

Let’s look over a few characteristics of the RV-1805 RTC so we know a bit more about how it behaves.

CharacteristicRange
Operating Voltage (Startup)1.6V - 3.6V
Operating Voltage (Timekeeping)1.5V - 3.6V
Operating Temperature-40&degC - 85&degC
Time Accuracy&plusmn2.0 ppm
Current Consumption22 nA (Typ.)
I2C Address0xD2

Pins

The characteristics of the available pins on the RTC are outlined in the table below.

Pin LabelPin FunctionInput/OutputNotes
3.3VPower SupplyInputShould be between 1.95 - 3.6V
GNDGroundInput0V/common voltage.
SDAI2C Data SignalBi-directionalBi-directional data line. Voltage should not exceed power supply (e.g. 3.3V).
SCLI2C Clock SignalInputMaster-controlled clock signal. Voltage should not exceed power supply (e.g. 3.3V).
PSWPower SwitchOutputPower Switch pin, digital output. Capable of switching power on an external microcontroller.
INTInterruptOutputInterrupt pin, active low, digital output. Also configurable as a square wave up to 32.768 kHz
RSTResetOutputReset pin, active low, digital output

Optional Features

The Qwiic RTC has onboard I2C pull-up resistors, which can be removed by removing the solder from the jumper highlighted below. Only remove this solder if you are using your own pull-ups on the I2C lines.

I2C Pullup

There is also the option to add a battery to the board if the supercapacitor just isn’t gonna keep your project powered long enough (keep in mind, the supercap can hypothetically make the board keep time for around 35 days) you can solder on an external battery. Keep in mind that if doing so, you’ll need to cut the trace connecting power to the capacitor, and add solder to the side of the jumper that connects power to the battery labeled as BAT.

Power Jumper

Hardware Assembly

If you haven’t yet assembled your Qwiic Shield, now would be the time to head on over to that tutorial.

With the shield assembled, Sparkfun’s new Qwiic environment means that connecting the sensor could not be easier. Just plug one end of the Qwiic cable into the RTC breakout, the other into the Qwiic Shield of your choice. You’ll be ready to upload a sketch and start keeping track of the time. It seems like it’s too easy too use, but that’s why we made it that way!

RTC Plugged In

External Coin Cell Battery

Now if you’ve decided that you’d like to power the RTC from a battery instead of a supercapacitor, you’ll need to cut the trace jumper on the back of the board to disconnect power from the supercapacitor. Add solder to the other side of the jumper to connect power to the battery. Once you’ve done this, add a little bit of solder on the circular pad for contact, solder the battery holder legs to the board, insert the battery, and you’re good to go!

Battery

Library Overview

Note: This example assumes you are using the latest version of the Arduino IDE on your desktop. If this is your first time using Arduino, please review our tutorial on installing the Arduino IDE. If you have not previously installed an Arduino library, please check out our installation guide.

Before we get into programming our RTC, let’s download and check out the available functions in our library. SparkFun has written a library to control the Qwiic RTC. You can obtain these libraries through the Arduino Library Manager. Search for SparkFun Qwiic RTC RV1805 Arduino Library to install the latest version. If you prefer downloading the libraries from the GitHub repository and manually installing it, you can grab them here:

Download the SparkFun Qwiic RTC RV1805 Library (ZIP)

Let’s get started by looking at the functions that set up the RTC.

Setup and Settings

  • boolean begin( TwoWire &wirePort = Wire );— The begin function initalizes the RTC, enabling the trickle charging circuit along with low power mode. Also sets the RTC to a 12-hour time format.
  • void reset(void);— Performs a full software reset on the RTC.
  • bool setToCompilerTime();— Set’s the RTC to the time on the compiler.
  • bool setTime(uint8_t hund, uint8_t sec, uint8_t min, uint8_t hour, uint8_t date, uint8_t month, uint8_t year, uint8_t day);— Set’s the time registers of the RTC to a chosen time using individual variables.
  • bool setTime(uint8_t * time, uint8_t len)— Set’s the time registers of the RTC to a chosen time using an array of times in the following order {Hundredths, Seconds, Minutes, Hours, Date, Month, Year, Day}. Please note uint8_t len must be 7, the length of the time array, for this function to set the time properly.
  • bool setHundredths(uint8_t value);— Sets the hundredths register to value.
  • bool setSeconds(uint8_t value);— Sets the seconds register to value.
  • bool setMinutes(uint8_t value);— Sets the minutes register to value.
  • bool setHours(uint8_t value);— Sets the hours register to value.
  • bool setWeekday(uint8_t value);— Sets the weekday register to value.
  • bool setDate(uint8_t value);— Sets the date register to value.
  • bool setMonth(uint8_t value);— Sets the month register to value.
  • bool setYear(uint8_t value);— Sets the year register to value.
  • void set12Hour();— Sets the RTC to 12 hour mode.
  • void set24Hour();— Sets the RTC to 24 hour mode.
  • void enableTrickleCharge(uint8_t diode = DIODE_0_3V, uint8_t rOut = ROUT_3K);— Connects an internal diode and resistor to enable the trickle charging circuit to charge the supercapacitor. The default values are the fastest for charging the capacitor, although other globally scoped variables (listed below) can be passed to change the value of the diode and resistor using in the charging circuit.
    • DIODE_0_3V— 0.3V Diode
    • DIODE_0_6V— 0.6V Diode
    • DIODE_DISABLE— Disconnects diode, disables trickle charging circuit
    • ROUT_3K— 3 kΩ Resistor
    • ROUT_6K— 6 kΩ Resistor
    • ROUT_11K— 11 kΩ Resistor
    • ROUT_DISABLE— Disconnects resistor, disables the trickle charging circuit.
  • void disableTrickleCharge();— Disables the trickle charging circuit.
  • void enableLowPower();— Enables switching to the low power RC oscillator when the RTC is powered by the supercapacitor or battery.

Interrupt Functionality

  • void enableInterrupt(uint8_t source);— Enables a given interrupt based on the value of source, which can be any of the following.
    • INTERRUPT_EIE— External Interrupt
    • INTERRUPT_AIE— Alarm Interrupt
    • INTERRUPT_TIE— Timer Interrupt
    • INTERRUPT_BLIE— Battery Interrupt
  • void disableInterrupt(uint8_t source);— Disables a given interrupt based on the value of source, see above for possible values of source.
  • void clearInterrupts();— Clears all interrupt sources.
  • bool setAlarm(uint8_t sec, uint8_t min, uint8_t hour, uint8_t date, uint8_t month);— Sets the alarm to a chosen time using individual variables.
  • bool setAlarm(uint8_t * time, uint8_t len);— Sets the alarm to a chosen time using an array of times. uint8_t len must be 7, the length of the time array, for this function to set the alarm properly.
  • enableAlarmInterrupt();— Attaches the interrupt pin to the alarm function.
  • void setAlarmMode(uint8_t mode);mode must be between 0 and 7, alarm goes off with match of second, minute, hour, etc depending on the value of mode.
    • 0: Disabled
    • 1: Hundredths, seconds, minutes, hours, date and month match (once per year)
    • 2: Hundredths, seconds, minutes, hours and date match (once per month)
    • 3: Hundredths, seconds, minutes, hours and weekday match (once per week)
    • 4: Hundredths, seconds, minutes and hours match (once per day)
    • 5: Hundredths, seconds and minutes match (once per hour)
    • 6: Hundredths and seconds match (once per minute)
    • 7: Depends on the alarm value for hundredths.
      • 0-99: Hundredths match (once per second)
      • 240-249: Once per tenth (10 Hz)
      • 255: Once per hundredth (100 Hz)
  • void enableBatteryInterrupt(uint8_t voltage, bool edgeTrigger);— Enables the battery interrupt and sets the voltage at which the interrupt is triggered. The trigger voltages for different values of voltage and edgeTrigger are found in the table below.

    VoltageEdgeTrigger = trueEdgeTrigger = false
    03.0V2.5V
    12.5V2.1V
    22.2V1.8V
    31.6V1.4V
  • void setReferenceVoltage(uint8_t voltage, bool edgeTrigger);— Can be used to set the reference voltage used for the battery interrupt. Use the values in the above table.
  • bool checkBattery(uint8_t voltage, bool edgeTrigger);— Checks if the battery level is above the threshold set by the values voltage and edgeTrigger.

Reading the RTC

  • bool updateTime();— Updates the local time array with the RTC time registers.
  • stringDateUSA();— Returns the date in MM-DD-YYYY format.
  • stringDate();— Return date in DD-MM-YYYY format.
  • stringTime();— Return time in HH:MM:SS with AM/PM if the RTC is in 12 hour mode.
  • uint8_t getHundredths();— Returns the value of the hundredths register.
  • uint8_t getSeconds();— Returns the value of the seconds register.
  • uint8_t getMinutes();— Returns the value of the minutes register.
  • uint8_t getHours();— Returns the value of the hours register.
  • uint8_t getWeekday();— Returns the value of the weekday register.
  • uint8_t getDate();— Returns the value of the date register.
  • uint8_t getMonth();— Returns the value of the month register.
  • uint8_t getYear();— Returns the value of the year register.
  • bool is12Hour();— Returns true if 12hour bit is set.
  • bool isPM();— Returns true if is12Hour() == true and PM bit is set.
  • uint8_t status();— Returns the status byte.
  • uint8_t BCDtoDEC(uint8_t val);— Converts from BCD to decimal format.
  • uint8_t DECtoBCD(uint8_t val);— Converts from decimal to BCD format.
  • uint8_t readRegister(uint8_t addr);— Reads the register at addr.
  • bool writeRegister(uint8_t addr, uint8_t val);— Writes val to location addr.
  • bool readMultipleRegisters(uint8_t addr, uint8_t * dest, uint8_t len);— Reads len number of registers, incrementing up from the addr location, into the array dest.
  • bool writeMultipleRegisters(uint8_t addr, uint8_t * values, uint8_t len);— Writes len number of registers, incrementing up from the addr location, from the array values.

Example Code

Example 1 - Set Time

Once you’ve installed the SparkFun Qwiic RTC RV-1805 Arduino library go to File>Examples>SparkFun Qwiic RTC RV-1805 Arduino Library>Example1-Set_Time to open the example sketch. We will use this first sketch to set up our RTC’s internal clock. Take note of the following lines of code, which use the compiler time to set the RTC’s clock.

language:c
if (rtc.setToCompilerTime() == false) {
  Serial.println("Something went wrong setting the time");
}

Note that this doesn’t reset every time we upload code into our Arduino, so make sure you restart the IDE before uploading to get the most current time to upload into your RTC.

Example 2 - Print Time

Now that we’ve set the time on the RTC, let’s read it out. Open the next example by heading to File>Examples>SparkFun Qwiic RTC RV-1805 Arduino Library>Example2-Print_Time to open the example sketch. After initializing the RTC object, we attempt to update the time variables in our microcontroller with the values from the RTC using some of the code below. If this is successful, we print them out.

language:c
if (rtc.updateTime() == false) //Updates the time variables from RTC
  {
    Serial.print("RTC failed to update");
  }

Also, in its need to feel special, the United States formats its dates differently than the rest of the world (We do MM/DD/YYYY format while everybody else does DD/MM/YYYY format). So if you don’t live in the U.S. or you just like how the rest of the world formats their dates, you’ll need to uncomment the following line of code (line 50) in your sketch.

language:c
//String currentDate = rtc.stringDate());

Once you upload this code to your microcontroller, go ahead and open the serial monitor with a baud rate of 9600. You should see the current date and time go streaming past, looking something like the image below.

Print Time

If your output is showing the incorrect time, you may need to recompile your sketch to get the latest compiler time using the code from the first example. If this doesn’t work, try restarting the Arduino IDE to get a new compiler time.

Example 3 - Trickle Charging

To pull up the next example, go to File>Examples>SparkFun Qwiic RTC RV-1805 Arduino Library>Example3-Trickle_Charging. This example will show us how to fiddle with the RTC’s trickle charging circuit to configure it for different charge rates as well as disable it if we want to use a coin cell battery.

The trickle charge circuit consists of a diode (0.3v or 0.6v drop) in series with a resistor (3kOhm, 6kOhm, or 11kOhm) These are available to pass into the function as DIODE_0_3V, DIODE_0_6V, ROUT_3K, ROUT_6K, ROUT_11K. The fastest possible rate, with a 0.3V diode and 3kOhm resistor is enabled by default. Note that the trickle charger should only be used for charging the supercapacitor. Disable the trickle charger simply by calling disableTrickleCharge() if you’ve connected the optional battery.

Example 4 - Alarm Interrupt

To pull up the next example, go to File>Examples>SparkFun Qwiic RTC RV-1805 Arduino Library>Example4-Alarm_Interrupt. This example shows how to enable and use the alarm interrupt to generate an interrupt every time some or all of the alarm registers match the time register. First, we need to set up what time we want the alarm to go off. To do this, we set the variables in the preamble to the time we would like. They default to the values below as these are the default alarm values.

language:c
byte secondsAlarm = 0;
byte minuteAlarm = 0;
byte hourAlarm = 0;
byte dateAlarm = 0;
byte monthAlarm = 0;

Next, we need to set which parts of the time must match in order for the alarm to be triggered. to do this, we use the setAlarmMode(uint8_t mode); where mode is a number between 0 and 7. Go to line 60 (in the setup loop) if you’d like to change how often the alarm is triggered. The values corresponding to which registers much match are listed below.

  • 0: Disabled
  • 1: Hundredths, seconds, minutes, hours, date and month match (once per year)
  • 2: Hundredths, seconds, minutes, hours and date match (once per month)
  • 3: Hundredths, seconds, minutes, hours and weekday match (once per week)
  • 4: Hundredths, seconds, minutes and hours match (once per day)
  • 5: Hundredths, seconds and minutes match (once per hour)
  • 6: Hundredths and seconds match (once per minute)
  • 7: Depends on the alarm value for hundredths.
    • 0-99: Hundredths match (once per second)
    • 240-249: Once per tenth (10 Hz)
    • 255: Once per hundredth (100 Hz)

Once you’ve set the alarm to your liking, go ahead and upload the code to your microcontroller. The interrupt pin will now drop low every time the alarm is triggered. If you don’t want to physically check the status of the interrupt pin, you can uncomment the section of code in the void loop that reads the status register of the RTC. This will alert you when the alarm has been triggered.

Example 5 - Battery Interrupt

To pull up the next example, go to File>Examples>SparkFun Qwiic RTC RV-1805 Arduino Library>Example5-Battery_Interrupt to open the example sketch. This example checks the charge level of the supercapacitor and alerts the user when it has reached 2.5V. You can change the voltage level at which the user is alerted by changing the values passed into checkBattery(voltage, edgeTrigger);. Follow the chart on the Library Overview page to select the proper voltage. Once you’ve uploaded the example code to your microcontroller, go ahead and open the serial monitor to 9600 baud. The output should look something like the image below once the RTC is charged to the selected voltage.

Battery Checker

Resources and Going Further

Now that you’ve successfully got your Qwiic RTC (RV-1805) module up and running, it’s time to incorporate it into your own project!

For more information about the Qwiic RTC (RV-1805) module, check out the resources below:

Need some inspiration for your next project? Check out some of these related tutorials:

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.

Real Time Clock Module Hookup Guide

A quick introduction to the DS1307 RTC module and a hookup guide for the SparkFun Breakout.

DeadOn RTC Breakout Hookup Guide

An introduction to the DS3234 real-time clock (RTC), example wiring diagrams, and an Arduino library!

Or check out some of these blog posts for ideas:


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

Qwiic Differential I2C Bus Extender (PCA9615) Hookup Guide

$
0
0

Qwiic Differential I2C Bus Extender (PCA9615) Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The Qwiic Differential I2C Breakout is the fastest and easiest way to extend the range of your I2C communication bus. The breakout uses NXP’s PCA9615 IC, which converts the two default I2C signals into four differential signals: two for SCL and two for SDA. Coupled with the ease of SparkFun’s Qwiic connection system, the differential I2C breakout board makes it easier to connect it to the rest of your system. The differential signals are sent over an Ethernet cable, which attaches to the breakouts through the on-board RJ-45 connectors. The differential signaling allows the I2C signals to reach distances of up to 100ft. while still maintaining their signal integrity!

SparkFun Differential I2C Breakout - PCA9615 (Qwiic)

BOB-14589
$9.95

Whether you need to extend the range of an I2C sensor on an autonomous vehicle plagued with noise from motors or want to create a vast sensor network in your home or office, the Qwiic differential I2C breakout is a great solution to extend distance and reduce noise susceptibility.

Required Materials

To follow along with this project tutorial, you will need the following materials. You may not need everything though depending on what you have. Add it to your cart, read through the guide, and adjust the cart as necessary.

Tools

You may need a soldering iron, solder, general soldering accessories, and a hobby knife depending on your setup.

Solder Lead Free - 100-gram Spool

TOL-09325
$7.95
7
Weller WLC100 Soldering Station

TOL-14228
$44.95
Hobby Knife

TOL-09200
$2.95
2

Suggested Reading

If you aren’t familiar with our new Qwiic system, we recommend reading here for an overview. We would also recommend taking a look at the following tutorials if you aren’t familiar with them.

Logic Levels

Learn the difference between 3.3V and 5V devices and logic levels.

I2C

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

How to Work w/ Jumper Pads and PCB Traces

Handling PCB jumper pads and traces is an essential skill. In this tutorial, you will learn how to cut a PCB trace and add a solder jumper between pads to reroute connections. You will also learn how to repair a trace with the green wire method if a trace is damaged.

Qwiic Shield for Arduino & Photon Hookup Guide

Get started with our Qwiic ecosystem with the Qwiic shield for Arduino or Photon.

Qwiic HAT for Raspberry Pi Hookup Guide

Get started interfacing your Qwiic enabled boards with your Raspberry Pi. This Qwiic connects the I2C bus (GND, 3.3V, SDA, and SCL) on your Raspberry Pi to an array of Qwiic connectors.

Hardware Overview

The simplicity of the Qwiic differential I2C breakout is one of its biggest appeals. Other I2C communication methods require packetizing I2C communication into another protocol, be it RS-485 or 1-Wire. However, the PCA9615 keeps the I2C protocol by utilizing a differential transceiver. In this section, we’ll take a closer look at the board to better understand how it works.

Pinout

Below are the plated through hole pins that are broken out on the board. The I2C pins are connected to the two Qwiic connectors on the sides.

Highlight of PTH Pins

PTH Connections

  • GND - Ground
  • VDDA - 2.3VDC to 5.5VDC. I2C-bus side power supply.
  • VDDB - 3.0VDC to 5.5VDC. Differential side power supply. If jumper “VDD A-B” is not shorted, then VDDB will need to be powered for the differential I2C bus to operate.
  • SDA - I2C data signal.
  • SCL - I2C clock signal.
  • EN (optional) - PCA9615 enable (active high, internally pulled up). This is used to disable the bus buffer, and is useful for fault finding, power-up sequencing, or reconfiguration of a large bus system by isolating sections not needed at all times.

Qwiic Connections

  • GND - Ground.
  • VDDA - 2.3VDC to 5.5VDC. I2C-bus side power supply. If “VDD A-B” is not shorted, VDDB will need to powered separately for the differential I2C bus to operate.
  • SDA - I2C data signal.
  • SCL - I2C clock signal.

VDDA vs VDDB

To power the board, VDDA must be present and be the same logic voltage as the SDA/SCL lines, while VDDB is used to power the differential I2C bus. By default, the jumper labeled “VDD A-B” is closed, which connects the VDDA rail to the VDDB rail. By cutting the jumper you can separate the two rails which would allow for one rail to operate at 3.3V while the other can operate at 5V.

Highlight of VDDA,VDDB,VDD Jumper

VDDB and Ground Jumpers

If the number of sensors connected on the other side of the extended I2C bus is minimal, you can power them over the Ethernet cable. However, if there are numerous sensors connected, it is advised that both ends be powered separately. To isolate the power supplies at both ends of the Ethernet cable, use a sharp blade to cut the small traces betweens the pads of the jumpers labeled “VDDB” and “GND”. VDDB will still be present on each board, but the Ethernet cable will not carry any current to power a device at the other end of the cable.

Bottom Jumper Highlight

Differential Signals

From the bottom of the board, we can see which pins the RJ-45 connector uses for the differential signaling. The board has been designed to use a standard Ethernet cable. If a custom cable is made, make sure to connect a twisted pair for pins 1 and 2 (DSCL-, DSCL+) and pins 7 and 8 (DSDA-, DSDA+).

Highlight of RJ-45 Differential Signals

I2C Pull-Up Resistors

As with most SparkFun I2C products, there is a jumper for the pull-up resistors on the I2C bus. If multiple sensors are connected to the bus with the pull-up resistors enabled, the parallel equivalent resistance will create too strong of a pull-up for the bus to operate correctly. As a general rule of thumb, disable all but one pair of pull-up resistors if multiple devices are connected to the bus.

I2C Pull-Up Resistor Jumper Highlight

Hardware Assembly

Ethernet cables used must be straight-through (i.e. Pin 1 on one side of the cable is connect to pin 1 on the other side. The same for pin 2 and so on.).

Differential Boards Connected via I2C

I2C Pull-Up Resistors

Remember, each individual non-differential I2C bus needs at least on set of pull-up resistors enabled. Make sure you keep track of which devices have their I2C pull-ups enabled and which do not.

Power Schemes

With two power supply rails and quite a few jumpers, it’s easy to feel confused about how to power the differential I2C bus extender. In this section, we’ll go over the different ways you can power your project.

VDD_A == VDD, Power Whole Bus (Default)

Highlight of VDD Jumper

  • VDD_A and VDD_B are connected.
  • Both are powered at 3.3V.
  • Power is connected to a twisted pair of the Ethernet cable and sent to the slave nodes.
  • No power is required at the slave nodes.

VDD_A != VDD_B, Power Whole Bus

VDD Jumper Cut

 

  • VDD A-B jumper trace has been cut.
  • Separate power supply (3.0-5.5V) is supplied to VDD_B, while VDD_A remains at 3.3V.
  • VDD_B voltage is connected to a twisted pair of the Ethernet cable and sent to the slave nodes.
  • No power is required at the slave nodes.

VDD_A == VDD_ B, Power Each Node Separately

 

Bottom Jumpers Cut

 

  • VDD_A and VDD_B are connected.
  • Both are powered at 3.3V.
  • Jumpers underneath board (VDDB and GND) are cut and power is NOT connected to the Ethernet cable.
  • Each slave node is powered individually with 3.3V only. Differential I2C signals are the only connections on the bus.

VDD_A != VDD_ B, Power Each Node Separately

 

VDD_A != VDD_ B, Powering Each Node Separately by cutting VDD, VDDB, and GND

 

  • VDD A-B jumper trace has been cut on the top of the board.
  • Separate power supply (3.0-5.5V) is supplied to VDD_B, while VDD_A remains at 3.3V.
  • Jumpers underneath board (VDDB and GND) are cut and power is NOT connected to the Ethernet cable.
  • Each slave node is powered individually with 3.3V only. Differential I2C signals are the only connections on the bus.

VDD_A == VDD_ B, Power Whole Bus (Non-Qwiic Option)

Non-Qwiic Default

  • VDD_A and VDD_B are connected.
  • Both are powered at 5V.
  • Power is connected to a twisted pair of the Ethernet cable and sent to the slave nodes.
  • No power is required at the slave nodes.

VDD_A == VDD_ B, Power Each Node Separately (Non-Qwiic Option)

 

Bottom Jumpers Cut

 

  • VDD_A and VDD_B are connected.
  • Both are powered at 5V.
  • Jumpers underneath board (VDDB and GND) are cut and power is NOT connected to the Ethernet cable.
  • Each slave node is powered individually with 5V only. Differential I2C signals are the only connections on the bus.

I2C Bus Extender Example

For this example, we’re going to use our Environmental Combo Breakout using the Differential I2C Bus Extender. To follow along in this example, you’ll need the following:

You’ll also need a straight-through Ethernet cable (up to 100ft).

Hardware Hookup

You’ll first need to solder the headers on to the Qwiic shield and then connect the shield to the Redboard. Once that’s done, you can connect one of the differential I2C to your Redboard as shown below using one of the Qwiic cables.

Redboard Connected to Differential I2C using Qwiic

On the other end, all that’s needed is to connect the environmental combo sensor to the other differential I2C using another Qwiic cable as shown below.

Sensor Connected to Differential I2C using Qwiic

Arduino Library Installation

Note: This example assumes you are using the latest version of the Arduino IDE on your desktop. If this is your first time using Arduino, please review our tutorial on installing the Arduino IDE. If you have not previously installed an Arduino library, please check out our installation guide.

We’re going to use the code from the environmental combo sensor’s hookup guide.

CCS811/BME280 (Qwiic) Environmental Combo Breakout Hookup Guide

September 8, 2017

Sense various environmental conditions such as temperature, humidity, barometric pressure, eCO2 and tVOCs with the CCS811 and BME280 combo breakout board.

Since we are using the environmental combo sensor, the BME280 and CCS811 libraries need to be installed. SparkFun has written libraries to control both the CCS811 and the BME280. You can obtain these libraries through the Arduino Library Manager. Search for SparkFun BME280 and SparkFun CCS811 to install the latest version. If you prefer downloading the libraries, you can grab them here to manually install:

Download the SparkFun BME280 Library (ZIP)

Download the SparkFun CCS811 Library (ZIP)

Example Code

With the sensor connected via the I2C bus extender, we will use example 2 of the environmental combo breakout. Assuming that you have installed the library for both sensors, copy the code below and paste it into your Arduino IDE and upload the sketch to your board.

language:c
#include <SparkFunBME280.h>  //https://github.com/sparkfun/SparkFun_BME280_Arduino_Library/
#include <SparkFunCCS811.h>  //https://github.com/sparkfun/SparkFun_CCS811_Arduino_Library/

#define CCS811_ADDR 0x5B //Default I2C Address
//#define CCS811_ADDR 0x5A //Alternate I2C Address

//Global sensor objects
CCS811 myCCS811(CCS811_ADDR);
BME280 myBME280;

void printData()
{
  Serial.print(" CO2[");
  Serial.print(myCCS811.getCO2());
  Serial.print("]ppm");

  Serial.print(" TVOC[");
  Serial.print(myCCS811.getTVOC());
  Serial.print("]ppb");

  Serial.print(" temp[");
  Serial.print(myBME280.readTempC(), 1);
  Serial.print("]C");

  //Serial.print(" temp[");
  //Serial.print(myBME280.readTempF(), 1);
  //Serial.print("]F");

  Serial.print(" pressure[");
  Serial.print(myBME280.readFloatPressure(), 2);
  Serial.print("]Pa");

  //Serial.print(" pressure[");
  //Serial.print((myBME280.readFloatPressure() * 0.0002953), 2);
  //Serial.print("]InHg");

  //Serial.print("altitude[");
  //Serial.print(myBME280.readFloatAltitudeMeters(), 2);
  //Serial.print("]m");

  //Serial.print("altitude[");
  //Serial.print(myBME280.readFloatAltitudeFeet(), 2);
  //Serial.print("]ft");

  Serial.print(" humidity[");
  Serial.print(myBME280.readFloatHumidity(), 0);
  Serial.print("]%");

  Serial.println();
}

void printDriverError( CCS811Core::status errorCode )
{
  switch ( errorCode )
  {
    case CCS811Core::SENSOR_SUCCESS:
      Serial.print("SUCCESS");
      break;
    case CCS811Core::SENSOR_ID_ERROR:
      Serial.print("ID_ERROR");
      break;
    case CCS811Core::SENSOR_I2C_ERROR:
      Serial.print("I2C_ERROR");
      break;
    case CCS811Core::SENSOR_INTERNAL_ERROR:
      Serial.print("INTERNAL_ERROR");
      break;
    case CCS811Core::SENSOR_GENERIC_ERROR:
      Serial.print("GENERIC_ERROR");
      break;
    default:
      Serial.print("Unspecified error.");
  }
}

void setup()
{
  Serial.begin(9600);
  Serial.println();
  Serial.println("Apply BME280 data to CCS811 for compensation.");

  //This begins the CCS811 sensor and prints error status of .begin()
  CCS811Core::status returnCode = myCCS811.begin();
  if (returnCode != CCS811Core::SENSOR_SUCCESS)
  {
    Serial.println("Problem with CCS811");
    printDriverError(returnCode);
  }
  else
  {
    Serial.println("CCS811 online");
  }

  //Initialize BME280
  //For I2C, enable the following and disable the SPI section
  myBME280.settings.commInterface = I2C_MODE;
  myBME280.settings.I2CAddress = 0x77;
  myBME280.settings.runMode = 3; //Normal mode
  myBME280.settings.tStandby = 0;
  myBME280.settings.filter = 4;
  myBME280.settings.tempOverSample = 5;
  myBME280.settings.pressOverSample = 5;
  myBME280.settings.humidOverSample = 5;

  //Calling .begin() causes the settings to be loaded
  delay(10);  //Make sure sensor had enough time to turn on. BME280 requires 2ms to start up.
  byte id = myBME280.begin(); //Returns ID of 0x60 if successful
  if (id != 0x60)
  {
    Serial.println("Problem with BME280");
  }
  else
  {
    Serial.println("BME280 online");
  }
}

void loop()
{
  if (myCCS811.dataAvailable()) //Check to see if CCS811 has new data (it's the slowest sensor)
  {
    myCCS811.readAlgorithmResults(); //Read latest from CCS811 and update tVOC and CO2 variables
    //getWeather(); //Get latest humidity/pressure/temp data from BME280
    printData(); //Pretty print all the data
  }
  else if (myCCS811.checkForStatusError()) //Check to see if CCS811 has thrown an error
  {
    Serial.println(myCCS811.getErrorRegister()); //Prints whatever CSS811 error flags are detected
  }

  delay(2000); //Wait for next reading
}

Once uploaded, open your favorite serial monitor to the port assigned to the Arduino. You should see something like similar to the output below:

Serial Monitor Output Window

Resources and Going Further

Now that you’ve successfully got your differential I2C breakout up and running, it’s time to incorporate it into your own project!

For more on the differential I²C breakout, check out the links below:

For more information related to I²C over long distances, check out the resources below:

Need some inspiration for your next project? Check out some of these related tutorials:

Qwiic Adapter Hookup Guide

Get started with your Qwiic adapter board. This adapter breaks out the I2C pins from the Qwiic connectors to pins that you can easily solder with your favorite I2C enabled device.

Qwiic Accelerometer (MMA8452Q) Hookup Guide

Freescale’s MMA8452Q is a smart, low-power, three-axis, capacitive micro-machined accelerometer with 12-bits of resolution. It’s perfect for any project that needs to sense orientation or motion. We’ve taken that accelerometer and stuck it on a Qwiic-Enabled breakout board to make interfacing with the tiny, QFN package a bit easier.
New!

RedBoard Edge Hookup Guide

The RedBoard Edge is a RedBoard that's been rebuilt around the idea that projects are eventually put into an enclosure to help clean up their look.
New!

Qwiic Real Time Clock Module (RV-1805) Hookup Guide

Find out what time it is, even after the power's been out on your project for a while with the Qwiic Real Time Clock (RTC) module.

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

Flexible Grayscale OLED Hookup Guide

$
0
0

Flexible Grayscale OLED Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

We’ve been hearing about and seeing flexible screens at CES for years now, but now you can finally get one in your hands and bend a screen! You can’t fold it like paper but this flexible grayscale OLED from Wisechip can be bent to a 40mm radius without damage. The display is less than 0.5mm thick, less than 0.5 grams, and can display some impressive graphics with great contrast.

SparkFun Flexible Grayscale OLED Breakout - 1.81"

LCD-14606
$49.95

The OLED display is 1.81" long with 160x32 4-bit grayscale pixels. The interface is 3-wire SPI and each pixel requires 4 bits. This means you will need a processor capable of storing a local array of 80*32 = 2,560 bytes in order to truly flex (pun intended) the power of the grayscale display. Basic 8-bit Arduinos can communicate with the display and do things like text but graphics will be tricky.

Required Materials

To get started, you’ll need a microcontroller to control everything in your project.

SparkFun RedBoard - Programmed with Arduino

DEV-13975
$19.95
29
SparkFun ESP32 Thing

DEV-13907
$19.95
52
Raspberry Pi 3

DEV-13825
$39.95
90
Particle Photon (Headers)

WRL-13774
$19.00
28

Tools

You will need a soldering iron, solder, and general soldering accessories.

Solder Lead Free - 100-gram Spool

TOL-09325
$7.95
7
Weller WLC100 Soldering Station

TOL-14228
$44.95

Suggested Reading

If you aren’t familiar with the following concepts, we recommend checking out these tutorials before continuing.

How to Solder: Through-Hole Soldering

This tutorial covers everything you need to know about through-hole soldering.

Serial Peripheral Interface (SPI)

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

Logic Levels

Learn the difference between 3.3V and 5V devices and logic levels.

Hardware Overview

Let’s look over a few characteristics of the flexible OLED so we know a bit more about how it behaves.

CharacteristicRange
Operating Voltage3.5V - 5V
Operating Temperature-40&degC - 60&degC
Resolution160 x 32
Bend Radius40 mm
Pixel Density88 DPI
Grayscale Resolution4 bit

Pins

The characteristics of the available pins on the flexible OLED breakout are outlined in the table below.

Pin LabelPin FunctionNotes
CSChip SelectChip Select, active low, part of SPI interface. 3.3V or 5V logic
SCLKSerial ClockProvides the clock signal for the serial interface. 3.3V or 5V logic
SDINMaster OutputData output from master. All image data is sent on this line. 3.3V or 5V logic
RESResetResets the display, active low. 3.3V or 5V logic
GNDGround0V/common voltage.
VINPower SupplyShould be between 3.5V - 5V

Pinout of Flexible Grayscale OLED Breakout

Hardware Assembly

The flexible OLED is fairly simple to connect to your microcontroller. You can either solder headers to the OLED breakout or solder wires straight to the breakout pins. If you’ve not soldered headers to a board, make sure to check out our tutorial here on soldering.

Hookup Table

The onboard buffer means that you can hook the display straight up to 3.3V or 5V logic without the need for any logic conversion circuitry. Therefore, you can just connect the pins directly to the I/O on your microcontroller. Simply connect the pins to their assignments in the below table and we’ll be ready to go. These pins can be changed in software later if you need to use any of them to control other parts of your project.

Flexible Grayscale OLED Breakout Board PinArduino Pin
VINShould be between 3.5V - 5V
GND0V/common voltage
RESPin 8
SDINPin 11
SCLKPin 13
CSPin 10

Library Overview

Note: This example assumes you are using the latest version of the Arduino IDE on your desktop. If this is your first time using Arduino, please review our tutorial on installing the Arduino IDE. If you have not previously installed an Arduino library, please check out our installation guide.

First, you’ll need to download and install the Sparkfun Flexible Grayscale OLED Brekaout library. You can do this through the Arduino library manager or manually installing it by clicking the button below.

Download the SparkFun Flexible Grayscale Library

Before we get started developing a sketch, let’s look at the available functions of the library.

  • void command(uint8_t c);— Sends the display a command byte.
  • void data(uint8_t c);— Sends the display a data byte.
  • void setColumnAddress(uint8_t add);— Sets the column address.
  • void setPageAddress(uint8_t add);— Sets the page address.

LCD Drawing Functions

  • void clearDisplay(uint8_t mode):— Clears the screen buffer in the OLED’s memory, pass in mode = CLEAR_DISPLAY to clear the memory of the display, mode = CLEAR_BUFFER to clear the display buffer, or mode = CLEAR_ALL to clear both.
  • void display(void);— Moves display memory to the screen to draw the image in memory.
  • void setCursor(uint8_t x, uint8_t y);— Set cursor position to (x, y).
  • void invert(boolean inv);— Turns every black pixel white, turns all white pixels black.
  • void setContrast(uint8_t contrast);— Changes the contrast value anywhere between 0 and 255.
  • void flipVertical(boolean flip);— Does a vertical mirror of the screen.
  • void flipHorizontal(boolean flip);— Does a horiontal mirror of the screen.

  • void setPixel(uint8_t x, uint8_t y);— Draw a pixel using the current fore color and current draw mode in the screen buffer’s x,y position.

  • void setPixel(uint8_t x, uint8_t y, uint8_t color, uint8_t mode);— Draw a pixel with NORM or XOR draw mode in the screen buffer’s x,y position.

  • void line(uint8_t x0, uint8_t y0, uint8_t x1, uint8_t y1);— Draw line using current fore color and current draw mode from x0,y0 to x1,y1 of the screen buffer.

  • void line(uint8_t x0, uint8_t y0, uint8_t x1, uint8_t y1, uint8_t color, uint8_t mode);— Draw line using color and mode from x0,y0 to x1,y1 of the screen buffer.
  • void lineH(uint8_t x, uint8_t y, uint8_t width);— Draw horizontal line using current fore color and current draw mode from x,y to x+width,y of the screen buffer.
  • void lineH(uint8_t x, uint8_t y, uint8_t width, uint8_t color, uint8_t mode);— Draw horizontal line using color and mode from x,y to x+width,y of the screen buffer.
  • void lineV(uint8_t x, uint8_t y, uint8_t height);— Draw vertical line using current fore color and current draw mode from x,y to x,y+height of the screen buffer.
  • void lineV(uint8_t x, uint8_t y, uint8_t height, uint8_t color, uint8_t mode);— Draw vertical line using color and mode from x,y to x,y+height of the screen buffer.

  • void rect(uint8_t x, uint8_t y, uint8_t width, uint8_t height);— Draw rectangle using current fore color and current draw mode from x,y to x+width,y+height of the screen buffer.

  • void rect(uint8_t x, uint8_t y, uint8_t width, uint8_t height, uint8_t color , uint8_t mode);—Draw rectangle using color and mode from x,y to x+width,y+height of the screen buffer.
  • void rectFill(uint8_t x, uint8_t y, uint8_t width, uint8_t height);— Draw filled rectangle using current fore color and current draw mode from x,y to x+width,y+height of the screen buffer.
  • void rectFill(uint8_t x, uint8_t y, uint8_t width, uint8_t height, uint8_t color , uint8_t mode);— Draw filled rectangle using color and mode from x,y to x+width,y+height of the screen buffer.

  • void circle(uint8_t x, uint8_t y, uint8_t radius);— Draw circle with radius using current fore color and current draw mode with center at x,y of the screen buffer.

  • void circle(uint8_t x, uint8_t y, uint8_t radius, uint8_t color, uint8_t mode);— Draw circle with radius using color and mode with center at x,y of the screen buffer.
  • void circleFill(uint8_t x0, uint8_t y0, uint8_t radius);— Draw filled circle with radius using current fore color and current draw mode with center at x,y of the screen buffer.
  • void circleFill(uint8_t x0, uint8_t y0, uint8_t radius, uint8_t color, uint8_t mode);— Draw filled circle with radius using color and mode with center at x,y of the screen buffer.

  • void drawChar(uint8_t x, uint8_t y, uint8_t c);— Draws a character at position (x, y).

  • void drawChar(uint8_t x, uint8_t y, uint8_t c, uint8_t color, uint8_t mode);— Draws a character using a color and mode at position (x, y)

  • void drawBitmap(uint8_t * bitArray);— Draws a preloaded bitmap.

  • uint16_t getDisplayWidth(void);— Gets the width of the OLED.
  • uint16_t getDisplayHeight(void);— Gets the height of the OLED.
  • void setDisplayWidth(uint16_t);— Sets the width of the OLED.
  • void setDisplayHeight(uint16_t);— Sets the height of the OLED.
  • void setColor(uint8_t color);— Sets the color of the OLED
  • void setDrawMode(uint8_t mode);— Sets the drawing mode of the OLED
  • uint8_t *getScreenBuffer(void);

Font Settings

  • uint8_t getFontWidth(void);— Gets the current font width as a byte.
  • uint8_t getFontHeight(void);— Gets the current font height as a byte.
  • uint8_t getTotalFonts(void);— Return the total number of fonts loaded into the MicroOLED’s flash memory.
  • uint8_t getFontType(void);— Returns the font type number of the current font (Font types shown below).
  • boolean setFontType(uint8_t type);— Sets the font type (Font types shown below).

    Font TypeMaximum ColumnsMaximum RowsDescription
    0106Smallest, 5x7-pixel characters.
    163Medium, 8x16-pixel characters.
    2537-segment display style characters, 10x16-pixels each.
    351Large, 12x48 (the entire screen height) characters.
  • uint8_t getFontStartChar(void);— Returns the starting ASCII character of the current font.

  • uint8_t getFontTotalChar(void);— Return the total characters of the current font.

Rotation and Scrolling

The following functions will scroll the screen in the various specified directions of each function. Start and stop indicate the range of rows/columns that will be scrolling.

  • void scrollRight(uint8_t start, uint8_t stop);
  • void scrollLeft(uint8_t start, uint8_t stop);
  • void scrollUp(uint8_t start, uint8_t stop);
  • void scrollStop(void);

Example Code

Now that we have our library installed, we can get started playing around with our examples to learn more about how the screen behaves.

Example 1 - Text

To get started, open up Example1_Text under File>Examples>SparkFun Flexible Grayscale OLED Breakout>Example1_Text. Upon opening this example, you’ll notice that our void loop() is empty. This is because we only need to draw the image to our OLED one time in order for it to stay there. We first initialize our screen with CS connected to pin 10 and RES connected to pin 9, with the line SSD1320 flexibleOLED(10, 9);. Then in our setup loop we use flexibleOLED.begin(160, 32); to begin a display that is 160x32 pixels. We then use the following lines to first clear the display, set the font, the location where we’d like to type, and the text we’d like to type. The final line tells the display to show what we’ve just written to the display buffer.

language:c
flexibleOLED.clearDisplay(); //Clear display and buffer

flexibleOLED.setFontType(1); //Large font
flexibleOLED.setCursor(28, 12);
flexibleOLED.print("Hello World!");

flexibleOLED.setFontType(0); //Small font
flexibleOLED.setCursor(52, 0);
flexibleOLED.print("8:45:03 AM");

flexibleOLED.display();

This will write the text to the display when our microcontroller runs the setup loop and leave it there, the output should look something like the below image.

Hello World

Example 2 - Graphics

To get started, open up Example2_Graphics under File>Examples>SparkFun Flexible Grayscale OLED Breakout>Example2_Graphics. This example will draw a grayscale image from pre-converted image data, in this case, an image of a macaque. In order to convert your own images to a format readable by the OLED, check out this neat Python script for converting Bitmaps to arrays for the grayscale OLED. First you’ll need a *.bmp file that is 160 pixels wide and 32 pixels tall. Once you have your *.bmp, generating an image array is as simple as running the python script from the command line like below. (Make sure you put in the proper file paths)

language:bash
python <path to bmptoarray.py> <pathway to image.bmp>

The output will be placed in the output.txt file in the same directory as bmptoarray.py, and will look something like the below image.

PROGMEM Text

This large array must then be copied into a *.h file in the same folder as your sketch. Go ahead and name it something memorable, my sketch folder looks like this, with my array sitting in the TestImage.h file

Sketch Folder

Then, in our sketch, we’ll need to make sure we include the file containing this array, so make sure to put an #include "TestImage.h" at the top of your sketch. Also make sure you comment out any other image files that may be included. If you haven’t gone ahead and replaced the macaque with your own image, the output should look like the below image, otherwise, it should obviously look like whatever image you’ve chosen to display on your OLED.

Macaque

Example 3 - Lines

To get started, open up Example3_Lines under File>Examples>SparkFun Flexible Grayscale OLED Breakout>Example3_Lines. This example draws a few shapes on the display. Once again, it simply writes the image to the display and leaves it there. Play around with the parameters that draw each rectangle and circle to determine how this affects their positioning and size. The stock example code should look something like the below image.

Rectangles/Circles

Example 4 - BMP Eater

In this example, we’ll feed bitmaps directly into the screen using a serial terminal like Tera Term. If you’re not too familiar with using a terminal, check out our overview of serial terminal basics and download Tera Term. This is useful because we don’t have to convert our bitmaps into a prog_mem or anything. To get started we’ll first have to make sure our microcontroller can properly parse the serial input into pixel data. Go ahead and open up Example4_BMP_Eater under File>Examples>SparkFun Flexible Grayscale OLED Breakout>Example4_BMP_Eater. Once you have this open and uploaded, check out the getBitmap() function, which checks the structure of what we’re sending over serial and then writes it to the screen. Now that our microcontroller is ready for data, it’s time to open up Tera Term and start sending data. A new instance of Tera Term should prompt you to enter the COM port. Be sure to enter the port that your microcontroller is on.

COM Port

Once we’ve done this, we’ll need to change the baud rate of our terminal to match the microcontroller’s baud of 57600. Do this by going to Setup>Serial Port… and select 57600 from the drop-down menu. Now that we’ve opened a connection to the OLED we can start sending images to it. To do this, all we need to do is go to File>Send File… and select the bitmap we want to send to our screen. Go to Documents>Arduino>Libraries>SparkFun_Flexible_Grayscale_OLED_Breakout>Examples>Example4_BMP_Eater. This folder should contain a few bitmaps. If you got fancy and created your own bitmap in the second example, you can load that up as well. Select your file, make sure you’re sending it in a binary format (the image below shows the binary box checked).

Binary Checkbox

Uploading the image should show the display refresh line by line as it gets new data to chew on. The process looks something like the below GIF.

BMP Eater

Example 5 - All The Text

To get started, open up Example5_AllTheText under File>Examples>SparkFun Flexible Grayscale OLED Breakout>Example5_AllTheText. This example displays all of the text capabilities of the OLED. Take a look at the text example functions below to see how each one writes the corresponding text.

language:c
void smallTextExample()
{
  printTitle("Small text", 0);

  flexibleOLED.setFontType(0); //Small text

  byte thisFontHeight = flexibleOLED.getFontHeight();

  flexibleOLED.clearDisplay(); //Clear display RAM and local display buffer
  flexibleOLED.setCursor(0, thisFontHeight * 3);
  flexibleOLED.print("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
  flexibleOLED.setCursor(0, thisFontHeight * 2);
  flexibleOLED.print("abcdefghijklmnopqrstuvwxyz");
  flexibleOLED.setCursor(0, thisFontHeight * 1);
  flexibleOLED.print("1234567890!@#$%^&*(),.<>/?");
  flexibleOLED.setCursor(0, thisFontHeight * 0);
  flexibleOLED.print(";:'\"[]{}-=_+|\\~`");

  flexibleOLED.display();

  delay(2000);
}

Changing the type of text is simply a matter of using the setFontType() and changing the font used by the screen. Also notice how we must use different cursor positions for our lines of text to prevent them from overlapping each other.

language:c
void largeTextExample()
{
  printTitle("Large text", 0);

  flexibleOLED.setFontType(1); //Larger text
  byte theDisplayHeight = flexibleOLED.getDisplayHeight();
  byte thisFontHeight = flexibleOLED.getFontHeight();

  flexibleOLED.clearDisplay(); //Clear display RAM and local display buffer

  flexibleOLED.setCursor(0, theDisplayHeight - (thisFontHeight * 1));
  flexibleOLED.print("ABCDEFGHIJKLMNOPQ");
  flexibleOLED.setCursor(0, theDisplayHeight - (thisFontHeight * 2));
  flexibleOLED.print("abcdefghij1234567");

  flexibleOLED.display();

  delay(2000);
}

Uploading this example should yield an output on your screen similar to the one shown in the image below.

All Text

Example 6 - Pong

This next example will play us a nice little game of fake pong. To get started, open up Example6_Pong under File>Examples>SparkFun Flexible Grayscale OLED Breakout>Example6_Pong. The meat and potatoes of this pong example is contained in the shapeExample() function, shown below.

language:c
void shapeExample()
{
  printTitle("Shapes!", 0);

  // Silly pong demo. It takes a lot of work to fake pong...
  int paddleW = 3;  // Paddle width
  int paddleH = 15;  // Paddle height
  // Paddle 0 (left) position coordinates
  int paddle0_Y = (flexibleOLED.getDisplayHeight() / 2) - (paddleH / 2);
  int paddle0_X = 2;
  // Paddle 1 (right) position coordinates
  int paddle1_Y = (flexibleOLED.getDisplayHeight() / 2) - (paddleH / 2);
  int paddle1_X = flexibleOLED.getDisplayWidth() - 3 - paddleW;
  int ball_rad = 2;  // Ball radius
  // Ball position coordinates
  int ball_X = paddle0_X + paddleW + ball_rad;
  int ball_Y = random(1 + ball_rad, flexibleOLED.getDisplayHeight() - ball_rad);//paddle0_Y + ball_rad;
  int ballVelocityX = 1;  // Ball left/right velocity
  int ballVelocityY = 1;  // Ball up/down velocity
  int paddle0Velocity = -1;  // Paddle 0 velocity
  int paddle1Velocity = 1;  // Paddle 1 velocity

  //while(ball_X >= paddle0_X + paddleW - 1)
  while ((ball_X - ball_rad > 1) &&
         (ball_X + ball_rad < flexibleOLED.getDisplayWidth() - 2))
  {
    // Increment ball's position
    ball_X += ballVelocityX;
    ball_Y += ballVelocityY;
    // Check if the ball is colliding with the left paddle
    if (ball_X - ball_rad < paddle0_X + paddleW)
    {
      // Check if ball is within paddle's height
      if ((ball_Y > paddle0_Y) && (ball_Y < paddle0_Y + paddleH))
      {
        ball_X++;  // Move ball over one to the right
        ballVelocityX = -ballVelocityX; // Change velocity
      }
    }
    // Check if the ball hit the right paddle
    if (ball_X + ball_rad > paddle1_X)
    {
      // Check if ball is within paddle's height
      if ((ball_Y > paddle1_Y) && (ball_Y < paddle1_Y + paddleH))
      {
        ball_X--;  // Move ball over one to the left
        ballVelocityX = -ballVelocityX; // change velocity
      }
    }
    // Check if the ball hit the top or bottom
    if ((ball_Y <= ball_rad) || (ball_Y >= (flexibleOLED.getDisplayHeight() - ball_rad - 1)))
    {
      // Change up/down velocity direction
      ballVelocityY = -ballVelocityY;
    }
    // Move the paddles up and down
    paddle0_Y += paddle0Velocity;
    paddle1_Y += paddle1Velocity;
    // Change paddle 0's direction if it hit top/bottom
    if ((paddle0_Y <= 1) || (paddle0_Y > flexibleOLED.getDisplayHeight() - 2 - paddleH))
    {
      paddle0Velocity = -paddle0Velocity;
    }
    // Change paddle 1's direction if it hit top/bottom
    if ((paddle1_Y <= 1) || (paddle1_Y > flexibleOLED.getDisplayHeight() - 2 - paddleH))
    {
      paddle1Velocity = -paddle1Velocity;
    }

    // Draw the Pong Field
    flexibleOLED.clearDisplay(CLEAR_BUFFER); //Save time. Only clear the local buffer.
    // Draw an outline of the screen:
    flexibleOLED.rect(0, 0, flexibleOLED.getDisplayWidth() - 1, flexibleOLED.getDisplayHeight());
    // Draw the center line
    flexibleOLED.rectFill(flexibleOLED.getDisplayWidth() / 2 - 1, 0, 2, flexibleOLED.getDisplayHeight());
    // Draw the Paddles:
    flexibleOLED.rectFill(paddle0_X, paddle0_Y, paddleW, paddleH);
    flexibleOLED.rectFill(paddle1_X, paddle1_Y, paddleW, paddleH);
    // Draw the ball:
    flexibleOLED.circle(ball_X, ball_Y, ball_rad);
    // Actually draw everything on the screen:
    flexibleOLED.display();

    //delay(25);  // Delay for visibility
  }

  delay(1000);
}

Most of this function is simply math to move the paddles and ball around the screen and check for collisions. The actual drawing of the objects is executed in the last few lines of the function, right before the flexibleOLED.display(): function. The shapeExample() function is called repeatedly in our void loop() to progress the positions of the Pong pieces. The OLED should look something like the below GIF with this code uploaded.

Pong

Example 7 - Logo

To get started, open up Example7_Logo under File>Examples>SparkFun Flexible Grayscale OLED Breakout>Example7_Logo. This example simply shows us how to display what was already in the OLED’s buffer. All we have to do is initialize the screen without clearing the buffer, give the flexibleOLED.display() command, and the OLED will show the SparkFun logo. It’ll look similar to the image below.

SparkFun Logo

Example 8 - Noise Drawing

To get started, open up Example8_NoiseDrawing under File>Examples>SparkFun Flexible Grayscale OLED Breakout>Example8_NoiseDrawing. This example writes noise directly to the display and also to the buffer. However, the buffer is incapable of grayscale so we will only get black and white noise when calling the writeToBuffer() function. We can see upon closer inspection that each of these functions writes noise from the A0 and A1 pins, so make sure these aren’t connected to anything. The output will look something like the below image. Notice how the noise from the buffer is only in black and white.

Noise

Resources and Going Further

Now that you’ve successfully got your flexible grayscale OLED display up and running, it’s time to incorporate it into your own project!

For more information, check out the resources below:

Need some inspiration for your next project? Check out some of these related tutorials:

Using OpenSegment

How to hook up and use the OpenSegment display shield. The OpenSegment is the big brother to the Serial 7-Segment Display. They run on the same firmware, however the OpenSegment is about twice as big.

Using the Serial 7-Segment Display

How to quickly and easily set up the Serial 7-Segment Display and the Serial 7-Segment Display Shield.

Serial Graphic LCD Hookup

Learn how to use the Serial Graphic LCD.

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

RedBoard Edge Hookup Guide

$
0
0

RedBoard Edge Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The RedBoard Edge is a nifty little rework of the SparkFun RedBoard designed to be panel mounted in your custom project enclosure to allow for an easy way to make a clean, finished looking product. It has all the features of a normal RedBoard, allowing you to prototype on a RedBoard and easily move your project over to a RedBoard Edge without complication.

SparkFun RedBoard Edge

DEV-14525
$19.95

The RedBoard Edge is just as easy to use as a regular RedBoard, so it’s still an excellent learning platform for physical computing.

The goal of this tutorial is to familiarize you with the RedBoard Edge so you’ll be able to easily transfer over your RedBoard project when you’re ready to go from a prototype to an enclosed product. Since it’s basically a reshaped RedBoard, you may be able to glaze over parts of this tutorial if you’re familiar with how the RedBoard works.

Required Materials

To follow along with this tutorial, you will need the following materials. You may not need everything though depending on what you have. Add it to your cart, read through the guide, and adjust the cart as necessary.

You will need a RedBoard Edge and a micro-B-to-A USB cable. The USB interface serves two purposes: it powers the RedBoard Edge and allows you to upload programs to it.

USB micro-B Cable - 6 Foot

CAB-10215
$4.95
9
SparkFun RedBoard Edge

DEV-14525
$19.95

You’ll also need a computer – Mac, PC, or Linux will do – with the Arduino IDE installed on it. You can download Arduino from their website. They’ve got installation instructions there, but we’ll also go over installation in this tutorial.

Download the Arduino IDE

Tools

Depending on your setup, you may need a soldering iron, solder, and general soldering accessories.

Solder Lead Free - 100-gram Spool

TOL-09325
$7.95
7
Weller WLC100 Soldering Station

TOL-14228
$44.95

Suggested Reading

The RedBoard Edge aims to be as beginner friendly as a microcontroller platform can be. You can get by using it without an innate knowledge of Ohm’s Law or How Electricity Works (but a little understanding wouldn’t hurt!). The board utilizes the Qwiic system so we recommend reading here for an overview. Brushing up on your skills in I2C is also recommended, as all Qwiic sensors are I2C. If you aren’t familiar with the following concepts, we recommend checking out these tutorials before continuing.

What is a Circuit?

Every electrical project starts with a circuit. Don't know what a circuit is? We're here to help.

What is an Arduino?

What is this 'Arduino' thing anyway?

I2C

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

A Rearranged RedBoard

With the RedBoard Edge, we’ve rearranged the RedBoard Programmed with Arduino to include everything “user-facing” (i.e. “front” side) on one side of the board, and everything “project-facing” on the other side of the board.

User-Facing Side (i.e. "Front" Side)Project-Facing Side

Below are images highlighting where all of the things you’ve come to know and love on your regular old RedBoard have moved to. Pins have been grouped by function (PWM, ADC, SPI), with power rails for 5V and Ground running parallel to each grouping. There are also 4-pin power rails for 5V and 3.3V right next to the 5mm 2-pin screw terminal which is connected to VIN through the toggle switch on the user-facing side of the board.

The User-Facing Side (i.e. “Front” Side)

micro-B USB

The RedBoard Edge can be powered via either the USB or barrel jack connectors. If you choose to power it via USB, the other end of the USB cable can be connected to either a computer or a (5V regulated) USB wall charger.

micro-B Connector

Barrel Jack for VIN

The power jack accepts a center-positive barrel connector with an outer diameter of 5.5mm and inner diameter of 2.1mm. Our 9V and 12V wall adapters are good choices if you’re looking to power the RedBoard this way. Any wall adapter connected to this jack should supply a DC voltage between 7V and 15V.

Barrel Jack

Power Switch

The board has a switch to toggle power for the rest of the board. Note that the toggle switch will not disconnect USB power.

Power Switch

Choosing Power for the RedBoard Edge

There are a few options to power the RedBoard Edge depending on your preference and project needs. USB is usually the easiest way to power the board, especially when you’re programming it, because the USB interface is required for uploading code too. Why would you use the barrel jack? Usually, it’s because you need more power. A USB port is usually only allowed to supply 500mA. If you need more than that a wall adapter may be your only choice.

It is acceptable to connect both a barrel jack and a USB connector at the same time. The RedBoard Edge has power-control circuitry to automatically select the best power source. As explained earlier, the toggle switch will not disconnect USB power.

Indication and Interfacing

All of the indication lights have been moved to the front side of the board, so you would be able to see them in your custom enclosure. From left to right, the indicator lights are connected to power, pin 13, TX, and RX, shown in the image below. The button on the far right of the board controls Reset.

LEDs and Reset Switch

The Project-Facing Side

Screw Terminals for VIN

This barrel connector is connected to the screw terminals on the project-facing side of the board through the toggle switch on the front of the board.

Screw Terminals for VIN

PTH Power Pins

The board also comes with 5V, 3.3V, and GND pins throughout the board.

Voltage Rails

Pin Grouping

The RedBoard Edge has its pins separated into three groups on the project facing side of the board (ADC, SPI, and PWM) which are highlighted in the image below. These pins have the same functions as their RedBoard counterparts so expect to be able to use them like you would on your regular old RedBoard. Each group of three rows has the pins broken out on the top row, a 5V rail in the middle row, and ground on the bottom row.

Analog Inputs

There are eight analog inputs on the analog header. These pins all have analog-to-digital converters, which can be used to read in an analog voltage between 0 and 5V. These are useful if you need to read the output of a potentiometer or other analog sensors. All eight analog pins can also serve as digital inputs and outputs.

ADC Pins

Serial Peripheral Interface (SPI)

The center group of 4 pins is the SPI Interface where pin 10 = SS, pin 11 = MOSI, pin 12 = MISO and pin 13 = SCK.

SPI Pins

Pulse Width Modulation (PWM)

The furthest right grouping of pins are the Pulse-Width Modulation (PWM) pins, which can be used to drive LED’s or servos.

PWM Pins

Headers

The RedBoard Edge does not come with headers on-board to allow you the option to be able to solder your finished circuit straight into the board. However, if you’d like to use your Edge for something more along the lines of prototyping purposes, grab some headers.

Check out our through hole soldering tutorial if you have yet to solder headers to a board

With Headers

Other Neat Features

Grounded Mounting Holes

One of the cool things about the RedBoard Edge is the ability to ground the board to your metal enclosure through the standoffs on the left side. You can choose to connect your enclosure ground to either the USB shield or the board’s ground, or both. Simply add solder to the respective jumper pad and connect the enclosure to your board with any 4-40 screw.

USB Shield GND Mounting HoleGND Mounting Hole

Qwiic Connector

We’ve also added a Qwiic connector, sandwiched in there between the power and ADC pins, to allow the RedBoard Edge to interface with SparkFun’s Qwiic Ecosystem.

Qwiic Connector

CH340G USB-to-Serial Converter

As opposed to using the FTDI for USB-to-serial conversion, the board uses the CH340G IC. One advantage is that it does not need a driver since most operating systems have the CDC drivers pre-installed. What this means is that you shouldn’t need to install any extra software.

CH340G USB-to-Serial Converter

Download/Install Arduino

Before you plug the RedBoard Edge into your computer, you’ll need to install Arduino first.

Installing Arduino

To begin, head over to Arduino’s download page and grab the most recent, stable release of Arduino. Make sure you grab the version that matches your operating system.

Download the Arduino IDE

The installation procedure is fairly straightforward, but it varies by OS. Here are some tips to help you along. We’ve also written a separate Installing Arduino tutorial if you get really stuck.

Installing Arduino IDE

March 26, 2013

A step-by-step guide to installing and testing the Arduino software on Windows, Mac, and Linux.

Windows Install Tips

The Windows version of Arduino is offered in two options: an installer or a zip file. The installer is the easier of the two options, just download that, and run the executable file to begin installation. If you’re prompted to install a driver during installation, select “Don’t Install” (the RedBoard Edge doesn’t use the same drivers). Don’t forget which directory it installs to (defaults to “Program Files/Arduino”).

Windows Installer

Windows install steps. Click the image to get a bigger view.

If, instead, you choose to download the zip file version of Arduino, you’ll need to extract the files yourself. Don’t forget which folder you extract the files into! We’ll need to reference that directory when we install drivers.

Mac Install Tips

The Mac download of Arduino is only offered in a zip file version. After the download is finished, simply double-click the .zip file to unzip it.

Mac Install Screenshot

Following that, you’ll need to copy the Arduino application into your applications folder to complete installation.

Linux Install Tips

As you Linux users are no doubt aware, there are many flavors of Linux out there, each with unique installation routines. Check out the Linux section of the Installing Arduino tutorial for some helpful links for an assortment of Linux distributions.

For Ubuntu and Debian users, installing Arduino should be as easy as running a little “apt-get” magic, with a command like:

language:bash
sudo apt-get update && sudo apt-get install arduino arduino-core  

And other Linux distros aren’t too dissimilar from that.


With Arduino downloaded and installed, the next step is to plug the RedBoard Edge in and install some drivers! Pretty soon you’ll be blinking LEDs, reading buttons, and doing some physical computing!

No Drivers Needed!

The CH340G USB-to-serial converter that is populated on the RedBoard Edge does not need a driver. It has been tested on Windows 7, Windows 8.x, Windows 10, Linux Mint, and OSX Yosemite, El Capitan, and Sierra. These operating systems have the CDC drivers pre-installed, which means you shouldn’t need to install any extra software. However, there are a wide range of operating systems out there, so if you run into driver problems, you can get CH340G drivers from the Serial Basic Hookup Guide:

Serial Basic Hookup Guide: Drivers If You Need Them

Note: This example assumes you are using the latest version of the Arduino IDE on your desktop. If this is your first time using Arduino, please review our tutorial on installing the Arduino IDE.

Now it’s finally time to open up the Arduino IDE Software. You’ll be presented with a window that looks a little something like this:

Arduino IDE annotated

Lets upload a Blink sketch to make sure our new RedBoard Edge setup is totally functional. Go up to the File menu in Arduino, then go to Examples > 01.Basics > Blink to open it up.

Before we can send the code over to the RedBoard Edge, there are a couple adjustments we need to make.

Select a Board

This step is required to tell the Arduino IDE which of the many Arduino boards we have. Go up to the Tools menu. Then hover over Board and make sure Arduino Uno is selected.

Board Selection

Select a Serial Port

Next up we need to tell the Arduino IDE which of our computer’s serial ports the RedBoard is connected to. For this, again go up to Tools, then hover over Serial Port and select your RedBoard’s COM port.

Port Selection

If you’ve got more than one port, and you’re not sure which of the serial ports is your RedBoard Edge, unplug it for a moment and check the menu to see which one disappears.

Upload!

With all of those settings adjusted, you’re finally ready to upload some code! Click the Upload button (the right-pointing arrow) and allow the IDE some time to compile and upload your code. It should take around 10-20 seconds for the process to complete. When the code has uploaded, you should see something like this in your console window:

Uploading Code

And if you look over to the RedBoard Edge, you should see the blue LED turn on for a second, off for a second, on for a second, off for a second…ad infinitum (at least until it loses power). If you want to adjust the blink speed, try messing with the “1000” value in the delay(1000); lines. You’re well on your way to becoming an Arduino programmer!

Something Wrong?

Uh oh! If you didn’t get a “Done Uploading” message, and instead got an error, there are a few things we can double-check.

If you got an avrdude: stk500_getsync(): not in sync: resp=0x00 error in your console window.

Upload error

Either your serial port or board may be incorrectly set. Again, make sure Arduino Uno is the board selection (under the “Tools > Board” menu). The serial port is usually the more common culprit here. Is the Serial Port correctly set (under the “Tools > Serial Port” menu)? Did the drivers successfully install? To double check your RedBoard Edge’s serial port, look at the menu when the board is plugged in, then unplug it and look for the missing port. If none of the ports are missing, you may need drivers.

Panel Mounting

The RedBoard Edge was designed with panel mounting in mind, so let’s look at how everything is laid out on the user-facing side so we can put holes in the proper places for a panel or enclosure.

Front of Edge

The RedBoardEdgePanel.svg used for a panel mount should work well with a printer or maybe even a laser cutter. The file can be downloaded from the button below. Just make sure to unzip the file before using.

Download RedBoardEdgePanel (ZIP)

Once you’ve created your front panel, it’s easy to slide your RedBoard Edge through and secure it in place using the nut on the toggle switch. Look at that, my apartment smells of many burnt electronics and rich mahogany.

Mounted Edge

Mounting Hardware

If you’d like to mount the RedBoard Edge to some sort of baseplate as well, you can attach the RedBoard Edge to your baseplate using 4-40 standoffs and screws to attach the RedBoard Edge to your baseplate. Keep in mind that grounding the board through the mounting holes will require metal standoffs.

Standoffs Plastic - (4-40; 3/4"; 10 pack)

PRT-10462
$3.95
Standoff - Metal Hex (4-40; 3/8"; 10 pack)

PRT-10463
$3.95
Standoffs Plastic (4-40; 3/8"; 10 pack)

PRT-10461
$2.95
Standoff - Nylon (4-40; 3/8"; 10 pack)

PRT-10927
$2.95
Screw - Phillips Head (1/4", 4-40, 10 pack)

PRT-10453
$1.50
Screw - Phillips Head (1/2", 4-40, 10 pack)

PRT-10452
$1.50
Screw - Phillips Head (1", 4-40, 10 pack)

PRT-10450
$1.50$0.46
Screw - Phillips Head (3/4", 4-40, 10 pack)

PRT-10451
$1.50$0.45

Resources and Going Further

Now that you’ve gotten code uploaded to your RedBoard Edge, you’re ready to finally create that nice, clean looking panel mounted project of your dreams.

For more on the RedBoard Edge, check out the links below:

Need some inspiration for your next project? Check out some of these related tutorials:

Installing a Bootloader on the MicroView

Fix your bootloader-less MicroView! This tutorial covers how to: disassemble the MicroView, wire it up to an assortment of programmers, program the bootloader, and test it out.

MP3 Player Shield Hookup Guide V15

How to get your Arduino groovin' using the MP3 Player Shield.

ESP8266 Thing Hookup Guide

An overview of SparkFun's ESP8266 Thing - 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.

DIY Light-Up Shoes

This tutorial provides everything you need to know to make your own light up high top sneakers!

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

HX1 APRS Transmitter Hookup Guide

$
0
0

HX1 APRS Transmitter Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The HX1 is a low-power radio transmitter set to a fixed frequency of 144.390MHz. In North America this frequency is used for the Automatic Packet Reporting System, or APRS.

HX1 - VHF Narrow Band FM APRS Transmitter  (144.39Mhz - NA)

WRL-14740
$50.95

APRS is a standard used by amateur-radio operators to broadcast location and sensor data. This data can be received by anyone with the proper equipment, and is aggregated on the internet through gateways run by the APRS community.

APRS is used to share real-time data including vehicle location (GPS), weather stations, high-altitude balloon tracking, remote sensor platforms, disaster relief coordination, and more. It’s effectively an open-source, open-data, community-run, free to use, IoT system with potentially worldwide coverage.

Required Materials

To follow along with this guide, you will need the following materials.

  • A HX1 Transmitter.
  • A 5V Arduino such as the SparkFun RedBoard.
    • Since the HX1 is a “bare” transmitter, you’ll need a microcontroller programmed to properly format the transmission. We’ll cover an Arduino project to do this later in this guide.
  • A power supply capable of 150mA or more, such as a 9V Wall Adapter.
  • Any sensors your application requires.
  • An antenna tuned to 433MHz (or more generally the 2-meter band)
    • The HX1 requires an external antenna to operate. We’ll show you how to construct one later in this guide.
  • An amateur radio license.

Getting Licensed

Before we go too much further, we’ll remind you that since this transmitter uses an amateur radio frequency, you will need an amateur radio license to operate it. Don’t worry; getting a license is easy and opens you up to a whole new world of technical capabilities.

The most basic license class, Technician, will be sufficient to use this transmitter. You’ll need to pass a 35-question test, and the entire pool of questions and answers is available beforehand for you to study. If you’ve been playing with electronics for a while and know Ohm’s Law (V=IR), you’re halfway there. The rest involves memorizing some straightforward rules and regulations.

The first step is to go to the American Radio Relay League (ARRL) website. The ARRL is the amateur radio community organization. Even though your license will be issued by the Federal Communications Commission (FCC), the ARRL handles training and testing. At the ARRL website you’ll find a list of upcoming exam sessions near you, as well as practice questions and other useful information.

ARRL Amateur Radio License Training and Testing

Once you pick an exam date and location, study! In addition to the ARRL website, there are a number of books, websites, and apps that can help you study. On test day, show up with the required fee, a photo ID, a #2 pencil, and a nonprogrammable calculator (phones aren’t allowed). When you finish the test, the examiners will tell you immediately whether you passed or not. If you passed, you’ll get your callsign in the mail in a few weeks. And once you have your callsign, you can legally transmit with the HX1 (as well as do many other things).

Pro Tip: Although you'll only need a technician-class license to transmit with the HX1, you can also take the higher class tests on the same day at no additional cost. It may be worth a bit more studying!

What is APRS?

APRS was conceived in the 1980s by Bob Bruninga (WB4APR), currently a senior research engineer at the United States Naval Academy and still very active in the APRS community. It filled a need for a simple way to transfer small amounts of textual data between multiple amateur radio stations without having to manually copy voice messages. APRS has since evolved into a rich, global system for transmitting location and sensor values that others can receive and use.

Receiving APRS Messages

Speaking of receiving, if the HX1 is just a transmitter, how does one receive APRS messages?

You can easily receive APRS packets with the proper equipment. An inexpensive 2-meter receiver tuned to 144.390MHz will receive the audio tones that make up APRS packets. You can then pipe the audio to a computer running the proper software to decode the packets. You can then use the information in the packets to display locations on a map, graph other data included in the packets, etc.

But you don’t necessarily have to set up your own receiver. Many people in the APRS community have already set up receiving stations, called “gateways,” that receive APRS packets and pipe the data onto the internet for aggregation by various websites. One of the largest websites is APRS.fi. It receives live APRS data from all over the world, displaying station locations and data on a map. (If you become an enthusiast of APRS, you’re encouraged to set up your own gateway and join the network.)

screen capture of the APRS.fi website showing APRS stations on a map

What is a Packet?

An APRS “packet” is a short (25 to 200 characters), self-contained text message. APRS has strict formatting rules, with fields for various types of data (station callsign, GPS location, time, weather data, etc.). Because the formatting is standard, packets generated with one software package can be received and decoded by everyone else. Formatting details are available in the APRS Spec available at APRS.org.

APRS Packet Specification

Because APRS uses a single shared frequency (in North America it’s 144.390MHz), everyone can see what everyone else is doing. By keeping the packets short and turning off transmitters between sends, many people can share the same frequency. Packets are often sent at slightly random times to avoid packet collisions (two people transmitting at the same time). If there are collisions the data for both packets is garbled. However, APRS systems are normally set to resend new packets every few minutes, guaranteeing fresh data before too long.

What Can I Do With APRS?

If you go to APRS.fi and look at the live map, you’ll see the current locations of vehicles, aircraft, and sometimes high-altitude balloons. You’ll also see fixed weather stations and other environmental sensors. These transmissions are all being made by people who have a personal or hobbyist use for various data (such as vehicle or balloon locations), or who want to provide useful data to the larger community (such as a weather station at their house).

Google Maps APRS

What CAN’T I Do With APRS?

It’s worth noting that since APRS uses amateur radio frequencies, the transmissions must abide by the rules and spirit of the amateur radio community. Specifically:

  • Amateur radio frequencies are solely for non-commercial use. You can use APRS for your own hobby or scientific use, but you can’t use APRS for any part of a business. (Amateurs are very serious about this - radio bands are a valuable commodity, and amateurs regularly have to fight to keep what they have from being sold to commercial bidders.)

  • The data you send must be open. Since you’re transmitting on an open system everyone can see your data, but you’re not allowed to hide it by encrypting or obscuring it. Along these lines, it’s encouraged that the data you send be of interest to the community - weather stations and other public-service data sources are always appreciated.

Hardware Overview

The HX1 has seven pins in two groups:

HX1 Pinout

PinFunctionNotes
1RF GroundAntenna ground or coax shield
2Antenna OutputAntenna or coax center
3RF GroundAntenna ground or coax shield
   
4EN (Enable) Input5V to transmit, 0V for standby
55V Power Input (VCC)Regulated 5V power supply at 140mA
6GroundGround of regulated power supply
7TXD (Transmit Data) Input5V signal with modulation and formatting

Power Supply

The HX1 requires a regulated 5V supply capable of providing 140mA when it’s transmitting (it uses essentially no current in standby). The voltage regulator already present on a 5V Arduino should be able to handle this.

EN (Enable) Input

The EN or enable pin controls whether the module is transmitting or in standby mode (sometimes this is called a PTT or “Push To Talk” control). Since APRS uses a shared frequency, it’s important to only transmit during the brief time that a packet is being sent and stay silent otherwise; this lets many people share the frequency. To transmit, the EN pin must be set to a high logic level (5V).

After enabling the transmitter, it’s a good idea to wait 5ms before sending any data to the TXD pin. Your software should handle this automatically.

TXD (Transmit Data) Input

It’s important to note that the HX1 is a bare transmitter and doesn’t do any modulation or packetizing on its own. The TXD data input must be modulated properly in order to transmit properly. Modulation and packetizing is a broad topic beyond the scope of this tutorial, but there are several Arduino projects designed to connect to the TXD pin of the HX1 and send data. We’ll cover one of these projects below.

Antenna

WARNING: Do not transmit without an antenna or equivalent load connected to the antenna pin. Without an antenna, RF energy can reflect back into the module, damaging it.

The HX1 requires an antenna to transmit. You can buy one (search for “2 meter antenna” as the APRS frequency is in the 2-meter amateur radio band), or you can build one.

There are many antenna designs out there, but a simple quarter-wave ground plane antenna works well and is easy to make. This antenna features a vertical element surrounded by four radial elements angled down at 45 degrees:

Antenna Drawing

Having a hard time seeing the circuit? Click on the image for a closer look.

The length of an antenna’s elements depends on the frequency. For the 144.390MHz frequency we’ll be using, the element lengths are:

AntennaLength
Vertical Element (1x):19 + 7/16"493mm
Radial Elements (4x):21 + 3/4"553mm

The elements can be made of any conductive metal, but brass and copper rods are easy to solder to. The rods can be supported in position by any nonconductive material (plastic, wood, etc.).

To connect the antenna to the HX1, connect the vertical element to the antenna output pin (2), and the radial elements to the RF ground pins (1,3) on either side of the antenna pin.

If the HX1 transmitter will be more than a couple inches away from the antenna, use 50-ohm coaxial cable to connect the RF pins to the antenna. Connect the antenna output pin (2) to the center conductor of the coax, and the outer RF ground pins (1,3) to the shield. On the antenna side, connect the center conductor to the vertical element, and the shield to the radial elements or ground plane.

For maximum range, locate your antenna as high as practical and away from nearby metal objects PVC pipe is a good nonconductive structural material for this.

Note that this antenna design is omnidirectional, which means that it will work equally well in all directions, but it will have a somewhat reduced range. Directional antennas will give you greater range, but you’ll need to point them towards the remote receiver. Amateur radio books and websites have information on many other antenna designs; check them out if you’re interested.

Connecting to Trackuino

Note: This example assumes you are using the latest version of the Arduino IDE on your desktop. If this is your first time using Arduino, please review our tutorial on installing the Arduino IDE. Make sure the included header files are in the same folder in order for the trackuino.ino sketch to compile.

Several open-source Arduino APRS projects are available, with various features and limitations. Here we’ll present a project called Trackuino written by Javi Martin. Trackuino is a combination of hardware and software used to track high-altitude balloons. It’s a bit older, but probably the easiest Arduino APRS implementation to use with the HX1.

Note: We recommend that you download SparkFun's fork of the Trackuino software from the link below. We are working to improve this project for general APRS use:

GitHub Repo Fork: SparkFun Trackuino

Hardware Assembly

A default Trackuino system includes a GPS receiver, two temperature sensors, a battery voltage sensor, and a buzzer (used to locate balloons when they land). To wire up the default system, use the following wiring diagram and table. (We’ll discuss modifying the default system in the next section.)

schematic diagram matching below table

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

FromToDescription
HX1 VCC (5)Arduino 5VHX1 power supply
HX1 GND (6)Arduino GNDHX1 power ground
HX1 EN (4)Arduino D4HX1 transmit enable
HX1 TXD (7)Arduino D3HX1 transmit data
   
HX1 RF ground (1)Antenna groundAntenna ground plane
HX1 antenna output (2)AntennaAntenna
HX1 RF ground (1)Antenna groundAntenna ground plane
   
GPS TXArduino D0 (RX)GPS data
GPS powerArduino 3.3VGPS power
GPS groundArduino groundGPS ground
   
Internal TMP36 powerArduino D6Temperature sensor power
Internal TMP36 signalArduino A0Temperature sensor signal
Internal TMP36 groundArduino groundTemperature sensor ground
   
External TMP36 powerArduino D7Temperature sensor power
External TMP36 signalArduino A1Temperature sensor signal
External TMP36 groundArduino groundTemperature sensor ground
   
Buzzer powerArduino D9Buzzer power
Buzzer groundArduino groundBuzzer ground
   
Arduino VIN (battery voltage)Arduino A2 via 10k resistorBattery voltage sensor
Arduino A2Arduino ground via 3.3k resistorBattery voltage sensor

Configuring Trackuino

Out of the box, Trackuino is configured for use on high-altitude balloons, but with a little hacking you can alter it for your own purposes.

Note: We're going to be working on SparkFun's fork of Trackuino to make it more general-purpose and easier to configure. Keep an eye on the forked GitHub repository at SparkFun Trackuino for changes and updates.

GitHub Repo Fork: SparkFun Trackuino

There’s one change you must make: open the config.h file, and insert your callsign and station ID at line 42. APRS transmits your callsign in every packet; this is a legal requirement.

Another thing you may want to change in the file aprs.cpp is the “symbol” character defined on line 62. This controls what graphical symbol will show up at your location when you’re using APRS mapping software or websites. The provided ‘O’ indicates a balloon, but there are many other symbols available such as ‘-’ for fixed location, ‘K’ for school, ‘>’ for car, ‘Y’ for boat, etc. For a complete list, check out the link below.

APRS Display Symbols

By default Trackuino sends an APRS packet that includes GPS time, GPS location, altitude, battery voltage, and several temperature sensor values. If you want to build your own APRS packet, you can alter the aprs_send() function in aprs.cpp to remove various sensor values or add your own.

Running Trackuino

Once you have the hardware and software set up, run Trackuino. This should should begin transmitting APRS packets after it obtains a GPS lock.

If you have a 2-meter receiver or SDR, you can set it to 144.390MHz to hear the packets being sent. If you pipe the audio to a computer and run the proper software (Dire Wolf is one such package), you’ll be able to decode the packets and see the original text.

If you are close enough to an APRS gateway, your packets will be received and piped to the internet. You should be able to go to APRS.fi and search for your callsign to see received packets and the data they contain.

Next Steps

There is a great deal of information about APRS on the internet. One can build antennas, run gateways, track balloons, help coordinate disaster relief, etc. Even the sky isn’t the limit, as many amateur satellites receive and transmit APRS packets.

SparkFun will also be updating this and other tutorials as we work on APRS and other amateur radio projects. Get licensed, and stay tuned!

Resources and Going Further

Now that you’ve successfully got your HX1 APRS Transmitter up and running, it’s time to incorporate it into your own project!

For more information, check out the resources below:

Need some inspiration for your next project? Check out some of these related tutorials:

Photon Remote Water Level Sensor

Learn how to build a remote water level sensor for a water storage tank and how to automate a pump based off the readings!

Weather Station Wirelessly Connected to Wunderground

Build your own open-source, official Wunderground weather station that connects over WiFi via an Electric Imp.

Photon Remote Temperature Sensor

Learn how to build your own Internet-connect, solar-powered temperature collection station using the Photon from Particle.

Looking for more information about high altitude balloon projects? Check out some of these related tutorials:

Nate's High Altitude Balloon SeriesAaron's High Altitude Balloon Launch

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

LilyPad USB Plus Hookup Guide

$
0
0

LilyPad USB Plus Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The LilyPad USB Plus is a sewable electronics microcontroller that you can use with Arduino. In this tutorial we’ll introduce the features of the USB Plus and set up the free Arduino software you’ll need to upload code to it.

Lilypad USB Plus

DEV-14631
$24.95

The USB Plus is available as a standalone board or as part of the LilyPad ProtoSnap Plus board.

LilyPad ProtoSnap Plus

DEV-14346
$39.95

Required Materials

To reprogram and recharge the board, you’ll need a micro-B USB cable. This is a common cable used by many devices, so you may already have one. Double check that it is not labeled ‘Power Only’ as these type of cables will not transmit the programming data needed by the LilyPad USB Plus board. If you don’t have one you can get one from SparkFun:

USB micro-B Cable - 6 Foot

CAB-10215
$4.95
9
USB Micro-B Cable - 6"

CAB-13244
$1.95
3

Suggested Reading

If you aren’t familiar with the following concepts, we recommend checking out these tutorials before continuing.

What is an Arduino?

What is this 'Arduino' thing anyway?

Installing Arduino IDE

A step-by-step guide to installing and testing the Arduino software on Windows, Mac, and Linux.

Planning a Wearable Electronics Project

Tips and tricks for brainstorming and creating a wearables project.

Hardware Overview and Features

The LilyPad USB Plus is an Arduino-compatible microcontroller. It has fourteen sew tabs for connecting components with conductive thread. Four of these tabs are reserved for connecting power and ground of LilyPad sensors and accessory boards, and ten are input/output (I/O). For reference, each sew tab has a nearby label with its name and the pin number it is connected to on the ATmega32U4 chip at its center.

LilyPad USB plus with labels for power, ground, and input/output sew tabs

Features:

  • USB port for connecting to a computer.
  • Two sets of power (+) and ground (-) sew tabs.
  • Built-in RGB LED attached to pins 12 (R), 13 (G), and 14 (B).
  • A row of six white LEDs attached to pins 15-20.
  • Charging circuit for single-cell (3.7V) Lithium-Polymer batteries.

Additional SMD LEDs

Powering the LilyPad USB Plus

The LilyPad USB Plus can be powered in two ways:

  • If you have a USB power source available (a computer, 5V USB wall adapter, USB battery pack, etc.), you can run the board from a USB cable.

  • Once sewn into a project, you can easily attach a rechargable Lithium-polymer battery to the board. See Technical Notes section for more information on batteries and charging.

To power up the USB Plus, connect it to your computer using a micro-B USB cable or attach an E-Textiles Battery. Then slide the switch on the right side of the LilyPad USB Plus to the ON position.

Switch ON

Setting Up Arduino

Note: The LilyPad USB Plus requires Arduino version 1.8 or higher. If this is your first time using Arduino, you can install it by following our Installing the Arduino IDE tutorial. Otherwise, please make sure to install (or update to) the latest version of Arduino and verify that you are connected to the internet to download the LilyPad USB Plus software add-ons.

When you first install Arduino, it knows how to program a number of “standard” Arduino-compatible boards. Since the LilyPad USB Plus is a newer LilyPad microcontroller, you will need to manually add it to this list by following the steps below. You’ll only have to do this once to add the board to Arduino.

Note for Linux Users: If you are installing the LilyPad USB Plus in Linux, this document has some specific notes: https://github.com/sparkfun/LilyPad_ProtoSnap_Plus/blob/master/Documentation/LinuxInstallation.md.

Add SparkFun Boards to Arduino’s Preferences

Start the Arduino IDE software (version 1.8 or higher) and open the Preferences window by choosing File>Preferences from the menu.

Now copy the below text and paste it into the “Additional Boards Manager URLs” text box:

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

Additional Board Manager

No room? If there is already a URL in the box, click the button to the right of the box. This will open a window allowing you to paste the URL onto a new line.

Additional Board Manager URLs

When you’re done, click the “OK” button.

Install SparkFun AVR Boards

Next, you’ll add the LilyPad USB Plus through Arduino’s Boards Manager Menu. Open the Boards Manager by choosing Tools>Board>Boards Manager… (The Boards Manager option is at the very top of the list of boards; you may need to scroll up to see it.)

Board Manager

When the Boards Manager window opens, it will present a long list of options. Type “SparkFun” (without quotes) into the “Filter your search” box at the top of the window. This will shrink the list down to SparkFun’s options.

You should see several entries. Look for the one labeled SparkFun AVR Boards by SparkFun Electronics.

SparkFun AVR Boards by SparkFun Electronics GUI

Troubleshooting: If you don't see a SparkFun entry, it may mean that the URL you pasted into the Additional Boards Manager section of Arduino's preferences did not load correctly in Step #1, or you're not connected to the internet. Double check that the entire link was copied into the Additional Boards Manager URLs, and that you're connected to the internet. You might also try closing and restarting the Arduino software to refresh the preferences.

Click anywhere in the SparkFun AVR Boards box. A version number and an “Install” button will appear. Click the install button. This will download and install the extension. If you have already installed the SparkFun AVR Boards support, update to the latest version (LilyPad USB Plus is included in 1.1.8 and higher).

Select the Install Version

If everything worked, a blue “INSTALLED” note should appear next to the SparkFun AVR Boards title. You’re ready to start programming.

Confirm the Install

Uploading Code

Once you’ve installed the LilyPad USB Plus extensions to Arduino, you’re ready to start programming the board!

Note that you won’t have to install the extensions again, but you will need to perform the below three steps every time you want to program the board. These three steps are:

1. Connect the LilyPad USB Plus to your computer using a USB cable
2. Select "LilyPad USB Plus" from Arduino's "Board" menu
3. Select "LilyPad USB Plus" from Arduino's "Port" menu

Let’s go over the three steps in detail:

1. Connect the LilyPad USB Plus to Your Computer

Place the LilyPad USB Plus on a clean, non-metal work surface. Connect the LilyPad USB Plus to a USB port on your computer using a micro-B USB cable. The cable can only be inserted one way, and should snap in securely.

USB Cable

Tip: Both the micro-B USB cable and the connector on the LilyPad have a subtle "D" shape to them. Match this shape to plug it in properly.

Connected to computer's USB port

Slide the switch on the LilyPad USB Plus to the ON position. You will not be able to upload code to the board if it is set to the OFF position.

Turn LilyPad USB Plus on

2. Select LilyPad USB Plus from the Board Menu

If the Arduino board support was installed correctly, “LilyPad USB Plus” option will be available in the Tools>Board list under the SparkFun AVR Boards group. Open the menu and select LilyPad USB Plus. Depending on how many boards are already in the list, you may need to scroll down a bit to get to it. A dot (Windows) or check mark (Mac) will show next to the board in the menu when it is selected, and it will show next to Board in the Tools menu.

IMPORTANT: You'll see some LilyPad entries higher in the Arduino menu, but the LilyPad USB Plus is not one of them. You'll need to scroll down to the SparkFun section at the bottom of the list to find it. We're working on getting the LilyPad USB Plus added to the LilyPad group in the future.

Select Board Definition

Troubleshooting: If you don't see "LilyPad USB Plus" in the board list, go back to Setting Up Arduino and double check that you performed all the steps. You might try restarting Arduino as well.

3. Select LilyPad USB Plus from the Port Menu

Arduino needs to know which port your LilyPad USB Plus is attached to so it can program it. Whenever you plug a USB device into your computer, your computer will assign it a port number. This used to be difficult to determine, but this board has a handy feature that identifies itself. Go to the Tools>Port menu, and select the port that has “LilyPad USB Plus” next to it.

On Windows, ports are listed as COM##; on a Mac or Linux machine they will be “/dev/cu.usbmodem####”. Your screen may look different than the image below, depending on what operating system you are using, but all should show LilyPad USB Plus next to the port address.

COM Port

Troubleshooting: If you don't see a port with "LilyPad USB Plus" next to it, ensure that the board is powered up (switch in the ON position), and that the USB cable is securely connected to both the board and your computer. Some micro-USB cables are only meant for charging and don't pass data - they'll power the board, but it won't show up in the port menu. If needed, try a different cable.

Uploading Code

To review, once you’ve:

  1. Connected the LilyPad USB Plus to your computer using a USB cable.
  2. Selected the board type (“LilyPad USB PlusNOTLilyPad Arduino USB”).
  3. Selected the COM port.

You are ready to upload code! Let’s upload some code to try it out:

Load the “Blink” example from the menu File>Examples>01.Basics>Blink. This is a very simple example program; it just blinks a LED on and off once per second.

Blink Example

Click the “Upload” button (the large round button with the right arrow in it).

Upload Button

Arduino will compile the code, then send it to the LilyPad USB Plus via the USB cable. While the code is uploading, the built-in LED will blink to signal the code is transferring. When the code finally runs, the RGB LED at the center of the board will slowly blink green. Success!

If this all works, congratulations! You’re all set up and ready to prototype with the LilyPad USB Plus.

Troubleshooting: Error Messages on Upload?

If you are using a Mac and get an error message like the following:

Board LilyPad USB Plus (platform avr, package SparkFun) is unknown

It is possible that old Arduino versions left over after updates are interfering with the LilyPad USB Plus support installation. If you want to clear out this old information, follow these steps:

  1. Open Arduino’s “Preferences” window.
  2. At the bottom of the window will be a link to your preferences file. Click on it and it will open a finder window.
  3. In the finder window, look for an “Arduino15” folder and delete it.
  4. Now open a finder window and open your personal folder (the one with your login name and a house icon next to it). Look for an “Arduino” folder (possibly in “Documents”). If the “Arduino” folder contains a “Hardware” folder, delete it. Your Arduino installation is now clean. Restart Arduino and repeat the LilyPad installation instructions from the previous page.

Troubleshooting: Still Problems Uploading?

If you still have problems uploading code to the LilyPad USB Plus and they are not outlined here, try checking out the troubleshooting section of our activity guide:

LilyPad Protosnap Plus Activity Guide: Troubleshooting

Stitching Into a Project

As you plan your project and prototype your code, you can use alligator clips to connect individual LilyPad pieces to the USB Plus and test them before building into a project.

The connections you’ve planned using alligator clips or a sketch of your circuit can then be recreated with conductive thread by stitching the components in your project once you are finished prototyping. If you’d like to continue to refine your code after sewing into your project, make sure to leave the USB connector accessible.

Sew LilyPad Components

These tutorials will give you some tips and tricks for project construction and insulation:

Insulation Techniques for e-Textiles

Learn a few different ways to protect your conductive thread and LilyPad components in your next wearables project.

LilyPad Basics: E-Sewing

Learn how to use conductive thread with LilyPad components.

Technical Notes

If you are already familiar with programming Arduino for a while, read on for some additional notes about the LilyPad USB Plus. It’s similar to other Arduinos, but has some special features and limitations you’ll want to know about.

Using a Battery and Battery Charging

SparkFun sells a number of LiPo batteries compatible with this board. If you are new to the LilyPad system, we recommend the E-Textiles Battery. If you’re supplying your own battery, use a single-cell (3.7V) LiPo battery with a JST connector.

Batteries with larger capacities (measured as amp-hours or Ah) will run the board longer before needing recharging. How long will depend on how many LEDs your program turns on, etc. If you’re just running a few LEDs, you can expect the board to run about 5 hours for every 100mAh of battery capacity.

Charge Rate

To recharge an attached battery, plug the board into a USB power source.

Inserting a battery into the LilyPad USB Plus

While the battery is charging, the “CHG” LED will illuminate. When the battery is fully charged the LED will turn off. The default charge current is set to 100mA, so a 100mAh battery will recharge in one hour, a 1000mAh battery in 10 hours, etc. Since the board is set to charge at a rate of 100mA, we do not recommend connecting a lower capacity LiPo battery (i.e. 40mAh LiPo battery) to charge.

Location of CHG LED

Location of the “CHG” LED

It is safe to leave a LiPo battery attached to the board permanently, even with USB power applied. The battery will not be overcharged.

Notes on Washing LilyPad Projects

Removing the LiPo Battery

The battery connector can be tight; to remove a battery never pull on the wires. Use a pair of needle nose pliers or cutters to gently hold pull the plug out of the connector.

Using needle nose pliers to help move the plastic battery connector

Pin Numbering

Below is a list of the LilyPad USB Plus I/O pins and each function.

Legend:

  • n = digital pin
  • ~n = PWM-capable pin
  • An = analog-capable pin
  • (n) = internal pin (not connected to sew tab)
  • [n] = internal pin (available on an exposed via)
FunctionDigitalAnalog
RX_LED(0)
RX_LED/SS(1)
2A2
3A3
4A4
5A5
~6
~7A7
~8A8
9A9
SCL~10
SDA11
RGB LED - Red(~12)
RGB LED - Green(~13)
RGB LED - Blue(~14)
Bar Graph LED 0(15)
Bar Graph LED 1(16)
Bar Graph LED 2(17)
Bar Graph LED 3(18)
Bar Graph LED 4(19)
Bar Graph LED 5(20)
SCLK[21]
MOSI[22]
MISO[23]

Resources and Going Further

Now that you’ve successfully got your LilyPad USB Plus up and running, it’s time to incorporate it into your own project!

For more information about the LilyPad USB Plus, check out the resources below:

Looking to reuse old Lilypad Development Board examples and projects with the new LilyPad ProtoSnap Plus? Check out the guide linked below for more information.

New!

Adapting LilyPad Development Board Projects to the LilyPad ProtoSnap Plus

May 24, 2018

An overview of the updates made in the redesign of the LilyPad Development Board to the LilyPad ProtoSnap Plus and how to adapt code written for the old board to the new one.

Check out these projects using LilyPad Arduino:

Dungeons and Dragons Dice Gauntlet

A playful, geeky tutorial for a leather bracer that uses a LilyPad Arduino, LilyPad accelerometer, and seven segment display to roll virtual 4, 6, 8, 10, 12, 20, and 100 side dice for gaming.

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.

Night Sky Halloween Costume

Make a beautiful night sky costume using the LilyPad LEDs and the LilyTiny.

LilyPad Safety Scarf

This scarf is embedded with a ribbon of LEDs that illuminate when it gets dark out, making yourself more visible to vehicle and other pedestrians.

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


LilyPad Light Sensor V2 Hookup Guide

$
0
0

LilyPad Light Sensor V2 Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The LilyPad Light Sensor is a sewable breakout board with an ALS-PT19 light sensor on it. To use the light sensor, you will need to connect to a LilyPad Arduino or other microcontroller to read the sensor values and use them in your code.

The LilyPad Light Sensor outputs voltage between 0V and 3.3V depending on the level of ambient light shining on it. As more light is applied on the sensor, more current will flow from the board through the signal tab to the microcontroller you connect the sensor to. If the sensor receives no light, no current will flow through it. In a typical indoor lighting situation, the sensor will output around 1 to 2V.

LilyPad Light Sensor

DEV-14629
$2.95

This sensor is also used on the LilyPad ProtoSnap Plus and LilyMini ProtoSnap.

LilyPad ProtoSnap Plus

DEV-14346
$39.95
LilyPad LilyMini ProtoSnap

DEV-14063
$14.95
2

To follow along with the code examples, we recommend:

Suggested Reading

To add this sensor to a project, you should be comfortable sewing with conductive thread and uploading code to a LilyPad Arduino. Here are some tutorials to review before working with this sensor:

What is a Circuit?

Every electrical project starts with a circuit. Don't know what a circuit is? We're here to help.

Serial Terminal Basics

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

LilyPad Basics: E-Sewing

Learn how to use conductive thread with LilyPad components.

Getting Started with LilyPad

An introduction to the LilyPad ecosystem - a set of sewable electronic pieces designed to help you build soft, sewable, interactive e-textile projects.

Attaching to a LilyPad Arduino

The LilyPad Light Sensor has three sew tabs - Power (+), Ground (-), and Signal (S). Next to each tab is a white label on the top and bottom of the board for reference. The signal tab should be connected to an analog tab (marked with an ‘A’) on a LilyPad Arduino.

Labeled top and bottom views of the LilyPad Light Sensor board

To follow along with the code examples in this tutorial, connect the light sensor to a LilyPad Arduino as shown below. Use alligator clips to temporarily connect Signal to A2 on a LilyPad Arduino, (-) to (-) on the LilyPad, and (+) to (+). When you are finished prototyping, replace the alligator clips with conductive thread traces for permanent installation in your project.

LilyPad Light Sensor clipped to a LilyPad USB with alligator clips

Connecting to a LilyPad Arduino USB


Please Note:
If following along with a LilyPad ProtoSnap Plus, the light sensor is pre-wired to Pin A2. The light sensor on the ProtoSnap is a slightly different version than the catalog item, but functions the same.

If following along with the LilyMini ProtoSnap,the light sensor is pre-wired to Pin 1. Again, the light sensor on the LilyMini ProtoSnap is a slightly different version than the catalog item, but functions the same.

LilyPad Light Sensor location circled on a LilyPad ProtoSnap Plus boardLilyPad Light Sensor location circled on a LilyMini ProtoSnap board

Reading Values in Serial Monitor

Note: This example assumes you are using the latest version of the Arduino IDE on your desktop. If this is your first time using Arduino, please review our tutorial on installing the Arduino IDE.

After connecting the light sensor, let’s take a look at the values it reads under different lighting conditions. For this we’ll use analogRead() and Serial.print().

Upload the following code to your LilyPad Arduino, making sure to select the correct LilyPad board from the Tools->Board drop down menu. Choose LilyPad Arduino USB if using a LilyPad Arduino USB. The LilyPad Arduino Simple, LilyPad Arduino, LilyPad Development Board, and Development Board Simple all use a LilyPad ATmega 328. Select LilyPad USB Plus if following along with the LilyPad USB Plus or LilyPad ProtoSnap Plus. Don't forget to select the Serial Port that your LilyPad is connected to. Note the following potential code changes:
  • If prototyping with a LilyPad ProtoSnap Plus, change sensorPin to A2.
  • If prototyping with a LilyMini ProtoSnap, change sensorPin to 1.

Copy the following code and upload it to your LilyPad.

language:c
/******************************************************************************

LilyPad Light Sensor Example
SparkFun Electronics

This example code reads the input from a LilyPad Light Sensor and displays in
the Serial Monitor.

Light Sensor connections:
   * S tab to A2
   * + tab to +
   * - tab to -

******************************************************************************/

// Set which pin the Signal output from the light sensor is connected to
int sensorPin = A2;
// Create a variable to hold the light reading
int lightValue;

void setup()
{
    // Set sensorPin as an INPUT
    pinMode(sensorPin, INPUT);

    // Initialize Serial, set the baud rate to 9600 bps.
    Serial.begin(9600);
}

void loop()
{

   // Get the current light level
    lightValue = analogRead(sensorPin);

   // Print some descriptive text and then the value from the sensor
    Serial.print("Light value is:");
    Serial.println(lightValue);

    // Delay so that the text doesn't scroll too fast on the Serial Monitor. 
    // Adjust to a larger number for a slower scroll.
    delay(200);
}

Once your code is uploaded, open the serial terminal in the IDE and observe the output. Numbers should begin to stream by. Note how the numbers change as the ambient light changes. Use your hand to cover the sensor or a flashlight to shine more light on it. Next we’ll be using these values to control behaviors in our code.

Using Values to Trigger Behaviors

Next, we’ll make some decisions in the code based on the light sensor’s readings. This example code creates a simple automatic night light that turns on an LED when it’s dark.

We’ll use the analogRead() function to get data from the light sensor and compare it to a variable we set for darkness level. When the readings from the light sensor fall below our threshold set for dark, it will turn on the LED.

You can hook up a LilyPad LED to sew tab 5 or use the built-in LED attached to pin 13.

language:c
/******************************************************************************

LilyPad Light Sensor Trigger - Automatic Night Light
SparkFun Electronics

Adapted from Digital Sandbox Experiment 11: Automatic Night Light

This example code reads the input from a LilyPad Light Sensor compares it to
a set threshold named 'dark'. If the light reading is below the threshold,
an LED will turn on.

Light Sensor connections:
   * S tab to A2
   * + tab to +
   * - to -

Connect an LED to pin 5 or use the built-in LED on pin 13

******************************************************************************/
// The dark variable determines when we turn the LEDs on or off. 
// Set higher or lower to adjust sensitivity.
const int darkLevel = 50;

// Create a variable to hold the readings from the light sensor.
int lightValue;

// Set which pin the Signal output from the light sensor is connected to
int sensorPin = A2;

// Set which pin the LED is connected to. 
// Set to 5 if you'd rather hook up your own LED to the LilyPad Arduino.
int ledPin = 13;

void setup()
{
    // Set sensorPin as an INPUT
    pinMode(sensorPin, INPUT);

    // Set LED as outputs
    pinMode(ledPin, OUTPUT);

    // Initialize Serial, set the baud rate to 9600 bps.
    Serial.begin(9600);
}

void loop()
{
    // Read the light sensor's value and store in 'lightValue'
    lightValue = analogRead(sensorPin);

    // Print some descriptive text and then the value from the sensor
    Serial.print("Light value is:");
    Serial.println(lightValue);

    // Compare "lightValue" to the "dark" variable
    if (lightValue <= darkLevel) // If the reading is less then 'darkLevel'
    {
        digitalWrite(ledPin, HIGH); // Turn on LED
    }
    else // Otherwise, if "lightValue" is greater than "dark"
    {
        digitalWrite(ledPin, LOW);  // Turn off LED
    }

    // Delay so that the text doesn't scroll to fast on the Serial Monitor. 
    // Adjust to a larger number for a slower scroll.
    delay(100);
}

If your light sensor isn’t triggering correctly, check the output of the Serial Monitor to see if there’s a better value for the dark variable than what is set in the example code.

Sewing into a Project

Once you are finished prototyping your project using the LilyPad Light Sensor, you can replace any temporary connections with conductive thread.

For an overview of sewing with conductive thread, check out this guide:

LilyPad Basics: E-Sewing

December 17, 2016

Learn how to use conductive thread with LilyPad components.

To hide the sensor in your project, you can cover with a material making sure to leave an opening for the sensor to be exposed to light. Cutting a hole above the sensor in fabric is one way to do this.

Hole cut in fabric above light sensor


Hole cut in felt to allow sensor to take readings

Project Examples

Light Sensitive Hat

Let your geek shine with this hat that blinks when the lights go down.

Geek Hat

Geek Hat Detail

Musical Bracelet

Combining the sensor with a LilyPad Buzzer can create interesting interactive projects, for example this wearable light-controlled musical instrument or Opto-Theremin. Control tones on the buzzer by covering the LilyPad Light Sensor.

Musical Bracelet

Musical Bracelet

Twinkling Prom Dress

The prom dress project featured in this video uses an initial threshold setting and light sensor to trigger some LilyPad Pixel Boards.

LilyPad Safety Scarf

Create a scarf that lights up when it gets dark with LilyPad and sewable LED ribbon.

LilyPad Safety Scarf

November 21, 2017

This scarf is embedded with a ribbon of LEDs that illuminate when it gets dark out, making yourself more visible to vehicle and other pedestrians.

Resources and Going Further

Here are some resources for e-textiles and planning a project with the light sensor:

Or, you can check out these other great light-based tutorials:

Light

Light is a useful tool for the electrical engineer. Understanding how light relates to electronics is a fundamental skill for many projects.

FLIR Lepton Hookup Guide

See the invisible world of infrared radiation using the FLIR Dev Kit and Raspberry Pi.

PIR Motion Sensor Hookup Guide

An overview of passive infrared (PIR) motion detecting sensors, and how to hook them up to an Arduino.

DIY Light-Up Shoes

This tutorial provides everything you need to know to make your own light up high top sneakers!

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

Nuclear Battery Assembly Guide

$
0
0

Nuclear Battery Assembly Guide a learn.sparkfun.com tutorial

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

A Healthy Green Glow

Nuclear Battery Kit (Bring Your Own Tritium)

SPX-14773
$34.95

After we caught sight of some very cool folks online making their very own homemade nuclear batteries, we knew we had to give it a go!

These devices are actually known as “Radioisotope Photovoltaic Generators” or “Photobetavoltaic Generators,” and they’re a pretty clever design: Glowing glass pills filled with Tritium gas and coated in a phosphorescent material are sandwiched between two photovoltaic cells. The beta radiation emitted by the Tritium is blocked by the glass walls of the pill, but they cause the phosphorescent coating to glow. This light has no trouble passing through the glass and lands on the photovoltaic cells where it produces a small amount of electricity!

a commercially available betavoltaic generator, a 28-pin DIP package with a white body and a prominent radiation warning symbol

Image courtesy of citylabs.net

Commercial Tritium batteries — like those produced by City Labs— cut out the middleman by using betavoltaic (as opposed to photovoltaic) cells in direct contact with Tritium gas. Those commercial devices are more rugged and efficient, but come with a very large price tag (thousands of USD per unit).

A number of tiny glass tubes are shown sandwiched between two small solar cells. The assembly is held together with clear packaging tape.

Image courtesy of NurdRage

On the other hand, homemade devices constructed using the packing tape sandwich method are as cheap as it gets, but aren’t particularly rugged.

This kit provides a good compromise between price and quality of construction. We’ve designed carrier boards for both of the photovoltaic cells which we supply pre-soldered and fixed to the boards with chipbonder. We’ve also designed and cast custom silicone rubber grommets which cushion the Tritium vials between the two photovoltaic cells, preventing the cells from getting scratched or chipped and — most importantly — the vials from getting broken. The carrier boards also allow you to choose whether the photovoltaic cells are wired in series or parallel and provide you with breadboard compatible pin spacing for the battery terminals.

A Brief Word on Tritium Gas Lights

Several glowing green tritium tubes on a black background

Before you get started, you’ll need to get your hands on some 2x12mm Tritium glow vials, 10 of them. These are sold under various tradenames such as:

  • Mixglo
  • DaxLight
  • BETALight
  • Gaseous Tritium Light Source (GTLS)
  • Tritium Glow Tube
  • Tritium Gas Tube
  • Tritium Glow Vial

They’re easily found on sites such as ebay, banggood, aliexpress, etc. as well as certain specialty websites. Although their sale is regulated in many countries — and you should be aware of your local laws before attempting to procure any radioisotope — we didn’t have any trouble mail-ordering a small number of them in the US.

These Tritium Glow Tubes are perfectly safe to handle as the beta radiation generated from the Tritium decay cannot pass through the glass wall of the vial. Incidentally, the collision of the beta particles with the glass does produce a very tiny amount of x-rays, but not enough to harm anything. The only danger associated with Tritium gas is if it is inhaled, injected or otherwise inserted into the body which can only happen if you break the glass vial. If a vial does break, evacuate the room for a while to allow the gas to dissipate. Tritium occurs naturally in very small quantities and has a very short half-life compared with other glow products (such as radium) so breaking a glow vial will not turn your home into a superfund site.

If you’d like to learn more about Tritium Glow Tubes, you can check out this excellent blog post on how they’re made and how they’re used in watchmaking!

Some Assembly Required

Step 1 - Gather Materials

Grab your 2x12mm Tritium Gas Tubes, the contents of the Nuclear Battery Kit, some soldering supplies, and a breadboard (if you have one). It’s not a bad idea to polish the PV cells with a soft cloth and maybe your tritium vials as well just to remove any smudges or dust that could effect the efficiency of the PV cells.

All of the parts of the kit laid out on a gray background. Two white PCBs with PV cells centered on each, a pair of beige rectangular silicone gaskets, a strip of long pin headers, and a small pile of tritium glow tubes.

Step 2 - Attach Headers to the Top PCB

Your kit came with a strip of breakaway headers. You really just need four of them, but they sometimes get bent or don’t break off cleanly so we tossed in a bunch just to be safe. Use a pair of pliers or wire snips to break off four individual pins.

A hand holds a strip of pin headers while snipping one away using wire snips

This next part is easier if you have a breadboard to hold the pins in place while you work, but you can manage without one. In the picture below, I’ve stuck the pin headers into my breadboard long-side-down in preparation to solder them to my top PCB. You can tell which one is the top because it will have the SparkX logo as well as some solder jumpers on the side opposite the PV cell.

Four separate pin headers protrude from a small black breadboard.

Now simply solder each pin into place with a generous solder joint.

A hand holds a soldering iron in position to solder the pins in place on a white PCB

You can remove your soldered assembly and flip it upside-down in preparation for the next step:

The white PCB is belly-up now, showing the PV cell in its center and four protruding pins

Step 3 - Make the Stack

Now you need to grab one of the silicone rubber gaskets. It doesn’t matter which one because they’re identical. Place it with the flat side down and the pips facing up in the area marked “gasket” on the PCB.

The white PCB now has a beige rubber gasket on top.

This step can be a little finicky, but take your time and use tweezers if you need to. Place each of the 10 Tritium gas tubes into the rubber gasket. It helps to start at one end and move across. Place one end of each tube gently into a ridge on one side of the gasket and then gently press down until the other side slides into its corresponding ridge.

Tweezers being used to place Tritium gas tubes into grooves in the rubber gasket.

After all of the tubes are in place, you can press on them gently with a flat object to make sure they’re seated. They should look like this:

a row of glass vials rest on top of the rubber gasket, suspended above the PV cell underneath.

Now cap the tubes with the other rubber gasket, being sure to align the holes and pips so that they mate together.

A second rubber gasket has been added to the stack.

Finally, you can slide the bottom PCB onto the stack. Careful! Make sure that the board is oriented correctly. The “NC,” “+,” and “-” pin labels on both boards should line up!

The second white PCB has been added to the stack

Step 4 - Solder It All Together

For this step, you’ll want to apply some clamping force to the stack. Too much force will deform the rubber gaskets, causing the tubes to rattle loose in the assembly and you’ll need to re-build your stack. A small weight or a very weak binder clip should work, but I find masking tape is also acceptable.

The PCB on the top of the stack has been taped down to the workbench using masking tape to apply clamping force to the stack.

Now solder each of the four pins, these provide both the electrical connection between the PV cells and the mechanical connection which holds the generator together. Do not clip the headers after soldering as they will act as the leads for your battery.

A hand holds a soldering iron in position to solder the pins

Once you’re finished soldering, your battery is complete!

The completed battery stands upright on its pin headers.

A Little Bit of Power

a graph shows the calculated maximum power point of the PV cells in this configuration as described below.

So how much power does it make? Not much. The best measurement we were able to make (using the method outlined by NurdRage) suggests that the maximum power point of this arrangement is 25nW, if you can build a circuit that loads it properly (between 20 and 30nA at about 0.6v). Further experiments show that the battery will — given enough time — charge a capacitor to a voltage of 1.5 volts. Using this battery to do any work will likely involve a clever energy harvesting circuit, but keep in mind that this tiny amount of power will continue to flow for about 20 years — the half life of Tritium being 12 years.

This image is an invisible square but it's here so that I can ask you a favor if you're enjoying this tutorial using a screen reader. I'm trying to improve our site's accessibility, so I would love to hear your feedback about the image alt tags in this article. You can email me at nick.poole@sparkfun.com and please put the phrase "image tags" in the subject line. Thank you so much. Happy Hacking!


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

Qwiic Distance Sensor (VL53L1X) Hookup Guide

$
0
0

Qwiic Distance Sensor (VL53L1X) Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The VL53L1X is the latest Time Of Flight (ToF) sensor to be released. It uses a VCSEL (vertical cavity surface emitting laser) to emit a class 1 IR laser (940 nm) and time the reflection to the target. (You can’t see the laser but cell phones can) What does all this mean? You can measure the distance to an object up to 4 meters away with millimeter resolution! That’s pretty incredible.

SparkFun Distance Sensor Breakout - 4 Meter, VL53L1X (Qwiic)

SEN-14722
$19.95

We’ve found the precision of the sensor to be 1mm but the accuracy is around +/-5mm. The minimum read distance of this sensor is 4cm. In this hookup guide we’ll go over how to read distance, change ranging modes, and check the status of our range measurement along with the sample rate. We’ll also check out how to display distance and speed over an LCD display.

Required Materials

To get started, you’ll need a microcontroller to, well, control everything.

SparkFun RedBoard - Programmed with Arduino

DEV-13975
$19.95
32
SparkFun ESP32 Thing

DEV-13907
$19.95
52
Raspberry Pi 3

DEV-13825
$39.95
92
Particle Photon (Headers)

WRL-13774
$19.00
28

Now to get into the Qwiic ecosystem, the key will be one of the following Qwiic shields to match your preference of microcontroller:

SparkFun Qwiic Shield for Arduino

DEV-14352
$5.95
SparkFun Qwiic HAT for Raspberry Pi

DEV-14459
$4.95
1
SparkFun Qwiic Shield for Photon

DEV-14477
$4.95

You will also need a Qwiic cable to connect the shield to your distance sensor, choose a length that suits your needs.

Qwiic Cable - 200mm

PRT-14428
$1.50
Qwiic Cable - 100mm

PRT-14427
$1.50
Qwiic Cable - 500mm

PRT-14429
$1.95
Qwiic Cable - 50mm

PRT-14426
$0.95

Suggested Reading

If you aren’t familiar with our new Qwiic system, we recommend starting here for an overview.

QWIIC System Overview

We would also recommend taking a look at the following tutorials if you aren’t familiar with them.

Serial Communication

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

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.

Qwiic Shield for Arduino & Photon Hookup Guide

Get started with our Qwiic ecosystem with the Qwiic shield for Arduino or Photon.

Hardware Overview

First let’s check out some of the characteristics of the VL53L1X sensor we’re dealing with, so we know what to expect out of the board.

CharacteristicRange
Operating Voltage2.6V-3.5V
Power Consumption20 mW @10Hz
Measurement Range~40mm to 4,000mm
Resolution+/-1mm
Light SourceClass 1 940nm VCSEL
I2C Address0x52
Field of View15&deg - 27&deg
Max Read Rate50Hz

Pins

The following table lists all of the VL53L1X’s pins and their functionality.

PinDescriptionDirection
GNDGroundIn
3.3VPowerIn
SDADataIn
SCLClockIn
INTInterrupt, goes low when data is ready.Out
SHUTShutdown, can be pulled low to put the IC in shutdown mode.In

Optional Features

The VL53L1X breakout has pull up resistors attached to the I2C bus as well as the interrupt pin; both can be removed by cutting the traces on the corresponding jumpers on the back of the board, highlighted below.

Pullup Jumpers

The onboard LED (highlighted below) will light up when the board is powered, and the sensor (also highlighted below) should be left uncovered in your application.

Sensor and LED

Hardware Assembly

If you haven’t yet assembled your Qwiic Shield, now would be the time to head on over to that tutorial. Depending on the microcontroller and shield you’ve chosen, your assembly may be different, but here’s a handy link to the Qwiic Shield for Arduino and Photon Hookup Guide to get you started!

Qwiic Shield for Arduino Photon Hookup Guide

With the shield assembled, SparkFun’s new Qwiic environment means that connecting the sensor could not be easier. Just plug one end of the Qwiic cable into the VL53L1X breakout, the other into the Qwiic Shield and you’ll be ready to upload a sketch and figure out how far away you are from that thing over there. It seems like it’s too easy too use, but that’s why we made it that way!

Connected to Qwiic Shield

SparkFun RedBoard and Qwiic Shield with the Qwiic Distance Sensor Attached

Library Overview

Note: This example assumes you are using the latest version of the Arduino IDE on your desktop. If this is your first time using Arduino, please review our tutorial on installing the Arduino IDE. If you have not previously installed an Arduino library, please check out our installation guide.

First, you’ll need the Sparkfun VL53L1X Arduino library. You can obtain these libraries through the Arduino Library Manager. Search for Sparkfun VL53L1X Arduino Library to install the latest version. If you prefer downloading the libraries from the GitHub repository and manually installing it, you can grab them here:

DOWNLOAD THE SPARKFUN VL53L1X ARDUINO LIBRARY (ZIP)

Before we get started developing a sketch, let’s look at the available functions of the library.

  • boolean begin(uint8_t deviceAddress = defaultAddress_VL53L1X, TwoWire &wirePort = Wire);— By default use the default I2C address, and use Wire port
  • void softReset();— Reset the sensor via software
  • void startMeasurement(uint8_t offset = 0);— Write a block of bytes to the sensor to configure it to take a measurement
  • boolean newDataReady();— Checks if a measurement is ready.
  • uint16_t getDistance();— Returns the results from the last measurement, distance in mm
  • uint16_t getSignalRate();— Returns the results from the last measurement, signal rate
  • void setDistanceMode(uint8_t mode = 2);— Sets distance mode (0 = short, 1 = medium, 2 = long)
  • uint8_t getDistanceMode();— Returns the distance mode
  • uint8_t getRangeStatus();— Returns the results from the last measurement, 0 = valid

Example Code

Now that we have our library installed and we understand the basic functions, let’s run some examples for our distance sensor to see how it behaves.

Example 1 - Read Distance

To get started with the first example, open up File>Examples>SparkFun VL53L1x 4M Laser Distance Sensor>Example1_ReadDistance. In this example, we begin by creating a VL53L1X object called distanceSensor and then initializing our sensor object in the setup() loop. The code to do this is shown below and is repeated in some form in all of the examples.

language:c
VL53L1X distanceSensor;

void setup(void)
{
  Wire.begin();

  Serial.begin(9600);
  Serial.println("VL53L1X Qwiic Test");

  if (distanceSensor.begin() == false)
    Serial.println("Sensor offline!");

}

Once we’ve initialized our sensor, we can start grabbing measurements from it. To do this, we send some configuration bytes to our sensor using distanceSensor.startMeasurement() to initiate the measurement. We then wait for data to become available and when it does, we read it in, convert it from millimeters to feet, and print it out over serial. The void loop() function that does this is shown below.

language:c
void loop(void)
{
  distanceSensor.startMeasurement(); //Write configuration bytes to initiate measurement

  //Poll for completion of measurement. Takes 40-50ms.
  while (distanceSensor.newDataReady() == false)
    delay(5);

  int distance = distanceSensor.getDistance(); //Get the result of the measurement from the sensor

  Serial.print("Distance(mm): ");
  Serial.print(distance);

  float distanceInches = distance * 0.0393701;
  float distanceFeet = distanceInches / 12.0;

  Serial.print("\tDistance(ft): ");
  Serial.print(distanceFeet, 2);

  Serial.println();
}

Opening your serial monitor to a baud rate of 9600 should show the distance between the sensor and the object it’s pointed at in both millimeters and feet. The output should look something like the below image.

Read Distance

Distance readings in mm and ft

Example 2 - Set Distance Mode

In this example, we’ll change the distance mode of the VL53L1X. The default long range mode is the most robust as far as sample rate and range are concerned, but for a slightly higher sample rate, you can bring the range down to medium (~3M) or short (~2M). To get started with the second example, open up File>Examples>SparkFun VL53L1x 4M Laser Distance Sensor>Example2_SetDistanceMode. The main difference between this example and the previous example is that after we initialize our sensor in the setup() loop, we first declare ints shortRange - 0, midRange = 1 and longRange = 2 to assign the proper values to our ranges. We then call distanceSensor.setDistanceMode(shortRange) to change the range of our sensor to short range. Although this feature is available, we’d recommend sticking with long range as it is the most robust.

Example 3 - Status and Rate

In the third example, we’ll read and average our distance as well as read the sample rate and status of each measurement. To get started with the third example, open up File>Examples>SparkFun VL53L1x 4M Laser Distance Sensor>ExampleStatusandRate. The status of a measurement can be any of 8 values. Our void loop() interprets the value returned by distanceSensor.getRangeStatus() and prints that value over serial. The below table shows the possible values of rangeStatus and their corresponding errors.

Range StatusError
0Valid measurement
1Raised if sigma estimator (uncertainty in measurement) check is above the internal defined threshold
2 Raised if signal value is below the internal defined threshold
4Raised when phase is out of bounds
5Raised in case of HW or VCSEL failure
7Wrapped target, not matching phases
8Internal algorithm underflow or overflow
14The reported range is invalid

In the example code, notice how the sketch stores our previous values in the array history so that the average distance can also be calculated. Uploading this sketch to your microcontroller and opening the serial monitor to a baud rate of 9600 should give you an output similar to the image shown below.

Status and Rate

Click the image for a closer look.

Example 4 - LCD Demo

The fourth example requires a serial enabled LCD screen for us to write our distance values to. If you haven’t played around with a Serial enabled LCD before, checkout our hookup guide on the matter. To get started with the fourth example, open up File >Examples>SparkFun VL53L1x 4M Laser Distance Sensor>Example4_LCDDemo. We’ll first need to connect the RX pin of our Serial LCD to pin A3 on our Arduino. Connect 5V and ground on the LCD and the backlight should light up. Notice how we also include the SoftwareSerial library. Uploading the sketch to our Arduino then takes in our sample rate and distances. By using these values, it calculates a velocity. Like the sketch before, distances are stored in an array. The sketch uses these values in the array to calculate velocity and the velocity is then displayed along with the current distance on the LCD. The output on the LCD should look something like the below GIF.

LCD Distance Display

Resources and Going Further

Now that you’ve successfully got your Qwiic Distance Sensor up and running, it’s time to incorporate it into your own project!

For more information, check out the resources below:

Want a great use case for your ToF sensor? How about integrating one into your AVC submission? Have a look here:

Need even more inspiration for your next project? Check out some of these related tutorials:

New!

Qwiic Differential I2C Bus Extender (PCA9615) Hookup Guide

Learn how to extend the range of your I2C communication bus with the Qwiic differential I2C bus extender (PCA9615 ) breakout board.

Qwiic Shield for Arduino & Photon Hookup Guide

Get started with our Qwiic ecosystem with the Qwiic shield for Arduino or Photon.

Qwiic Human Presence Sensor (AK9753) Hookup Guide

How to get started with your Qwiic enabled AK9753 Human Presence Sensor.

Qwiic Micro OLED Hookup Guide

Get started displaying things with the Qwiic Micro OLED.

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

Current Sensor Breakout (ACS723) Hookup Guide

$
0
0

Current Sensor Breakout (ACS723) Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The ACS723 is a handy little current sensor from Allegro MicroSystems for low to moderate current sensing applications. SparkFun offers two flavors of breakout board, one with just the sensor and another with an on-board amplifier to increase the sensitivity.

SparkFun Current Sensor Breakout - ACS723

SEN-13679
$7.95
SparkFun Current Sensor Breakout - ACS723 (Low Current)

SEN-14544
$14.95

The ACS723 sensor uses a Hall effect sensor to output a voltage relative to the current flowing through the IP+ and IP- pins. The advantage of using a Hall effect sensor is that the circuit being sensed and the circuit reading the sensor are electrically isolated. This means that, although your Arduino is running on 5V, the sensed circuit can be operating at higher DC or AC voltages!

The amplified breakout board (Low Current) is capable of sensing very small currents down to around 10mA and large currents up to 5A! However, since the output is analog, your usable readings will be limited by noise and the resolution of the ADC reading the output. This sensor is not recommended for current sensing lower than 10’s of milliamps.

Required Materials

Depending on the equipment available to you, you will need some of the following items to follow along with this hookup guide:

Suggested Reading

Here are some topics related to this hookup guide you may want to review:

Voltage, Current, Resistance, and Ohm's Law

Learn about Ohm's Law, one of the most fundamental equations in all electrical engineering.

How to Power a Project

A tutorial to help figure out the power requirements of your project.

Electric Power

An overview of electric power, the rate of energy transfer. We'll talk definition of power, watts, equations, and power ratings. 1.21 gigawatts of tutorial fun!

Series and Parallel Circuits

An introduction into series and parallel circuits.

How to Use a Multimeter

Learn the basics of using a multimeter to measure continuity, voltage, resistance and current.

There’s also a great tutorial from Shawn Hymel explaining electromagnetism and magnets:

The Hall Effect and Current Sensors

This section provides a quick recap of the electromagnetic concepts that make this current sensor possible. How does this little chip take current from one circuit and produce a proportional output voltage without physically connecting the two circuits?

Faraday’s Law of Induction

In the ACS723, sensing current starts with the phenomenon known as Faraday’s Law of Induction. This phenomenon, first discovered by Michael Faraday in 1831, is one of the foundations of modern radio and electromagnetics. This law describes how an electrical current flowing in a conductor creates a surrounding magnetic field, and how a changing magnetic field can create, or induce, a current in a conductor. This is how antennas pick up radio waves!

Faraday's Law

Illustration of the magnetic field created around a conductor with a current flowing through it (Photo courtesy of http://www.tesla-institute.com)

The current pins of the ACS723 are internally connected to a big trace of copper, allowing a lot of electricity to flow through this part of the chip. When current flows through the copper strip, a magnetic field is created around the trace with a strength proportional to the current.

The Hall Effect

The next step in sensing current is based on the Hall effect - a very useful phenomenon discovered by Edwin Hall in 1879. In basic terms, the Hall effect produces a voltage difference across a conductor in the presence of a magnetic field. This provides a neat way of sensing nearby magnetic fields and has many applications. For example, Hall effect sensors are used in some car engines to detect where in a rotation cycle the camshaft or crankshaft are.

Hall Effect Animation

Animation showing how a magnetic field creates a voltage difference. The blue circles are electrons flowing (Photo courtesy of http://www.explainthatstuff.com/hall-effect-sensors.html)

The ACS723 has an internal Hall effect sensor placed next to the aforementioned copper strip. When current flows through this copper strip, a magnetic field is created. This magnetic field is then sensed by the Hall effect sensor and produces a voltage output that is proportional to the input current!

Hall Effect current sensor

Illustration of how the current sensor looks internally (Photo courtesy of Allegro Micro)

This method of sensing allows the sensing circuit to be electrically isolated from the sensed circuit. Practically, this means that since the circuits aren’t physically connected, you can use a low-power Arduino to measure the current going through a high power device, even one that uses AC power!

Hardware Overview

This section will explore the various segments of the breakout with particular emphasis on the Low Current version.


ACS723 Breakout Board closeupACS723 Low Current Breakout Board closeup

ACS723 Breakout Details:

Both versions of this breakout board have the following attributes:

  • Analog output with bandwidth adjustable to 80kHz.
  • The bandwidth on the ACS723 Sensor Breakout width filter has been set to 20kHz to reduce noise when using at high gains. The full 80KHz bandwidth that the sensor is capable of can be recovered by closing the JP1 (Bandwidth Select) jumper on the back of the board. See either the ACS723 schematic or the ACS723 Low Current schematic for more details.
  • Measures DC and AC currents from around 10mA up to 5A
  • Full electrical isolation of measured and sensed circuits
  • The version without the op-amp has a base sensitivity of 400mV/A

In addition to the above, the Low Current Sensor Board has the following:

  • Adjustable sensitivity with on-board amplifier, gain from 2.2 to 22 V/V
Please Note: Although the chip itself is rated for up to 2.4kV (RMS) of isolation, the board has not been designed for such high voltage applications.

Below is a list of all the pins broken out on the ACS723 and their functions.

SymbolDescription
IP+High side of current sensor
IP-Low side of current sensor
GNDMust be connected to ground
VoVoltage output proportional to current flowing through IP+ and IP-
VCC5V power supply

To measure a current using this device, the current must flow through the IP+ terminal and out the IP- terminal (it will work in the other direction, but the measurement will be negative). IE: These terminals must be in series with the circuit that the measured current is flowing through. Note that both IP+ and both IP- terminals are connected to each other, you can use either (or both) of them.

Amplification (Low Current Sensor):

The amplified version of the breakout board (ACS723-Low Current) has two potentiometers on it: Vref and Gain.

The Vref potentiometer sets the baseline voltage output. In other words, it adjusts the voltage seen at Vo when there is no current flowing through the sensor (0 mA). This allows the sensor to output negative current readings as well as positive.

ACS723 Vref Potentiometer

Vref potentiometer, highlighted

The gain potentiometer sets the sensitivity of the device. For example, if the gain is set high, then a smaller current will cause the voltage output to increase more, giving you higher sensitivity and allowing you to sense smaller currents.

ACS723 Gain Potentiometer

Gain potentiometer, highlighted

However, there are a couple caveats:

  1. With higher gain you will see more noise (spikes) on the output, so smaller currents will be harder to measure accurately.
  2. If you are trying to measure larger currents with a high gain setting, your output will saturate or clip and reach the maximum 5V or 0V.

With that in mind, to get meaningful data from the current sensor, you must configure the Vref and Gain potentiometers properly.

Calibration and Example Code

Note: This example assumes you are using the latest version of the Arduino IDE on your desktop. If this is your first time using Arduino, please review our tutorial on installing the Arduino IDE.

An example sketch for Arduino is included below to help you get started with the ACS723 Low Current Sensor. It will help you set the potentiometers and perform calculations to convert raw ADC readings into the actual current in mA. While parts are specific to the ACS723 Low Current Sensor, the main body of the sketch should work for the ACS723 Current Sensor as well.

To properly calibrate the ACS723 breakout board, you should first consider what type and range of currents you want to measure.

Choosing the Range

If you are going to be dealing mainly with DC, positive currents, you can adjust Vref to the lower end of its range. If you are trying to measure AC currents, you will want to keep Vref about in the middle at 2.5V. This lets your output swing equally in the positive and negative directions.

The gain setting will depend on the range of currents you want to measure. If you want to measure a current between 100mA and 500mA, you will want to set the gain so the sensitivity is something like 250mV/100mA (you will learn how to do this in the following steps).

Setting Vref

To get started, copy and upload the sketch below to your Arduino. You can also find the latest files in the GitHub repository.

language:c
/*  SparkFun ACS712 and ACS723 Demo
    Created by George Beckstein for SparkFun
    4/30/2017
    Updated by SFE
    6/14/2018

    Uses an Arduino to set up the ACS712 and ACS723 Current Sensors
    See the product page at: https://www.sparkfun.com/products/8883

    Parts you may need:
    - 100 Ohm, 1/2W or greater resistor OR two 220 Ohm 1/4 resistors in parallel
    - ACS712 Breakout with on-board amplifier or ACS723 Current Sensor (Low Current)

    Optional equipment:
    - Oscilloscope
    - Multimeter (or two)
    - A power supply with current limiting/constant current would be handy to calibrate the device without using resistors
*/

const int analogInPin = A0;

// Number of samples to average the reading over
// Change this to make the reading smoother... but beware of buffer overflows!
const int avgSamples = 10;

int sensorValue = 0;

float sensitivity = 100.0 / 500.0; //100mA per 500mV = 0.2
float Vref = 2500; // Output voltage with no current: ~ 2500mV or 2.5V

void setup() {
  // initialize serial communications at 9600 bps:
  Serial.begin(9600);
}

void loop() {
  // read the analog in value:
  for (int i = 0; i < avgSamples; i++)
  {
    sensorValue += analogRead(analogInPin);

    // wait 2 milliseconds before the next loop
    // for the analog-to-digital converter to settle
    // after the last reading:
    delay(2);

  }

  sensorValue = sensorValue / avgSamples;

  // The on-board ADC is 10-bits -> 2^10 = 1024 -> 5V / 1024 ~= 4.88mV
  // The voltage is in millivolts
  float voltage = 4.88 * sensorValue;

  // This will calculate the actual current (in mA)
  // Using the Vref and sensitivity settings you configure
  float current = (voltage - Vref) * sensitivity;

  // This is the raw sensor value, not very useful without some calculations
  //Serial.print(sensorValue);

  /*************************************************************************************
   * Step 1.)
   * Uncomment and run the following code to set up the baseline voltage 
   * (the voltage with 0 current flowing through the device).
   * Make sure no current is flowing through the IP+ and IP- terminals during this part!
   * 
   * The output units are in millivolts. Use the Arduino IDE's Tools->Serial Plotter
   * To see a plot of the output. Adjust the Vref potentiometer to set the reference
   * voltage. This allows the sensor to output positive and negative currents!
   *************************************************************************************/

  Serial.print(voltage);
  //Serial.print("mV");

  /*************************************************************************************
   * Step 2.)
   * Keep running the same code as above to set up the sensitivity
   * (how many millivolts are output per Amp of current.
   * 
   * This time, use a known load current (measure this with a multimeter)
   * to give a constant output voltage. Adjust the sensitivity by turning the
   * gain potentiometer.
   * 
   * The sensitivity will be (Vreading - Vref)/(known current).
   *************************************************************************************/

    /*************************************************************************************
   * Step 3.)
   * Comment out the code used for the last two parts and uncomment the following code.
   * When you have performed the calibration steps above, make sure to change the 
   * global variables "sensitivity" and "Vref" to what you have set up.
   * 
   * This next line of code will print out the calculated current from these parameters.
   * The output is in mA
   *************************************************************************************/

  //Serial.print(current);
  //Serial.print("mA");


  // -- DO NOT UNCOMMENT BELOW THIS LINE --
  Serial.print("\n");

  // Reset the sensor value for the next reading
  sensorValue = 0;
}

This sketch reads the voltage on pin A0 and prints it to the serial terminal. In later steps you will learn how to get actual current readings with this sketch.

To set up Vref, the sensor should have no current flowing through it! For this part, you only need to connect the ACS723’s GND pin to Ground, VO pin to pin A0 on the SparkFun RedBoard (or equivalent), and 5V to the 5V pin on the RedBoard. If you have one available, it may be useful to also read the output voltage using a multimeter. See the Fritzing diagram below for more information:

Adjusting Vref Circuit

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

If you aren’t using a multimeter to set Vref, open up the Arduino IDE’s serial plotter by clicking Tools->Serial Plotter. This will show the voltage reading from the Arduino in real time. The units are in millivolts.

Turn the Vref potentiometer clockwise to increase Vref and counter-clockwise to decrease. Make small adjustments, as the adjustment is very sensitive!

Note: Using metal/magnetized screwdrivers may cause the sensor to give false readings. This is because the Hall effect sensor inside is picking up the magnetic fields from the screwdriver. You may want to use a plastic screwdriver to eliminate this effect. I made one out of an old guitar pick with some scissors!

In the Serial Plotter, you should see something like this:

Vref Animation

Using the RedBoard and Arduino, you can plot the output voltage as you adjust Vref

Tune Vref to about where you want it, for example 2500mV.

Setting Gain and Sensitivity

To set the gain, you need to pass a known current through the sensor and tune the gain pot to achieve the sensitivity your application needs.

For example, if you want to measure between 100mA and 500mA, you should shoot for a sensitivity of around 250mV/100mA. To do this, you can pass 100mA through the sensor, and adjust the gain pot until the output voltage is 250mV above your set Vref.

For those of you who have a benchtop power supply with a current limiter/constant current (CC) mode, getting this 100mA current is easy. In this case, you can simply connect the positive terminal of the power supply to the IP+ pin and the negative terminal of the power supply to the IP- pin. Make sure your current limit is set to something reasonable (NOT above 5A), and turn the power on. Adjust the output to a constant 100mA current for use in adjusting the gain.

If you don’t have a power supply, all you need are some resistors (like in this nifty resistor kit, or these power resistors for more power dissipation). To make a fixed, known current, just use Ohm’s Law!

If you want a 100mA current from a 5V source you need (5/0.1) = 50Ω

You should keep in mind how much power your resistors can handle though! If not, they’ll end up a bit toasty… With 5V and 100mA, the power would be 500mW or 1/2W. The small resistors in the kit above can only handle 250mW or 1/4W at most. But, wait! A resourceful engineer knows you can still use the 1/4W resistors, you just need to split the power dissipation. By placing equal resistors in parallel, you can increase the maximum allowable power dissipation; each resistor just adds their power rating. IE: 1/4W resistor + 1/4W resistor = 1/2W capacity! Keep in mind that the equivalent resistance will be lower though.

500mW is still a lot of power for these 1/4W resistors, so I recommend using only 50mA to tune the gain, unless you have the power resistors linked to above.

To get 50mA from 5V, you need 100Ω. Using parallel resistances, you need double that, or around 220Ω. You may want to use your multimeter to make sure the current flowing through the circuit is indeed 50mA. The tolerances of resistors can alter this current. To measure current with your multimeter, make sure to connect it in series! To see a diagram of how to build the circuit for setting the gain, see the Fritzing diagram below:

Adjusting Gain Circuit

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

With a known, constant current flowing through the sensor, the gain can be adjusted. The same sketch can be used as last time. Open up the Serial Plotter again. To set the gain, disconnect one of the wires to break the current sensing circuit. When you reconnect it, see how much the output voltage increases. Subtract this from your Vref, to keep the voltage change (also known as delta). So, if you have 50mA flowing in the circuit, you want this change to be about 125mV for the 250mV/100mA sensitivity example. An example is shown below:

Gain Adjust Delta Plot

Adjust the change (Vdelta) to what you need it to be by tuning the gain potentiometer. As mentioned above, this affects the noise (spikiness) you see in the output:

Gain Adjust Noise

As the gain increases, the spiky noise gets bigger (and the Vref changes slightly)

Note: Adjusting the gain pot also changes the Vref setting slightly; you need to take this into account when you do your calculations. You should measure your final Vref and sensitivity with a multimeter after calibration.

Once you have Vref and the sensitivity settings selected, you can modify the code in the example sketch to print out your current readings in milliamps! Follow step 3 in the code comments to learn how to do this. Make sure to change the sensitivity and Vref variables to what you have set so the code can calculate the current properly.

Resources and Going Further

The ACS723 sensor is ideal if you need to measure a small to moderate amount of current, especially if it’s AC current! For more information about the ACS723, check out the links below:

If you don’t need electrical isolation and want to measure smaller currents, check out the INA169 Breakout Board. And for even higher power applications, check out the Non-Invasive Current Sensor - 30A.

Non-Invasive Current Sensor - 30A

SEN-11005
$9.95
16
SparkFun Current Sensor Breakout - INA169

SEN-12040
$8.95
1

For more power related learning, check out the tutorials below:

Battery Technologies

The basics behind the batteries used in portable electronic devices: LiPo, NiMH, coin cells, and alkaline.

Benchtop Power Board Kit Hookup Guide

Need more power? This Benchtop ATX Power Supply Kit should help give you the boost you need to power those energy hungry projects.

Beefcake Relay Control Hookup Guide

This is a guide for assembling and basic use of the Beefcake Relay Control board
New!

Nuclear Battery Assembly Guide

How to put together your BYOT (Bring Your Own Tritium) Nuclear Battery Kit!

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

Rotary Dial Kit Assembly Guide

$
0
0

Rotary Dial Kit Assembly Guide a learn.sparkfun.com tutorial

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

A Simple Interface

Rotary Dial Kit

SPX-14790
$24.95

The Rotary Dial Kit is designed to be a simple interface device for your project. Input is achieved using a rotating encoder bezel and output is handled by a ring of addressable RGB LEDs along the inside edge of the ring. Two keyhole hangers are milled into the back of the Rotary Dial so it can be wall mounted.

The design was inspired by the rotating bezel on my Samsung Gear smartwatch as well as wall-mounted IoT devices such as the Nest thermostat.

To assemble the kit, you’ll need:

  • A small Philips screwdriver
  • A soldering iron and some solder (a flux pen helps too!)
  • Pliers or Tweezers are handy but not necessary

Assembly

Step 1 - Count Your Parts!

Make sure you have everything that you need. The kit includes three PCBs, three pogo pins, four 4-40 bolts, four 4-40 nuts and four ¼" standoffs.

top down shot of all kit components as described above

Step 2 - Solder the Pogo Pins

The trickiest part of the assembly will be soldering these pins. It’s not too tough, though, so let’s get it out of the way now! Start off by applying some flux to each pad, if you have it.

Close up of a hand holding a flux pen and applying flux to one of the small solder pads on the base board in preparation for soldering the pogo pin.

Then place a pogo pin on it’s pad and center it as best you can. Don’t worry too much about it because it will self-center if you add enough solder. Very carefully apply solder to the pad and allow it to flow to the pin. Add enough solder so that there is a rounded pool around the base of the pin. Once you have a small blob of solder, pull the iron away swiftly and smoothly, careful not to knock over the pogo pin. The surface tension of the still-molten solder should drag the pogo pin to the center of the pad.

Close up view of a soldering iron tip making the necessary solder joint

Check to make sure that the pin is aligned vertically. It doesn’t need to be perfectly perpendicular to the board, but it should be sticking relatively straight up. You may need to brag the pin with some tweezers, reheat the solder, and press it down onto the pad to get it aligned.

Macro shot of the completed solder joint showing an abundance of solder forming a rounded base around the pogo pin.

Repeat this process for each pin.

Step 3 - Add Some Solder to the Standoff Holes

The bolts that hold the assembly together are also the signal route for the RGB LEDs on the retainer ring, so it’s important to create a good electrical connection. To aid in this, add a little bit of solder to the face of each standoff hole on the back of the base board and the front of the retainer board. Make sure not to overdo it and make the hole too tight for the bolt to go through. The goal is to make a little bump for the nut or the head of the bolt to tighten against.

Hands hold a soldering iron and a length of solder against the exposed copper surrounding a standoff hole in the base board

Step 4 - Build your Sandwich!

Now it’s time to stack everything together! There are probably a lot of ways to accomplish this, but this is the way I find easiest.

Start by putting the 4-40 bolts through the front of the retainer ring (the board with the LEDs on it) so that the LEDs are on the opposite side from the head of the bolts. Now set this aside and place your base board with the pogo pins facing up.

A ring shaped board is laying face up to the right with LEDs on its face and bolts protruding toward the camera. In the center of the photo another round board is sitting with pogo pins facing up. A hand holds another ring shaped board overtop of the round board.

Carefully place a nylon standoff over each of the four standoff holes and place the ring pcb with the shiny side facing up and the tracks facing down onto the pogo pins.

The larger ring shaped board is now sitting on top of the round board with four nylon standoffs sitting along its inside circumference. The LED ring still sits to the side.

Now pick up your LED retainer board and carefully place it on top, threading each bolt through its corresponding standoff. To get the orientation right, make sure you’ve lined up the hole on the base board that doesn’t have a ring around it with the hole on the LED ring that doesn’t have a ring around it. If your orientation isn’t right, the LED ring won’t work.

Two hands hold the LED ring, now in position on top of the stack with LEDs facing down.

Carefully lift the entire stack and place the nuts on the end of the bolts. Tighten everything down firmly but not crazy tight.

Side view of the stack as it is held and the nuts are tightened onto the backside of the assembly.

Step 5 - Enjoy!

top down view of the completed assembly. A round contraption with a notched ring along the outside, trapped in place by a top retaining ring. You can see through the center of the retaining ring to the base board below which is covered in white silkscreen. This is designed to reflect the LEDs which are mounted on the underside of the retaining ring.

You can now solder some wires or pin headers to the 5-pin header on the base board and hook it up to your project!

Example Code

Here are two simple Arduino examples to get you started. Both of them have been tested to work with the SparkFun RedBoard with the following connections:

RedBoardRotary Dial
GNDGND
5V5V
D8LED IN
D5ENC A
D6ENC B

Both examples also make use of the PJRC Encoder Library and the Adafruit NeoPixel Library.

Example 1 - Color Wheel

This example uses pieces of the NeoPixel example code combined with pieces of the Encoder example code to implement a color selector. As you turn the encoder wheel one direction or the other, you will cycle through the RGB color space on all eight RGB LEDs at once.

#include <Adafruit_NeoPixel.h>
#include <Encoder.h>

Encoder myEnc(5, 6);

Adafruit_NeoPixel strip = Adafruit_NeoPixel(8, 8, NEO_GRB + NEO_KHZ800);

void setup() {
  strip.begin();
  strip.show();
}

long oldPosition  = -999;

void loop() {
  long newPosition = myEnc.read();
  if (newPosition != oldPosition) {
    oldPosition = newPosition;

    for(int i = 0 ; i < 8; i++){
      strip.setPixelColor(i, Wheel((newPosition*5) & 255));
    }

    strip.show();

  }

}

// Input a value 0 to 255 to get a color value.
// The colours are a transition r - g - b - back to r.
uint32_t Wheel(byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if(WheelPos < 85) {
    return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
  }
  if(WheelPos < 170) {
    WheelPos -= 85;
    return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
  }
  WheelPos -= 170;
  return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}

Example 2 - Rotary Selector

This example is almost identical except that as you turn the encoder ring, only one LED will light at a time, moving in the same direction that you turn the ring.

#include <Adafruit_NeoPixel.h>
#include <Encoder.h>

Encoder myEnc(5, 6);

Adafruit_NeoPixel strip = Adafruit_NeoPixel(8, 8, NEO_GRB + NEO_KHZ800);

void setup() {
  strip.begin();
  strip.show();
}

long oldPosition  = -999;

void loop() {
  long newPosition = myEnc.read();
  if (newPosition != oldPosition) {
    oldPosition = newPosition;

    for(int i = 0 ; i < 8; i++){
      strip.setPixelColor(i, 0);
    }

    int dot = abs(newPosition)%8;
    strip.setPixelColor(dot, Wheel((newPosition*5) & 255));
    strip.show();

  }

}

// Input a value 0 to 255 to get a color value.
// The colours are a transition r - g - b - back to r.
uint32_t Wheel(byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if(WheelPos < 85) {
    return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
  }
  if(WheelPos < 170) {
    WheelPos -= 85;
    return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
  }
  WheelPos -= 170;
  return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}

This image is an invisible square but it's here so that I can ask you a favor if you're enjoying this tutorial using a screen reader. I'm trying to improve our site's accessibility, so I would love to hear your feedback about the image alt tags in this article. You can email me at nick.poole@sparkfun.com and please put the phrase "image tags" in the subject line. Thank you so much. Happy Hacking!


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>