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

Roshamglo Hookup Guide

$
0
0

Roshamglo Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

SparkFun Roshamglo Badge Kit

KIT-14130
12.95

The Roshamglo Badge Kit is an easy to assemble badge that allows you to play Rock-Paper-Scissors with an opponent using infrared (IR) communication. The Roshamglo will also keep track of your score, which you can upload to the scoreboard station and see how you’re doing against other people at the event.

Required Materials

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

Suggested Reading

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

IR Communication

This tutorial explains how common IR communication works, as well as shows you how to set up a simple IR transmitter and receiver.

What is an Arduino?

What is this 'Arduino' thing anyway?

How to Solder: Through-Hole Soldering

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

How to Install an ATtiny Bootloader With Virtual USB

With this, you will be able to upload Arduino sketches directly to the ATtiny84 over USB without needing to use a programming device (such as another Arduino or FTDI chip).

Hardware Overview

Roshamglo labels

The Roshamglo uses the following:

  • ATtiny84
  • IR LED
  • IR receiver with built in 38kHz demodulator
  • USB programming
  • Programmable red and green LED
  • A switch for power
  • 5-way switch for input
  • Reset switch
  • 6x AAA PTH battery clips
  • 3x AAA batteries for power

The brains behind the Roshamglo is an ATtiny84, a light weight Arduino compatible microcontroller. The ATtiny84 comes with the following:

  • 8kB of flash memory for our program (~6kB after the bootloader is installed)
  • 512B of SRAM, which stores our variables used in our program
  • 512B of EEPROM
  • 12 IO pins MAX (the Roshamglo breaks out 9 of these pins)
  • 10-bit analog to digital converter which can be used on 8 pins

For details about what each pin is able to do, refer to the table below.

PinAnalog or DigitalAdditional UsesRoshamglo Uses
0Both Analog Reference5-way switch down
1Both --5-way switch right
2Both --5-way switch up
3Both --IR Receiver
4Both SCK, SCL5-way switch left
5Both MISO, PWMIR LED
6Both MOSI, SDA, PWM5-way switch center
7Both PWMGreen LED
8Digital PWMRed LED
Missing from the list, are digital pins 9 and 10. The bootloader, uses these two pins for USB programming.

Jumpers and Pins Highlighted

Each of these pins have been broken out to edge of the board to make customization easy! If you would like to use any of these pins for something other than what it’s currently connected two, we provided jumpers that can easily be cut with a hobby knife. The only pins that do not have a jumper on them are the pins used for the 5-way switch. The pins for the switch use the ATtiny’s internal pull up resistors, so as long as the switch is not closed, the pin can be configured in any way you’d like without having to cut traces.

One important feature missing

If you hadn’t noticed in the pin description, there was no mention of RX or TX pins. This is because unfortunately the ATtiny84 doesn’t have a hardware UART. The UART is used for serial communication, whether it’s for programming, or printing messages to the serial window. You might be thinking “But doesn’t the USB connector provide communication between the ATtiny and computer?”, and you’re right; it does. To keep the bootloader size as small as possible, the bootloader only allows for USB programming. For serial debugging, you’ll need a USB cable and a USB-to-Serial adapter, and Software Serial library to send messages to a computer. You can learn more about serial communication here.

Hardware Assembly

To use your Roshamglo, all that’s needed is to solder in the battery clips. To insert the battery clips, you’ll need to turn the board to the side with the pictures of the batteries and push the battery clips into the holes. Make sure that the metal tab on the ends are facing away from the center of the board.

Highlight of battery solder joints

Make sure the battery clips aren’t touching each other! To make sure they won’t short against each other, make sure the clips sit flat against the circuit board.

After the clips are installed, you can turn the board over and solder all of the joints on the top side of the board. When they’re all soldered together, they should look like this:

Roshamglo Soldered

Installing the batteries are easy, but as you install the batteries, make sure you insert the batteries in the same orientation as the silkscreen image between each pair of battery clips. After the batteries are installed, you’re all set! You can move the switch on the left side of the board to “ON”, and you should see the red power LED come on.

Highlight of Battery Orientation

How to Use the Roshamglo

To use the Roshamglo, first make sure that the board is on. When you move the power switch to “ON”, the red LED should illuminate.

How to Play

Playing the game is very straight forward, next to the 5-way switch are three images that correspond to your three possible moves: rock, paper, and scissors. To set your move as rock, you will push the switch to the left towards the rock image. Paper and scissors are played the same way, but this time towards their corresponding images. When you move the switch, the green LED will flash quickly every time the IR LED sends a signal. Once the LED starts to blink, you’ll want to point the USB connector towards your opponent’s controller.

If you’ve pressed the button by mistake, you can press the switch in any direction to cancel the move. Once you select your move though, the green LED will blink for a few seconds. After both sides have received their opponent’s move, the center LEDs will display one of the following:

  • Solid red - lose
  • Solid green - win
  • Alternating red and green - tie
  • Blinking red - see explanation below
  • Fading - timeout. Try standing closer to your opponent and aiming your USB connector at their USB connector

A blinking red LED could mean one of two things. One possibility is that you have played against an opponent too many times. Each controller has a unique ID and your Roshamglo will not function with the same opponent after 15 rounds. We want the Roshamglo to start a conversation with people around you, and the Roshamglo can be used to help break the ice. So walk around and continue on your quest of total domination! Another possibility is that the score saved to your controller is full. You can dump your points by heading over to the scoreboard station.

Viewing and Uploading Your Score

You can view your score by closing the 5-way switch’s center switch (push the switch straight down towards the top of the board). Each time the green LED turns on, represents one point. The score is saved to a 8-bit register, which means that the maximum score you can have saved is 255 points. You can clear your score by uploading it to the scoreboard station. If the LED is red, it means that your current saved score is 0.

To upload your score, head over to the scoreboard station. With the board powered on, insert the board to the station and move the 5-way switch to the down position (towards the SparkFun Logo and lanyard clip). Just like when you’re playing a game, the green LED will flash a few times. The score will be successfully read when the LED changes to solid green. If the LED is solid red, that means that it was not able to read the score.

Summary of the LED Indicator

If the center LED is fading on and off, it means you’re in standby mode. In standby, the board will go into a deep sleep for two seconds, and then wake up to fade LED on and off. Pressing the 5-way switch in any direction will wake up the Roshamglo and perform the function attached to that switch. There are three other modes that control the LED, those LED patterns are described below.

Playing a game:

LED ColorMeaning
Blinking GreenTransmitting IR.
Solid GreenYou won!
Solid RedYou lost.
Alternating Red and GreenIt's a tie!
Blinking RedCase 1: Played this person too many times.
Case 2: Saved score is too high. Upload score to reset.

Checking your score:

LED ColorMeaning
Blinking GreenEach blink represents 1 point.
RedYour saved score is 0. Go find someone to play against!

Uploading your score:

LED ColorMeaning
Blinking GreenTransmitting IR.
Solid GreenScore uploaded successfully. You can now remove your controller.
RedUnable to upload score.

Resources and Going Further

Now that you’ve successfully got your Roshamglo up and running, it’s time to incorporate it into your own project! If you’d like to hack your Roshamglo, you should check out the Hack Your Roshamglo Badge tutorial.

For more information, check out the resources below:

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

New!

Hack Your Roshamglo Badge

Learn how to customize and program your Roshamglo badge.

IR Control Kit Hookup Guide

How to get the most out of the IR receivers and transmitters included in the IR Control Kit.

Boss Alarm

Build a Boss Alarm that alerts you of anyone walking into your office and automatically changes your computer screen.

ZX Distance and Gesture Sensor Hookup Guide

How to connect and use the SparkFun ZX Distance and Gesture Sensor with an Arduino.
New!

Roshamglo Project: TV-B-Gone

Turn your Roshamglo board into a (nearly) universal TV power button.

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


Bark Back Interactive Pet Monitor

$
0
0

Bark Back Interactive Pet Monitor a learn.sparkfun.com tutorial

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

Introduction

Shed some light (er, sound) on the elusive mysteries of your pets' antics while away from home! This Internet of Things (IoT) Bark Back project monitors and uploads the level of noise in your home to the Cloud so you can check on your beloved pet(s). The best part: if it gets too loud (i.e., Fido is barking or making some other ruckus), the program plays your own “bark back” audio file to help distract and quiet down the pup.

Marley

This project uses a Raspberry Pi to read the SparkFun MEMS microphone breakout board and trigger an audio player. Data is uploaded to the CloudMQTT service using the MQTT communication protocol.

For a demo, check out the video below!

Covered in This Tutorial

This tutorial will show you how to do the following:

  • Connect and read in the SparkFun MEMS Microphone using the Raspberry Pi 3
  • Upload the volume level to the CloudMQTT service
  • Use a volume threshold to trigger your “bark back” at your pooch if he/she gets too noisy

Suggested Reading

RasPi + Mic

To build this project, you’ll need a fully configured, WiFi-connected Raspberry Pi 3 with Raspbian OS. It’s also helpful to know some Python programming as well as the following three things: (1) using and controlling the Raspberry Pi GPIO pins, (2) MQTT communication and (3) analog signals. If any of this is unfamiliar, or if you’re just curious (be curious!), check out the tutorials below!

Raspberry Pi 3

SD Cards and Writing Images

How to upload images to an SD card for Raspberry Pi, PCDuino, or your favorite SBC.

Raspberry gPIo

How to use either Python or C++ to drive the I/O lines on a Raspberry Pi.

Raspberry Pi 3 Starter Kit Hookup Guide

Guide for getting going with the Raspberry Pi 3 starter kit.

Raspberry Pi SPI and I2C Tutorial

How to use the serial buses on your Raspberry Pi.

MQTT Communication Protocol

MQTT (Message Query Telemetry Transport) is a popular IoT communication protocol. We’ll use the Paho Client Python library and an MQTT service called CloudMQTT.

  1. Exploring Communication Protocols for IoT
  2. Getting Started with CloudMQTT
  3. Overview of Eclipse Paho MQTT Python Client Library

MEMS Microphone Breakout Board

The MEMS Microphone is an analog microphone, so you’ll need the MCP3002 Analog-to-Digital converter (“ADC”) to read in the analog signal with the Raspberry Pi digital GPIO pins.

  1. Getting started with the SparkFun MEMS Microphone Breakout Board
  2. MEMS Microphone Datasheet
  3. MCP3002 ADC Datasheet

Materials

You’ll need the following materials to follow along.

You’ll also need the following:

Hardware Hookup

alt text

Hooking the Pi up to the other hardware. Click on the wiring diagram for a closer look.

Here’s the Raspberry Pi 2 (and 3) Model B pinout diagram:

1. Connect the MCP3002 to the Raspberry Pi.

MCP3002 Close up

Close-up of the MCP3002

There are four SPI pins for SPI communication: Serial Clock (“SCL”), Master Input Slave Output (“MISO”), Master Output Slave Input (“MOSI”) and Chip Select (“CS”). These pins correspond to Raspberry Pi GPIO pin 11 (SCLK), GPIO pin 9 (MISO), GPIO pin 10 (MOSI) and GPIO pin 8 (CE0), respectively.

Here’s the MCP302 pinout diagram:

alt text

Make the following connections with MCP3002 pins:

  • Connect pin 1 to Raspberry Pi GPIO pin 8 (CE0)
  • Connect pin 2 to the analog output of the MEMS Microphone breakout board
  • Connect pin 4 to GND
  • Connect pin 5 to Raspberry Pi GPIO pin 10 (MOSI)
  • Connect pin 6 to Raspberry Pi GPIO pin 9 (MISO)
  • Connect pin 7 to Raspberry Pi GPIO pin 11 (SCLK)
  • Connect pin 8 to Raspberry Pi 3.3V out

2. Solder wires to the MEMS Microphone breakout board. Connect to MCP3002 and Raspberry Pi.

alt text

  • Connect Vcc to Raspberry Pi 3.3V.
  • Connect GND to Raspberry Pi GND
  • Connect AUD to MCP3002 Pin 2

Pi Configuration

RasPi Configuration set up

RPi connected up!

Step 1: Check & Install Updates

Check for and install updates:

sudo apt-get update
sudo apt-get upgrade
sudo reboot

Step 2: Set up SPI Interface for MEMS Microphone + MCP3002

Install the Python Dev package :

sudo apt-get install python-dev

Create a subfolder and install the Serial Port Interface (“SPI”):

mkdir py-spidev
git clone git://github.com/doceme/py-spidev
sudo python setup.py install

Here’s the SPI-Dev Documentation if you run into any issues.

Step 3: Playing Sounds with OMXPlayer

The OMXPlayer is an audio and video player pre-loaded on Raspbian OS (woo!). It works with most sound file types, including: .wav, .mp3 and .m4a. We’ll use this to play our “bark back” sounds.

In the terminal, test the OMXPlayer using the following command:

omxplayer /home/pi/.../SongFilePath/SongFileName.mp3

If that doesn’t work, try forcing it over the local audio-out device:

omxplayer -o local /home/pi/.../SongFilePath/SongFileName.mp3

Step 4: Configure CloudMQTT Server

Now we set up an MQTT server! To do this using CloudMQTT, do the following:

  1. Set up a CloudMQTT account (the “Cute Cat” plan is free).
  2. Create a new MyCloud instance.
  3. In the Console, create a new ACL rule.
  4. You can monitor published messages in the “Websocket UI” of your CloudMQTT console.

Finally, install the MQTT Paho Client Python library:

pip install paho-mqtt

Software Setup

Our goal with the Bark Back is twofold: (1) trigger an audio file when the dog barks and (2) send the volume level data to a server.

alt text

But first we need some “bark back” sounds to play! You can easily record sounds in GarageBand (or on your smartphone) and send them to the Raspberry Pi. Save the files in an easily accessible location (e.g., Desktop).

Now you’re ready to write a Bark Back Python program! …Or just use mine:

Here’s the GitHub Repository for this project. You can also copy and paste the code below (keep in mind this is Python!).

language:python
####################################################
#Bark Back: Monitor & Interact with Pets!##
####################################################
# Code written by jenfoxbot <jenfoxbot@gmail.com>
# Code is open-source, coffee/beer-ware license.
# Please keep header + if you like the content,
# buy me a coffee and/or beer if you run into me!
#####################################################

# Many thanks to the folks who create & document the libraries
# and functions used in this project.

#Libraries
#SPI
import spidev
#OMXPlayer
from threading import Thread
import subprocess
#MQTT
import paho.mqtt.client as paho
#Other
import random, time, os, urlparse
import time


songList = ["SongFile1", #e.g. "/home/pi/Desktop/SongFile.mp3""SongFile2","SongFile3","SongFile4"]

creds = {
    'CloudMQTT URL': 'INSERT_CLOUDMQTT_URL', #e.g. 'https://m10.cloudmqtt.com'
    'user': 'INSERT_CLOUDMQTT_USERNAME',
    'password': 'INSERT__CLOUDMQTT_PASSWORD',
    'host': 'INSERT_CLOUDMQTT_SERVER'
    'port': 'INSERT_CLOUDMQTT_PORT',
    'topic': 'INSERT_ACL_TOPIC'
    }

########################################################
#   Reading SparkFun MEMS Microphone Breakout Board
########################################################
#Start SPI protocol.
spi = spidev.SpiDev()
spi.open(0,0) #This is the CE0 Pin (GPIO 08) on the RPi, for CE1, use (0,1)

#Function to read in CE0 channel
def read_spi(channel):
    spidata = spi.xfer2([96,0]) ##sending 2 bytes of data (96 and 0)
    data = ((spidata[0] & 3) << 8) + spidata[1]
    return data

#Function to calculate Peak to Peak Amplitude from MEMS mic
def PTPAmp():
    sampleTime = 0.05 #Sample Rate of 50 ms
    startTime = time.time()

    PTPAmp = 0
    maxAmp = 0
    minAmp = 1023

    while(time.time() - startTime < sampleTime):
        micOut = read_spi(0) #Read in channel CE0
        if(micOut < 1023): #Prevent erroneous readings
            if(micOut > maxAmp):
                maxAmp = micOut
            elif(micOut < minAmp):
                minAmp = micOut

    PTPAmp = maxAmp - minAmp #Calculate peak-to-peak amp.
    return PTPAmp

#Function to map peak-to-peak amp to a volume unit between 0 and 10
def VolumeUnit(data, fromLow, fromHigh, toLow, toHigh):
    return (data - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow


########################################################
#   Class to Control OMXPlayer for Audio
########################################################
class OMXPlayer():
    def call_omxplayer(self):
        print ("playing " + self.file_path + '\n')
        pid = subprocess.Popen(['omxplayer', '-o', 'local',
                                self.file_path], stderr=subprocess.PIPE,
                               stdout=subprocess.PIPE)
        self.is_running = False

    def play_song(self):
        if not self.is_running:
            self.song_thread = Thread(target=self.call_omxplayer, args=())
            self.song_thread.start()
            self.is_running = True

    def __init__(self, file_path):
        self.file_path = file_path
        self.is_running = False
        self.play_song()

#Function to select random song from list
def pickRandom(songList):
    return(random.choice(songList))


########################################################
#   CloudMQTT Server
########################################################
 # Define event callbacks
def on_connect(mosq, obj, rc):
    print("rc: " + str(rc))

def on_message(mosq, obj, msg):
    print(msg.topic + "" + str(msg.qos) + "" + str(msg.payload))

def on_publish(mosq, obj, mid):
    print("mid: " + str(mid))

def on_subscribe(mosq, obj, mid, granted_qos):
    print("Subscribed: " + str(mid) + "" + str(granted_qos))

def on_log(mosq, obj, level, string):
    print(string)


########################################################
#   Main Function
########################################################
def main():
    #Call Paho Python Client Server
    mqttc = paho.Client()
    #Assign event callbacks
    mqttc.on_message = on_message
    mqttc.on_connect = on_connect
    mqttc.on_publish = on_publish
    mqttc.on_subscribe = on_subscribe

    # Uncomment to enable debug messages
    #mqttc.on_log = on_log

    # Parse CLOUDMQTT_URL (or fallback to localhost)
    url_str = os.environ.get(creds['CloudMQTT URL'], 'mqtt://localhost:1883')
    url = urlparse.urlparse(url_str)

    # Connect
    mqttc.username_pw_set(creds['user'], creds['password'])
    mqttc.connect(creds['host'], creds['port'])

    # Start subscribe, with QoS level 0
    mqttc.subscribe(creds['topic'], 0)

    while True:
        #1. Find ADC value for MEMS mic peak-to-peak amp
        PTPamp = PTPAmp()
        #2. Calculate ptp amp (Volts)
        PTPampV = round(((PTPamp*3.3) / 1024), 2)
        #3. Map ptp amp (ADC value) to Volume Unit between 0 and 10
        VolUnit = VolumeUnit(PTPamp, 0, 700, 0, 10)

        #For debugging purposes
        print(PTPamp, VolUnit)

        #4. If Volume Unit is greater than 7, play one of the songs
        if(VolUnit > 7):
            playBack = pickRandom(songList)
            OMXPlayer(playBack)
            time.sleep(0.1)

        #5. Upload data to CloudMQTT Server
        mqttc.publish("Volume", str(VolUnit))
        rc = True
        while rc:
            rc = mqttc.loop()
            time.sleep(0.1)
        print("rc: " + str(rc))

    try:
        while True:
            pass
    except KeyboardInterrupt:
        myprocess.kill()


if __name__ == '__main__':
    main()

For the Bark Back system to work properly, fill in the following:

  • songList: Write in the file path and file name for each of the songs you want to play.
  • creds: Input your CloudMQTT information in this dictionary.

Feel free to (and please do) adjust and modify the code – check out the Resources and Going Further section for project variations and additions.

Program Overview

Step 1: Read in the SparkFun MEMS Microphone breakout board.

Use the SPI library to read in the MEMS microphone ADC value (between 0 and 1023) via the MCP3002. Calculate the audio signal peak-to-peak amplitude and map that to a Volume Unit between 1 and 10.

For a thorough overview of the MEMS mic, check out this tutorial.

Step 2: Trigger audio player.

Call the OMXPlayer in Python with the Popen function in the subprocess library (see line 84).

Step 3: Send data to CloudMQTT Server

Use the Paho Client Python library to communicate with the CloudMQTT servers. To broadly summarize: set up a Client server; define communication protocols; connect with our credentials (aka creds); and subscribe and publish our data. Most of this is done in the main function (lines 129–149 and lines 169–174).

Test and Install It!

Run the BarkBack.py program in Terminal or in the Python IDE (you can also use SSH to run the program remotely). Check that you are getting volume levels published to your CloudMQTT Websocket.

alt text

Bark Back Test

Test the system by yelling (or barking) into the mic to check that the speakers are triggered and play through all of the sounds. It’s also recommended to leave the system running while you putter around the house to make sure that the threshold isn’t set too low (don’t want to traumatize the poor pooch…or your neighbors!).

Once everything is up and running, it’s recommended to solder the components to a PCB for usage longer than a few days.

That’s it! Turn the program on when you leave and check in via your CloudMQTT console.

Resources and Going Further

Here’s a summary list of resources for this tutorial:

Check out these additional ideas for expanding upon your Bark Back project:

  • Add in an RPi camera module to include video.
Raspberry Pi Camera Module V2

DEV-14028
29.95
3
  • We’re already connected to the IoT, so why not throw in some more sensors!
LIDAR-Lite v3

SEN-14032
149.99
10
SparkFun Simultaneous RFID Reader - M6E Nano

SEN-14066
199.95
SparkFun 9DoF Razor IMU M0

SEN-14001
49.95
FLiR Dev Kit

KIT-13233
259.95
24

For example, you could monitor hazardous gases (perhaps methane?).

Happy building!


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

TeensyView Hookup Guide

$
0
0

TeensyView Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The TeensyView is an SSD1306 128x32 OLED screen breakout that matches the Teensy 3 form factor. It’s great for displaying debug information and visualizing data on a Teensy, and it is compatible with the LC, 3.1, 3.2, 3.5, 3.6, Audio Board, Prop Shield, Prop Shield LC and XBee Adapter.

alt text

This guide shows how to connect the TeensyView to various Teensy-related products, then shows some examples with a library reference. The SSD1306 driver is quite popular and has a lot of support behind it. The TeensyView Arduino Library is like the Micro OLED Breakout’s and the MicroView’s libraries, so expect the same functions to work, just tuned for the Teensy and conveniently packaged.

Required Materials

To get started, you’ll need the following things:

This guide uses a Teensy 3.2, Straight Break Away Headers and a Teensy Header Kit.

SparkFun TeensyView

LCD-14048
14.95
Teensy 3.2

DEV-13736
19.95
43
Break Away Headers - Straight

PRT-00116
1.5
20
Teensy Header Kit

PRT-13925
1.5

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.

Installing an Arduino Library

How do I install a custom Arduino library? It's easy!

Installing Arduino IDE

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

Hardware Overview and Assembly

The hardware comes as a headerless PCB with OLED soldered on. There are jumpers on one side to configure how the OLED communicates with the attached Teensy. You’ll need to set the jumpers, solder the TeensyView to the Teensy or to headers, then affix the OLED.

This section instructs the use of male headers on the TeensyView, with stackable headers on the Teensy.

alt text

In addition to the kit (TeensyView and foam square), you’ll need a single Straight Break Away Header and stackable Teensy Header Kit in order to follow along with this guide.

Careful! The flex cable is fragile before the OLED is mounted. Avoid unnecessary stress, and avoid letting the OLED flop around during assembly.
  1. The TeensyView has two available connections for the OLED communication lines, to allow compatibility with various boards.
    One side (factory configuration/‘Standard’) is all connected by copper jumpers, with the ‘Alternate’ side available to reconfigure the connections.

    Use this table to determine which pins to use for the TeensyView, or leave them set by copper to the standard pins if no other resources are in use.

    JumperCopper Jumpers
    (Standard)
    Audio Board compatible
    (Alternate)
    Prop Shield compatible
    RST15215 (Std.)
    D/C52121 (Alt.)
    CS102020 (Alt.)
    SCLK131413 (Std.)
    DATA11711 (Std.)
  2. If necessary, carefully cut the copper jumper on the board and apply solder to reroute the signal.

    alt text

    Cutting the copper traces: Make two cuts, one on each end of the copper link, then remove the excess copper with a slight twist of the knife. Solder connections are not shown here, but if you remove the copper link you will need to apply a solder jump between two of the pads of the jumper!

  3. Separate two 14-pin lengths of straight male header and fit them into the breadboard, then set the PCB onto them with the jumpers facing up and the LCD facing down. The LCD will fold over and cover the jumpers.

    alt text

    Notice that the OLED is soldered to the back side and folds around the edge of the PCB, covering the selection jumpers. This is so the jumpers can still be accessed if the TeensyView is more permanently attached to a Teensy.

  4. Next, solder the headers onto the TeensyView using a flux core solder. The silkscreen rings denote pins that are electrically connected to the TeensyView circuitry. You can choose to either solder all pins, for better mechanical stability, or just the connected pins, if you foresee removal of the pins in the future. This board is assumed to be the top of a stack and may not need all of the Teensy’s signals passing through.

    alt text

    Attaching the straight headers to the Teensy using a breadboard.

  5. Now that the TeensyView has headers, it can be used to help keep the Teensy Stackable Headers in place for assembly. Put the 6 long and two 13 long headers onto the TeensyView, then place the Teensy on and apply solder.

    alt text

    Using the TeensyView as a soldering jig

    alt text

    Attaching the Teensy Header Kit

  6. If you’ve decided to only solder the electrically connected pins, now’s a good time to pull the spare pins. Hold the TeensyView firmly with one hand and give a steady pull with pliers or wire strippers. To double check, there should only be pins left in the holes with silkscreen rings.

    alt text

    Pulling the pins

  7. Apply the screen using the double-sided foam. It’s best to start with little pieces until you’re sure of the configuration you would like. Visualize how the foam will be divided or draw on it with a pen. Then use your scissors to cut off strips, and subdivide from there.

    alt text

    A way to divide the square of foam tape

    A couple small pieces go a long way to keep it in place, while a large piece can keep it there on a more permanent basis. Reasons to remove the screen may be to adjust left-right justification (to match a chassis cutout, for example) or to change the configuration of the pins. It can be tempting to just start with a large piece, but don’t! The foam is extremely grippy once it’s set.

    alt text

    Two small pieces keep the screen from flopping around.

    alt text

    A large piece can be used as a permanent solution.

    alt text

    Carefully set down the glass.

  8. Oh no! You’ve put your screen down too early and need to adjust something! Don’t worry, but don’t just pry up the glass either. Use a thin, blunt tool to push the meat of the foam out from the side.

    alt text

    Breaking the foam structure without applying force to the OLED glass.

  9. Attach the TeensyView and USB cable, then run the examples. The TeensyView has a few pins (labeled 0, 13, 14, 3V and GND) to help make sure it’s oriented the right way.

    alt text

    Here’s what the final stack should look like.

Software Installation

The Teensy line doesn’t rely on Arduino’s compiler and libraries. Instead, the Teensyduino add-on supplies the resource.

To use the TeensyView, you’ll need:

  • A compatible Arduino IDE
  • A version of Teensyduino to match your Arduino IDE
  • The TeensyView Arduino Library
Note: See the Teensyduino download page for the latest information on compatiblility between TeensyDuino and Arduino IDE versions, and to download the add-on.

Getting the Arduino IDE and Teensyduino

Follow these steps to get what you need to compile for the Teensy.

  1. Install a nonweb-based Arduino.

    See PJRC Teensyduino page for Arduino compatibility information.

    Download compatible Arduino software and install to a directory – click on previous version of the current release for older releases.

    Windows Tip: The “Windows Installer” installs to your program directory and is fine for general use without version information. It expects only one installation to be present. When uisng Teensyduino with older versions of Teensy, use the “Windows ZIP file for non admin” and install it to a directory with version number in the name, and make an extra shortcut in your start menu. This will allow you to choose the latest Arduino for general use, or a particular installation for Teensy (or other boards).
  2. Install Teensyduino to your new Arduino installation

    Get Teensyduino installer from PJRC Teensyduino page (same as above). Run the installer. It will ask for:

    • The newly installed Arduino folder
    • Which libraries to include (all recommended)

    Older versions of Teensyduino can be obtained by changing the version number in the download link.

  3. Test your installation by selecting your Teensy board from the dropdown menu and then running the Blink example.

Getting the TeensyView Arduino Library

To get the Arduino library, download from GitHub or use the Arduino Library Manager.

Download the GitHub repository

Visit the GitHub repository to download the most recent version of the library, or click the button below:

Download the Arduino Library

Use the library manager or install in the Arduino IDE

For help installing the library, check out our Installing an Arduino Library tutorial.

If you don’t end up using the manager, you’ll need to move the SparkFun_TeensyView_Arduino_Library folder into a libraries folder within your Arduino sketchbook. You can remove “master” from the name if you like.

TeensyView Library Reference

Operating the Library

With Teensyduino and the TeensyView library installed, there’s a few things to do in order to start drawing on the screen.

  • Include the TeensyView header file – #include <TeensyView.h>
  • Create an object in the global space to use the TeensyView, and pass the desired pin numbers to the constructor. – TeensyView oled(PIN_RESET, PIN_DC, PIN_CS, PIN_SCK, PIN_MOSI);
  • Run the begin() function

Now you’re ready to start controlling the screen. To draw a frame,

  • Erase all or part of the screen.
  • Draw new objects
  • Use .display() to send all data to the screen.

This example shows including the library, creating the object, then repeatedly drawing a frame. The drawing commands are kept terse to serve as a good modifiable template. This example is also available from within the Arduino library.

language:c
/******************************************************************************
  Template.ino
  A useful starting place when adding a TeensyView to an existing project.

  Marshall Taylor @ SparkFun Electronics, March 15, 2017
  https://github.com/sparkfun/SparkFun_TeensyView_Arduino_Library

  This example sets up the TeensyView and draws a test frame repeatedly.
  The objects in the frame were selected to give copy-paste examples for various
  common operations without a lot of chaff.  See TeensyView.h for specifics.

  Compatible with:
  Teensy LC
  Teensy 3.1
  Teensy 3.2
  Teensy 3.5
  Teensy 3.6

  Development environment specifics:
  Arduino IDE 1.6.12 w/ Teensyduino 1.31
  Arduino IDE 1.8.1 w/ Teensyduino 1.35
  TeensyView v1.0

  This code is released under the [MIT License](http://opensource.org/licenses/MIT).

  Please review the LICENSE.md file included with this example. If you have any questions
  or concerns with licensing, please contact techsupport@sparkfun.com.

  Distributed as-is; no warranty is given.
******************************************************************************/
#include <TeensyView.h>  // Include the SFE_TeensyView library

///////////////////////////////////
// TeensyView Object Declaration //
///////////////////////////////////
//Standard
#define PIN_RESET 15
#define PIN_DC    5
#define PIN_CS    10
#define PIN_SCK   13
#define PIN_MOSI  11

//Alternate (Audio)
//#define PIN_RESET 2
//#define PIN_DC    21
//#define PIN_CS    20
//#define PIN_SCK   14
//#define PIN_MOSI  7


TeensyView oled(PIN_RESET, PIN_DC, PIN_CS, PIN_SCK, PIN_MOSI);

void setup()
{
  oled.begin();    // Initialize the OLED
  oled.clear(ALL); // Clear the display's internal memory
  oled.display();  // Display what's in the buffer (splashscreen)
  delay(1000);     // Delay 1000 ms
  oled.clear(PAGE); // Clear the buffer.

}

void loop()
{
  oled.clear(PAGE);  // Clear the page

  oled.rect(5, 5, 20, 20);  // Draw a rectangle
  oled.rectFill(35, 16, 23, 11);  // Draw a filled rectangle
  oled.circle(22, 20, 7);  // Draw the circle:
  oled.pixel(40, 7, WHITE, NORM);  // Draw a white pixel
  oled.pixel(48, 21, BLACK, NORM);  // Draw a black pixel (on the above rectange)

  oled.setFontType(1);  // Set font to type 1
  oled.setCursor(73, 17); // move cursor
  oled.print("world!");  // Write a byte out as a character
  oled.setFontType(0);  // Set font to type 0
  oled.setCursor(67, 12); // move cursor
  oled.print("Hello");  // Write a byte out as a character

  oled.display();  // Send the PAGE to the OLED memory

  delay(200);
}

In the above example, the standard pins are used for factory hardware. The “begin” function clears the OLED to our logo, then displays the memory contents.

TeensyView Class Reference

Below, you’ll find a complete list of available TeensyView classes that can be called in your code.

Initialization

  • void begin(void)— Initialize TeensyView Library.Setup I/O pins for SPI port, then send initialization commands to the SSD1306 controller inside the OLED.

  • void end (void)— Power off the OLED display. Reset display control signals and prepare the SSD1306 controller for power off, then power off the 3.3V regulator.

Display Actions, Settings and Orientation

  • void display(void)— Transfer display memory. Bulk move the screen buffer to the SSD1306 controller’s memory so that images/graphics drawn on the screen buffer will be displayed on the OLED.

  • void clear(* uint8_t mode)— Clear screen buffer or SSD1306’s memory. To clear GDRAM inside the LCD controller, pass in the variable mode = ALL and to clear screen page buffer pass in the variable mode = PAGE.

  • void clear(* uint8_t mode, * uint8_t c)— Clear or replace screen buffer or SSD1306’s memory with a character. To clear GDRAM inside the LCD controller, pass in the variable mode = ALL with c character and to clear screen page buffer, pass in the variable mode = PAGE with c character.

  • void invert(boolean inv)– Invert display. The WHITE color of the display will turn to BLACK, and the BLACK will turn to WHITE.

  • void contrast(* uint8_t contrast)— Set OLED contrast value from 0 to 255. Note: Contrast level is not very obvious.

  • void setCursor(* uint8_t x, * uint8_t y)— Set TeensyView’s cursor position to x,y.

  • void flipVertical(boolean flip)— Flip the graphics on the OLED vertically.

  • void flipHorizontal(boolean flip)— Flip the graphics on the OLED horizontally.

  • uint8_t getLCDWidth(void)— The width of the LCD return as byte.

  • uint8_t getLCDHeight(void)— The height of the LCD return as byte.

Display Scrolling

Note: For scrolling features, refer to the OLED Memory Map section of our MicroView hookup guide for explanation of the rows and columns.
  • void scrollRight(* uint8_t start, * uint8_t stop)— Right scrolling. Set row start to row stop on the OLED to scroll right.

  • void scrollLeft(* uint8_t start, * uint8_t stop)— Left scrolling. Set row start to row stop on the OLED to scroll left.

  • void scrollVertRight(* uint8_t start, * uint8_t stop)— Right vertical scrolling. Set column start to row stop on the OLED to scroll right.

  • void scrollVertLeft(* uint8_t start, * uint8_t stop)— Left vertical scrolling. Set column start to row stop on the OLED to scroll left.

  • void scrollStop(void)— Stop the scrolling of graphics on the OLED.

Font Functions

  • uint8_t getFontWidth(void)— Get font width. The current font’s width return as byte.

  • uint8_t getFontHeight(void)— Get font height. The current font’s height return as byte.

  • uint8_t getTotalFonts(void)— Get total fonts. Return the total number of fonts loaded into the TeensyView’s flash memory.

  • uint8_t getFontType(void)— Get font type. Return the font type number of the current font.

  • uint8_t setFontType(* uint8_t type)— Set font type. Set the current font type number (i.e., changing to different fonts based on the type provided).

  • uint8_t getFontStartChar(void)— Get font starting character. Return the starting ASCII character of the current font; not all fonts start with ASCII character 0. Custom fonts can start from any ASCII character.

  • uint8_t getFontTotalChar(void)— Get font total characters. Return the total characters of the current font.

Drawing Pixels

  • void pixel(* uint8_t x, * uint8_t y)— Draw pixel using the current fore color and current draw mode in the screen buffer’s x,y position.

  • void pixel(* uint8_t x, * uint8_t y, * uint8_t color, * uint8_t mode)— Draw color pixel in the screen buffer’s x,y position with NORM or XOR draw mode.

Drawing Lines

  • 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.

Drawing Rectangles

  • 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.

Drawing Circles

  • void circle(* uint8_t x, * uint8_t y, * uint8_t radius)— Draw circle with radius using current fore color and current draw mode 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 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 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 at x,y of the screen buffer. Uses the Bresenham’s circle algorithm with a few modifications to paint the circle without overlapping draw operations.

Misc. Drawing

  • void drawChar(* uint8_t x, * uint8_t y, * uint8_t c)— Draw character c using current color and current draw mode at x,y.

  • void drawChar(* uint8_t x, * uint8_t y, * uint8_t c, * uint8_t color, * uint8_t mode)— Draw character c using color and draw mode at x,y.

  • void drawBitmap(void)— Draw bitmap image stored elsewhere in the program to the OLED screen.

  • void setColor(* uint8_t color)— Set the current draw’s color. Only WHITE and BLACK available.

  • void setDrawMode(* uint8_t mode)— Set current draw mode with NORM or XOR.

Misc. Under-the-Hood Functions

  • virtual size_t write(uint8_t)— Override Arduino’s Print so that we can use uView.print().

  • void data(uint8_t c);— SPI data. Send 1 data byte via SPI to SSD1306 controller.

  • void setColumnAddress(uint8_t add)— Set SSD1306 column address. Send column address command and address to the SSD1306 OLED controller.

  • void setPageAddress(uint8_t add)— Set SSD1306 page address. Send page address command and address to the SSD1306 OLED controller.

  • void command(uint8_t c)— Send 1 command byte.

  • uint8_t * getScreenBuffer(void)— Get pointer to screen buffer. Return a pointer to the start of the RAM screen buffer for direct access.

System-Level Reference

  • TeensyView(uint8_t rst, uint8_t dc, uint8_t cs, uint8_t sck, uint8_t mosi)— Construct TeensyView object with the pins specified in the arguments.

  • static void begin()— SPI Initialization. Set up I/O pins for SPI port, then send initialization commands to the SSD1306 controller inside the OLED. Pins to use have been specified in the constructor.

Example: ScreenDemo With Default Configuration

This demo shows off the graphic and text commands that are within the TeensyView library.

Hardware Requirements

  • Teensy 3.1 to 3.6, or LC
  • TeensyView set to default jumpers (factory)

Choose the example ScreenDemo from the menu, compile and run. You should see all sorts of graphic demos go by on the screen. (Note: These can progress at different speeds depending on which Teensy is used.)

Alternately, copy the code from here:

language:c
/******************************************************************************
   TeensyView_Demo.ino
   SFE_TeensyView Library Demo
   Jim Lindblom @ SparkFun Electronics
   Original Creation Date: October 27, 2014
   Modified Febuary 2, 2017

   This sketch uses the TeensyView library to draw a 3-D projected
   cube, and rotate it along all three axes.

   Development environment specifics:
   Arduino IDE 1.6.12 w/ Teensyduino 1.31
   Arduino IDE 1.8.1 w/ Teensyduino 1.35
   TeensyView v1.0

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

   Distributed as-is; no warranty is given.
 ******************************************************************************/
#include <TeensyView.h>  // Include the SFE_TeensyView library

///////////////////////////////////
// TeensyView Object Declaration //
///////////////////////////////////
//Standard
#define PIN_RESET 15
#define PIN_DC    5
#define PIN_CS    10
#define PIN_SCK   13
#define PIN_MOSI  11

//Alternate (Audio)
//#define PIN_RESET 2
//#define PIN_DC    21
//#define PIN_CS    20
//#define PIN_SCK   14
//#define PIN_MOSI  7


TeensyView oled(PIN_RESET, PIN_DC, PIN_CS, PIN_SCK, PIN_MOSI);

void setup()
{
  oled.begin();    // Initialize the OLED
  oled.clear(ALL); // Clear the display's internal memory
  oled.display();  // Display what's in the buffer (splashscreen)
  delay(1000);     // Delay 1000 ms
  oled.clear(PAGE); // Clear the buffer.

  randomSeed(analogRead(A0) + analogRead(A1));
}

void pixelExample()
{
  printTitle("Pixels", 1);

  for (int i = 0; i < 1024; i++)
  {
    oled.pixel(random(oled.getLCDWidth()), random(oled.getLCDHeight()));
    oled.display();
  }
}

void lineExample()
{
  int middleX = oled.getLCDWidth() / 2;
  int middleY = oled.getLCDHeight() / 2;
  int xEnd, yEnd;
  int lineWidth = min(middleX, middleY);

  printTitle("Lines!", 1);

  for (int i = 0; i < 3; i++)
  {
    for (int deg = 0; deg < 360; deg += 15)
    {
      xEnd = lineWidth * cos(deg * PI / 180.0);
      yEnd = lineWidth * sin(deg * PI / 180.0);

      oled.line(middleX, middleY, middleX + xEnd, middleY + yEnd);
      oled.display();
      delay(10);
    }
    for (int deg = 0; deg < 360; deg += 15)
    {
      xEnd = lineWidth * cos(deg * PI / 180.0);
      yEnd = lineWidth * sin(deg * PI / 180.0);

      oled.line(middleX, middleY, middleX + xEnd, middleY + yEnd, BLACK, NORM);
      oled.display();
      delay(10);
    }
  }
}

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 = (oled.getLCDHeight() / 2) - (paddleH / 2);
  int paddle0_X = 2;
  // Paddle 1 (right) position coordinates
  int paddle1_Y = (oled.getLCDHeight() / 2) - (paddleH / 2);
  int paddle1_X = oled.getLCDWidth() - 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, oled.getLCDHeight() - 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 < oled.getLCDWidth() - 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 >= (oled.getLCDHeight() - 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 > oled.getLCDHeight() - 2 - paddleH))
    {
      paddle0Velocity = -paddle0Velocity;
    }
    // Change paddle 1's direction if it hit top/bottom
    if ((paddle1_Y <= 1) || (paddle1_Y > oled.getLCDHeight() - 2 - paddleH))
    {
      paddle1Velocity = -paddle1Velocity;
    }

    // Draw the Pong Field
    oled.clear(PAGE);  // Clear the page
    // Draw an outline of the screen:
    oled.rect(0, 0, oled.getLCDWidth() - 1, oled.getLCDHeight());
    // Draw the center line
    oled.rectFill(oled.getLCDWidth() / 2 - 1, 0, 2, oled.getLCDHeight());
    // Draw the Paddles:
    oled.rectFill(paddle0_X, paddle0_Y, paddleW, paddleH);
    oled.rectFill(paddle1_X, paddle1_Y, paddleW, paddleH);
    // Draw the ball:
    oled.circle(ball_X, ball_Y, ball_rad);
    // Actually draw everything on the screen:
    oled.display();
    delay(25);  // Delay for visibility
  }
  delay(1000);
}

void textExamples()
{
  printTitle("Text!", 1);

  // Demonstrate font 0. 5x8 font
  oled.clear(PAGE);     // Clear the screen
  oled.setFontType(0);  // Set font to type 0
  oled.setCursor(0, 0); // Set cursor to top-left
  // There are 255 possible characters in the font 0 type.
  // Lets run through all of them and print them out!
  for (int i = 0; i <= 255; i++)
  {
    // You can write byte values and they'll be mapped to
    // their ASCII equivalent character.
    oled.write(i);  // Write a byte out as a character
    oled.display(); // Draw on the screen
    delay(10);      // Wait 10ms
    // We can only display 60 font 0 characters at a time.
    // Every 60 characters, pause for a moment. Then clear
    // the page and start over.
    if ((i % 60 == 0) && (i != 0))
    {
      delay(500);           // Delay 500 ms
      oled.clear(PAGE);     // Clear the page
      oled.setCursor(0, 0); // Set cursor to top-left
    }
  }
  delay(500);  // Wait 500ms before next example

  // Demonstrate font 1. 8x16. Let's use the print function
  // to display every character defined in this font.
  oled.setFontType(1);  // Set font to type 1
  oled.clear(PAGE);     // Clear the page
  oled.setCursor(0, 0); // Set cursor to top-left
  // Print can be used to print a string to the screen:
  oled.print(" !\"#$%&'()*+,-./01234");
  oled.display();       // Refresh the display
  delay(1000);          // Delay a second and repeat
  oled.clear(PAGE);
  oled.setCursor(0, 0);
  oled.print("56789:;<=>?@ABCDEFGHI");
  oled.display();
  delay(1000);
  oled.clear(PAGE);
  oled.setCursor(0, 0);
  oled.print("JKLMNOPQRSTUVWXYZ[\\]^");
  oled.display();
  delay(1000);
  oled.clear(PAGE);
  oled.setCursor(0, 0);
  oled.print("_`abcdefghijklmnopqrs");
  oled.display();
  delay(1000);
  oled.clear(PAGE);
  oled.setCursor(0, 0);
  oled.print("tuvwxyz{|}~");
  oled.display();
  delay(1000);

  // Demonstrate font 2. 10x16. Only numbers and '.' are defined.
  // This font looks like 7-segment displays.
  // Lets use this big-ish font to display readings from the
  // analog pins.
  for (int i = 0; i < 25; i++)
  {
    oled.clear(PAGE);            // Clear the display
    oled.setCursor(0, 0);        // Set cursor to top-left
    oled.setFontType(0);         // Smallest font
    oled.print("A0: ");          // Print "A0"
    oled.setFontType(2);         // 7-segment font
    oled.print(analogRead(A0));  // Print a0 reading
    oled.setCursor(0, 16);       // Set cursor to top-middle-left
    oled.setFontType(0);         // Repeat
    oled.print("A1: ");
    oled.setFontType(2);
    oled.print(analogRead(A1));
    oled.setCursor(0, 32);
    oled.setFontType(0);
    oled.print("A2: ");
    oled.setFontType(2);
    oled.print(analogRead(A2));
    oled.display();
    delay(100);
  }

}

void loop()
{
  pixelExample();  // Run the pixel example function
  lineExample();   // Then the line example function
  shapeExample();  // Then the shape example
  textExamples();  // Finally the text example
}

// Center and print a small title
// This function is quick and dirty. Only works for titles one
// line long.
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);
}

The loop() can be seen near the end of the code. It runs each of the drawing examples. If you’re wondering how the code does a certain thing on the screen, examine the routine (such as shapeExample(){}) and consult the Library Reference.

Example: Audio Board-Compatible Connection

This example shows off using the TeensyView with the audio platform. It takes incoming audio data on both line-in channels and displays a 40-bin FFT for each, plus some CPU usage info.

alt text

The TeensyView atop a Teensy Audio stack

Hardware Requirements

  • Teensy 3.1 to 3.6 (Note: CPU usage at 100% on the 3.1 with both FFTs enabled)
  • TeensyView set to alternate jumpers
  • Audio board with a line-in connection added
  • Optional: Headphones attached to headphone out port (passes audio)

Choose the example TeensyViewAudio from the menu, compile and run. You should see all sorts of graphic demos go by on the screen. (Note: These can progress at different speeds depending on which Teensy is used.)

Alternately, copy the code from here:

language:c
/******************************************************************************
  TeensyViewAudio.ino
  Example using the TeensyView with the Teensy Audio board

  Marshall Taylor @ SparkFun Electronics, December 6, 2016
  https://github.com/sparkfun/SparkFun_TeensyView_Arduino_Library

  This is modified FFT example software.  It passes L/R audio channels to the
  headphone output while displaying the FFTs as a bar graph on the OLED, with
  CPU usage reports.

  Compatible with:
  Teensy 3.1 + Teensy Audio Board (100% processor usage)
  Teensy 3.2 + Teensy Audio Board (100% processor usage)
  Teensy 3.5 + Teensy Audio Board
  Teensy 3.6 + Teensy Audio Board

  Resources:
  Requires the Teensy Audio library

  Development environment specifics:
  Arduino IDE 1.6.12 w/ Teensyduino 1.31
  Arduino IDE 1.8.1 w/ Teensyduino 1.35
  TeensyView v1.0

  This code is released under the [MIT License](http://opensource.org/licenses/MIT).

  Please review the LICENSE.md file included with this example. If you have any questions
  or concerns with licensing, please contact techsupport@sparkfun.com.

  Distributed as-is; no warranty is given.
******************************************************************************/
#include <Audio.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <SerialFlash.h>

// GUItool: begin automatically generated code
AudioInputI2S            audioInput;     //xy=458,218
AudioAnalyzeFFT1024      LeftFFT;          //xy=672,138
AudioAnalyzeFFT1024      RightFFT;      //xy=683,295
AudioOutputI2S           audioOutput;    //xy=686,219
AudioConnection          patchCord1(audioInput, 0, LeftFFT, 0);
AudioConnection          patchCord2(audioInput, 0, audioOutput, 0);
AudioConnection          patchCord3(audioInput, 1, audioOutput, 1);
AudioConnection          patchCord4(audioInput, 1, RightFFT, 0);
AudioControlSGTL5000     audioShield;    //xy=467,310
// GUItool: end automatically generated code

const int myInput = AUDIO_INPUT_LINEIN;
//const int myInput = AUDIO_INPUT_MIC;

#include <TeensyView.h>  // Include the TeensyView library

///////////////////////////////////
// TeensyView Object Declaration //
///////////////////////////////////
//Standard
//#define PIN_RESET 15
//#define PIN_DC    5
//#define PIN_CS    10
//#define PIN_SCK   13
//#define PIN_MOSI  11

//Alternate (Audio)
#define PIN_RESET 2
#define PIN_DC    21
#define PIN_CS    20
#define PIN_SCK   14
#define PIN_MOSI  7

TeensyView oled(PIN_RESET, PIN_DC, PIN_CS, PIN_SCK, PIN_MOSI);

void setup()
{
  // Set up audio stuff:
  // Audio connections require memory to work.  For more
  // detailed information, see the MemoryAndCpuUsage example
  AudioMemory(20);

  // Enable the audio shield and set the output volume.
  audioShield.enable();
  audioShield.inputSelect(myInput);
  audioShield.volume(0.5); //Pass-through volume

  // Configure the window algorithm to use
  LeftFFT.windowFunction(AudioWindowHanning1024);
  RightFFT.windowFunction(AudioWindowHanning1024);

  //Initialize the OLED
  oled.begin();
  // clear(ALL) will clear out the OLED's graphic memory.
  // clear(PAGE) will clear the Arduino's display buffer.
  oled.clear(ALL);  // Clear the display's memory (gets rid of artifacts)
  // To actually draw anything on the display, you must call the
  // display() function.
  oled.display();
  // Give the splash screen some time to shine
  delay(2000);
}

unsigned long last_time = millis();
uint8_t overlayCounter = 0;
float lastLoopTime = 0;
uint16_t lastCPU = 0;
uint16_t lastMem = 0;

float leftBands[40] = {
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};

float RightBands[40] = {
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};

void loop()
{
  float loopTime;
  int i;

  //calc loopTime
  unsigned long this_time = millis();
  if (this_time > last_time)
  {
    loopTime = (this_time - last_time);
  }
  last_time = this_time;

  //Update data every 20 frames for readability
  overlayCounter++;
  if (overlayCounter > 20)
  {
    lastLoopTime = loopTime;
    lastCPU = AudioProcessorUsageMax();
    AudioProcessorUsageMaxReset();
    lastMem = AudioMemoryUsageMax();
    AudioMemoryUsageMaxReset();

    overlayCounter = 0;
  }

  //Draw a frame
  oled.clear(PAGE);

  //Draw left bands
  for (i = 0; i < 40; i++)
  {
    if (leftBands[i] > 0.5) leftBands[i] = 0.25;
    oled.line(62 - i, 31, 62 - i, 31 - (leftBands[i] * 127));
  }

  //Draw Right bands
  for (i = 0; i < 40; i++)
  {
    if (RightBands[i] > 0.5) RightBands[i] = 0.25;
    oled.line(65 + i, 31, 65 + i, 31 - (RightBands[i] * 127));
  }

  //Overlay info
  //  loop time
  oled.setCursor(0, 0);
  oled.print("Loop=");
  oled.print((uint8_t)lastLoopTime);
  oled.print("ms");
  //  Teensy Audio info
  oled.setCursor(83, 0);
  oled.print("cpu=");
  oled.print(lastCPU);
  oled.setCursor(91, 8);
  oled.print("mem=");
  oled.print(lastMem);
  //  L/R letters
  oled.setCursor(15, 24);
  oled.print("L");
  oled.setCursor(108, 24);
  oled.print("R");

  if (LeftFFT.available()) {
    // each time new FFT data is available
    for (i = 0; i < 40; i++) {
      leftBands[i] = LeftFFT.read(i);
    }
  }
  if (RightFFT.available()) {
    // each time new FFT data is available
    for (i = 0; i < 40; i++) {
      RightBands[i] = RightFFT.read(i);
    }
  }

  oled.display();

}

The important lesson from this sketch is that the constructor is passed the alternate set of pins, and can be used concurrently with the Audio board.

Use the same command from the ScreenDemo and paint the screen with whatever you need to display!

Example: Prop Shield-Compatible Connection

This example shows off using the TeensyView with the Prop Shield. This is a demonstration and test of all features on the Prop Shield and won’t work on the LC prop shield, which doesn’t have motion sensors.

The example:

  • Creates a test file on the Flash (you may lose existing data) that contains RGB data
  • Initializes the IMUs
  • Initializes the Audio platform
  • Displays heading, pitch and roll on the screen
  • Generates a sine wave of pitch and filter based on physical orientation — kind of like a Theremin!
  • Continuously reads flash data from the test file and applies it to the APA102 LED

Wire the LED and speaker to the Prop Shield using the connection table:

Prop Shield
Function
GAPA102 Ground (Pin 3)
CAPA102 Clock In (Pin 2)
DAPA102 Data In (Pin 1)
5APA102 VCC (Pin 4)
-Headphone ring
+Headphone tip

Prop Shield Connections

alt text

The TeensyView atop a Teensy Prop stack. Notice the attached LED and speaker.

Hardware Requirements

  • Teensy 3.1 to 3.6
  • TeensyView set to the following:
    • RST set to default
    • DC set to alternate
    • CS set to alternate
    • CLK set to default
    • mosi set to default
  • Prop Shield with:

Choose the example TeensyViewProp from the menu, compile and run. After the splash screen, the sketch will start, and the display will switch to orientation information. (Note: With so many included libraries, this can take awhile to compile!)

Alternately, copy the code from here:

language:c
/******************************************************************************
  TeensyViewProp.ino
  Example using the TeensyView with the Teensy Prop Shield.

  Marshall Taylor @ SparkFun Electronics, December 6, 2016
  https://github.com/sparkfun/SparkFun_TeensyView_Arduino_Library

  This enables all resources on the Teensy Prop Shield and operates them with
  the TeensyView.

  Accelerometer data is used to drive Teensy Audio system (bends pitch)
  Flash is programmed with LED data at boot (note: comment out flash erasor if necessary)
  LED continuously reads flash file for color information (Driven raw by SPI)
  TeensyView continuously updated with pitch, roll, and heading information.

  Compatible with:
  Teensy 3.1 + Prop Shield
  Teensy 3.2 + Prop Shield
  Teensy 3.5 + Prop Shield
  Teensy 3.6 + Prop Shield

  Resources:
  Requires the Teensy Audio library
  NXPMotionSense Library
  EEPROM Library
  SerialFlash Library


  Development environment specifics:
  Arduino IDE 1.6.12
  TeensyView v1.0

  This code is released under the [MIT License](http://opensource.org/licenses/MIT).

  Please review the LICENSE.md file included with this example. If you have any questions
  or concerns with licensing, please contact techsupport@sparkfun.com.

  Distributed as-is; no warranty is given.
******************************************************************************/


//********************IMU test*******************//
#include <NXPMotionSense.h>
#include <Wire.h>
#include <EEPROM.h>
NXPMotionSense imu;
NXPSensorFusion filter;
//********************IMU test*******************//

//********************Audio test*******************//
#include <Audio.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <SerialFlash.h>
// GUItool: begin automatically generated code
AudioSynthWaveformSine   sine4;          //xy=321,367
AudioSynthWaveformSine   sine3;          //xy=323,314
AudioSynthWaveformSine   sine2;          //xy=324,264
AudioSynthWaveformSine   sine1;          //xy=325,213
AudioMixer4              mixer1;         //xy=506,303
AudioSynthWaveformDc     dc1;            //xy=517,382
AudioFilterStateVariable filter1;        //xy=695,311
AudioFilterStateVariable filter2;        //xy=851,342
AudioOutputAnalog        dac1;           //xy=1028,366
AudioConnection          patchCord1(sine4, 0, mixer1, 3);
AudioConnection          patchCord2(sine3, 0, mixer1, 2);
AudioConnection          patchCord3(sine2, 0, mixer1, 1);
AudioConnection          patchCord4(sine1, 0, mixer1, 0);
AudioConnection          patchCord5(mixer1, 0, filter1, 0);
AudioConnection          patchCord6(dc1, 0, filter1, 1);
AudioConnection          patchCord7(dc1, 0, filter2, 1);
AudioConnection          patchCord8(filter1, 0, filter2, 0);
AudioConnection          patchCord9(filter2, 0, dac1, 0);
// GUItool: end automatically generated code
//********************Audio test*******************//

//********************Flash Test*******************//
//#include <SerialFlash.h>
//#include <SPI.h>
const int FlashChipSelect = 6; // digital pin for flash chip CS pin
SerialFlashFile file; //Working file
uint16_t fileIndex = 0;
//********************Flash Test*******************//

//********************TeensyView*******************//
#include <TeensyView.h>  // Include the SFE_TeensyView library

///////////////////////////////////
// TeensyView Object Declaration //
///////////////////////////////////
//Standard
#define PIN_RESET 15
//#define PIN_DC    5
//#define PIN_CS    10
#define PIN_SCK   13
#define PIN_MOSI  11

//Alternate (Audio)
//#define PIN_RESET 2
#define PIN_DC    21
#define PIN_CS    20
//#define PIN_SCK   14
//#define PIN_MOSI  7

TeensyView oled(PIN_RESET, PIN_DC, PIN_CS, PIN_SCK, PIN_MOSI);
//********************TeensyView*******************//

void setup()
{
  // These three lines of code are all you need to initialize the
  // OLED and print the splash screen.
  Serial.begin(115200);
  // Before you can start using the OLED, call begin() to init
  // all of the pins and configure the OLED.
  oled.begin();
  // clear(ALL) will clear out the OLED's graphic memory.
  // clear(PAGE) will clear the Arduino's display buffer.
  oled.clear(ALL);  // Clear the display's memory (gets rid of artifacts)
  // To actually draw anything on the display, you must call the
  // display() function.
  oled.display();

  delay(2000);
  oled.clear(PAGE);
  oled.setCursor(0, 0);
  oled.print("Heading");
  oled.setCursor(50, 0);
  oled.print("Pitch");
  oled.setCursor(90, 0);
  oled.print("Roll");
  oled.line(0, 9, 127, 9);
  oled.display();

  //********************Audio test*******************//
  AudioMemory(40);
  mixer1.gain(0, 0.1);
  mixer1.gain(1, 0.1);
  mixer1.gain(2, 0.1);
  mixer1.gain(3, 0.1);
  filter1.frequency(500);
  filter1.octaveControl(2);
  filter1.resonance(2);
  filter2.frequency(500);
  filter1.octaveControl(2);
  filter2.resonance(2);
  dc1.amplitude(0);
  setSines(110);
  pinMode(5, OUTPUT);
  digitalWrite(5, HIGH); // turn on the amplifier
  delay(10);
  //********************Audio test*******************//

  Serial.begin(9600);

  //********************IMU test*******************//
  imu.begin();
  filter.begin(100);
  //********************IMU test*******************//

  //********************RAW APA102*******************//
  pinMode(7, OUTPUT); //Configure chip select pin
  //********************RAW APA102*******************//

  //********************Flash Test*******************//
  if (!SerialFlash.begin(FlashChipSelect)) {
    Serial.println("Unable to access SPI Flash chip");
  }
  uint8_t id[5];
  SerialFlash.readID(id);
  Serial.println("ID word:");
  Serial.print("0x");
  Serial.println(id[0], HEX);
  Serial.print("0x");
  Serial.println(id[1], HEX);
  Serial.print("0x");
  Serial.println(id[2], HEX);
  Serial.print("0x");
  Serial.println(id[3], HEX);
  //clearFlash();  //Use this to erase all... this holds the program in a while loop when done.
  prepareTestFile();  //This creates a test file IF it doesn't exist
  listTestFile();
  //********************Flash Test*******************//

}
//********************RAW APA102*******************//
void setLED( uint8_t r, uint8_t g, uint8_t b )
{
  uint8_t brightness = 0b00001000; //Quarter bright
  SPI.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE0));
  digitalWrite(7, HIGH);  // enable access to LEDs
  SPI.transfer(0);
  SPI.transfer(0);
  SPI.transfer(0);
  SPI.transfer(0);
  SPI.transfer(0b11100000 | brightness);
  SPI.transfer(b);
  SPI.transfer(g);
  SPI.transfer(r);
  digitalWrite(7, LOW);  // enable access to LEDs
  SPI.endTransaction();
  //This sends data to the LED
}
//********************RAW APA102*******************//

//********************Flash Test*******************//
//Test data for mem R/W (also LED display data, as r1, g1, b1, r2, g2, b2...)
uint8_t const colorwheel[128 * 3] = {
  64, 22, 10, 63, 21, 11, 63, 19, 12, 63, 18, 14, 63, 16, 15, 63, 15, 16, 62, 14, 18, 62, 12, 19,
  61, 11, 21, 60, 10, 22, 60, 9, 24, 59, 8, 25, 58, 7, 27, 57, 6, 28, 56, 5, 30, 55, 4, 32,
  54, 3, 33, 53, 3, 35, 52, 2, 36, 51, 1, 38, 49, 1, 39, 48, 0, 41, 47, 0, 42, 45, 0, 44,
  44, 0, 45, 42, 0, 47, 41, 0, 48, 39, 0, 49, 38, 0, 51, 36, 0, 52, 35, 0, 53, 33, 0, 54,
  32, 1, 55, 30, 1, 56, 28, 2, 57, 27, 3, 58, 25, 3, 59, 24, 4, 60, 22, 5, 60, 21, 6, 61,
  19, 7, 62, 18, 8, 62, 16, 9, 63, 15, 10, 63, 14, 11, 63, 12, 12, 63, 11, 14, 63, 10, 15, 64,
  9, 16, 63, 8, 18, 63, 7, 19, 63, 6, 21, 63, 5, 22, 63, 4, 24, 62, 3, 25, 62, 3, 27, 61,
  2, 28, 60, 1, 30, 60, 1, 32, 59, 0, 33, 58, 0, 35, 57, 0, 36, 56, 0, 38, 55, 0, 39, 54,
  0, 41, 53, 0, 42, 52, 0, 44, 51, 0, 45, 49, 0, 47, 48, 0, 48, 47, 1, 49, 45, 1, 51, 44,
  2, 52, 42, 3, 53, 41, 3, 54, 39, 4, 55, 38, 5, 56, 36, 6, 57, 35, 7, 58, 33, 8, 59, 32,
  9, 60, 30, 10, 60, 28, 11, 61, 27, 12, 62, 25, 14, 62, 24, 15, 63, 22, 16, 63, 21, 18, 63, 19,
  19, 63, 18, 21, 63, 16, 22, 64, 15, 24, 63, 14, 25, 63, 12, 27, 63, 11, 28, 63, 10, 30, 63, 9,
  32, 62, 8, 33, 62, 7, 35, 61, 6, 36, 60, 5, 38, 60, 4, 39, 59, 3, 41, 58, 3, 42, 57, 2,
  44, 56, 1, 45, 55, 1, 47, 54, 0, 48, 53, 0, 49, 52, 0, 51, 51, 0, 52, 49, 0, 53, 48, 0,
  54, 47, 0, 55, 45, 0, 56, 44, 0, 57, 42, 0, 58, 41, 0, 59, 39, 1, 60, 38, 1, 60, 36, 2,
  61, 35, 3, 62, 33, 3, 62, 32, 4, 63, 30, 5, 63, 28, 6, 63, 27, 7, 63, 25, 8, 63, 24, 9
};
void clearFlash( void )
{
  Serial.print("Erasing flash");
  SerialFlash.eraseAll();
  while (SerialFlash.ready() == false)
  {
    // wait, 30 seconds to 2 minutes for most chips
    Serial.print(".");
    delay(100);
  }
  Serial.println("Done!");
  Serial.println("Program held.  Now comment out clearFlash(); and recompile");
  while (1);
}

void prepareTestFile( void )
{
  //Check if file exists, if not, create it.
  if (SerialFlash.exists("testfile.dat") == 0)
  {
    //File doesn't exist
    if (SerialFlash.create("testfile.dat", 128 * 3) == true)
    {
      Serial.println("Created testfile.dat");
    }
    else
    {
      Serial.println("File creation failed!!!");
    }
  }
  if (SerialFlash.exists("testfile.dat"))
  {
    Serial.println("File Exists, trying to open...");
    file = SerialFlash.open("testfile.dat");
    if (file)
    { // true if the file exists
      Serial.println("testfile.dat opened");
      uint8_t buffer[3];
      for (int i = 0; i < (128 * 3); i = i + 3)
      {
        buffer[0] = colorwheel[i];
        buffer[1] = colorwheel[i + 1];
        buffer[2] = colorwheel[i + 2];
        file.seek(i);
        file.write(buffer, 3);
        Serial.print(".");
      }
      file.close();
      Serial.println("Test data generation complete");
    }
    else
    {
      Serial.println("testfile.dat not opened!!!");
    }
  }
}

void listTestFile( void )
{
  file = SerialFlash.open("testfile.dat");
  if (file)
  { // true if the file exists
    Serial.println("testfile.dat opened");
    uint8_t buffer[3];
    fileIndex = 0;
    for (int i = 0; i < 128; i++)
    {
      file.seek(fileIndex);
      fileIndex = fileIndex + 3;
      file.read(buffer, 3);
      Serial.println(buffer[0], HEX);
      Serial.println(buffer[1], HEX);
      Serial.println(buffer[2], HEX);
    }
    file.close();
  }
  else
  {
    Serial.println("testfile.dat not opened!!!");
  }
}
//********************Flash Test*******************//

//********************Audio test*******************//
void setSines(float root)
{
  sine1.frequency(root);
  sine1.amplitude(0.25);
  sine2.frequency(root * 2);
  sine2.amplitude(0.25);
  sine3.frequency(root * 3);
  sine3.amplitude(0.25);
  sine4.frequency(root * 4);
  sine4.amplitude(0.25);
}
//********************Audio test*******************//

void loop()
{
  //********************IMU test*******************//
  float ax, ay, az;
  float gx, gy, gz;
  float mx, my, mz;
  float roll, pitch, heading;
  if (imu.available())
  {
    // Read the motion sensors
    imu.readMotionSensor(ax, ay, az, gx, gy, gz, mx, my, mz);
    // Update the SensorFusion filter
    filter.update(gx, gy, gz, ax, ay, az, mx, my, mz);
    // print the heading, pitch and roll
    roll = filter.getRoll();
    pitch = filter.getPitch();
    heading = filter.getYaw();
    Serial.print("Orientation: ");
    Serial.print(heading);
    Serial.print("");
    Serial.print(pitch);
    Serial.print("");
    Serial.println(roll);

    //********************Audio test*******************//
    dc1.amplitude(pitch / 20);
    setSines(55 + (roll * 10));
    //********************Audio test*******************//

    //********************TeensyView*******************//
    oled.setCursor(0, 13);
    oled.print("");
    oled.setCursor(0, 13);
    oled.print(heading);
    oled.setCursor(43, 13);
    oled.print(pitch);
    oled.setCursor(83, 13);
    oled.print(roll);
    oled.display();
    //********************TeensyView*******************//
  }
  //********************IMU test*******************//

  //********************Flash Test*******************//
  if (fileIndex >= (128 * 3)) fileIndex = 0;
  fileIndex = fileIndex + 3;
  if (!SerialFlash.begin(FlashChipSelect)) {
    Serial.println("Unable to access SPI Flash chip");
  }
  file = SerialFlash.open("testfile.dat");
  if (file)
  { // true if the file exists
    uint8_t buffer[3];
    file.seek(fileIndex);
    file.read(buffer, 3);
    file.close();
    //Serial.println(buffer[0], HEX); //Show red channel to serial console
    //********************RAW APA102*******************//
    setLED( buffer[0], buffer[1], buffer[2] );
    //********************RAW APA102*******************//
  }
  //********************Flash Test*******************//
}

After compiling and uploading, the TeensyView will display heading, pitch and roll, while the LED proves flash communication and the speaker proves that the audio system is functioning.

Resources and Going Further

The TeensyView was designed to be as flexible as possible while still being able to nest down into a low-profile addition to the Teensy.

alt text

Some various TeensyView-Teensy connections. The bottom centermost TeensyView was created using this guide, while the left is a minimal non-separable configuration. Using a breadboard is also an option.

The TeensyView works with some really heavy examples, but they’re really only demonstrations. What to do with it is up to you! They’re great for adding simple debug info to a mobile project, while a diligent pixel artist could implement a whole menu system.

More information about the SSD1306 controller and the TeensyView design can be found here:

Additional projects and sketches that use the TeensyView:

  • The HighSpeedTest, in the examples folder, draws alternating pixels as fast as possible. This can be used to experiment with the limits of the TeensyView’s OLED.

For additional inspiration, check out these other tutorials based on displays:

LED Light Bar Hookup

A quick overview of SparkFun's LED light bars, and some examples to show how to hook them up.

Bubble Display Hookup Guide

Need a small, cheap, and easy display? These bubble displays are what you've been looking for. Learn how to use them in this hookup guide.

Interactive Hanging LED Array

Learn how we converted 72 lightbulbs into an interactive LED array for our conference room.

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.

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

SIK Experiment Guide for Arduino - V3.3

$
0
0

SIK Experiment Guide for Arduino - V3.3 a learn.sparkfun.com tutorial

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

Introduction: Hardware

The SparkFun Inventor’s Kit is your map for navigating the waters of beginning embedded electronics. This kit contains all the information and parts you will need to create 16 circuits that cover the basics of programming and hardware interactions. At the center of this kit is one core philosophy – that anyone can (and should) experiment with electronics. When you’re done with this guide, you’ll have the know-how to start creating your own projects and experiments.

This guide is also available as a downloadable PDF, if you prefer.

SIK Guide Download

SparkFun Inventor’s Kit - V3.3

You should have one of the two following versions of the SIK. If you need a overview of the parts included in your kit, please click on the product link below.

SparkFun Inventor's Kit - V3.3

KIT-13969
99.95
SparkFun Inventor's Kit (for Arduino Uno) - V3.3

KIT-13970
109.95

The primary difference between the two kits is the microcontroller included in the kit. The SparkFun Inventor’s Kit includes a SparkFun RedBoard, while the SparkFun Inventor’s Kit for Arduino Uno includes an Arduino Uno R3. At the heart of each is the ATmega328p microcontroller, giving both the same functionality underneath the hood. Both development boards are capable of taking inputs (such as the push of a button or a reading from a light sensor) and interpreting that information to control various outputs (like a blinking LED light or an electric motor). And much, much more!

Note: The Arduino Uno version of the kit does not include a carrying case or printed copy of this manual to decrease weight and cost for international shipping.
Note: You can complete all 16 experiments in this guide with either kit.

If you need more information to determine which microcontroller is right for you, please check out the following tutorials.

RedBoard Hookup Guide

January 7, 2014

How to get your RedBoard up-and-blinking!

What is an Arduino?

February 26, 2013

What is this 'Arduino' thing anyway?

Open Source!

At SparkFun, our engineers and educators have been improving this kit and coming up with new experiments for a long time now. We would like to give attribution to Oomlout, since we originally started working off their Arduino Kit material many years ago. The Oomlut version is licensed under the Creative Commons Attribution Share-Alike 3.0 Unported License.

SparkFun’s version 3.3 is licensed under the Creative Commons Attribution Share-Alike International License.

Suggested Reading

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

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.

Polarity

An introduction to polarity in electronic components. Discover what polarity is, which parts have it, and how to identify it.

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 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!

Introduction: The Arduino Software (IDE) and Code

The following steps are a basic overview of getting started with the Arduino IDE. For more detailed, step-by-step instructions for setting up the Arduino IDE on your computer, please check out the following tutorial.

Installing Arduino IDE

March 26, 2013

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

Download the Arduino IDE

In order to get your microcontroller up and running, you’ll need to download the newest version of the Arduino software first (it’s free and open source!).

Download the Arduino IDE

This software, known as the Arduino IDE, will allow you to program the board to do exactly what you want. It’s like a word processor for writing code.

Connect the Microcontroller to your Computer

Use the USB cable provided in the SIK kit to connect the included microcontroller (RedBoard or Arduino Uno) to one of your computer’s USB inputs.

Install FTDI Drivers

Depending on your computer’s operating system, you will need to follow specific instructions. Please go to How to Install FTDI Drivers, for specific instructions on how to install the FTDI drivers onto your RedBoard.


How to Install FTDI Drivers

June 4, 2013

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

Select your board: Arduino Uno

Before we can start jumping into the experiments, there are a couple adjustments we need to make. This step is required to tell the Arduino IDE which of the many Arduino boards we have. Go up to the Tools menu. Then hover over Board and make sure Arduino Uno is selected.

Please note: Your SparkFun RedBoard and the Arduino UNO are interchangeable but you won’t find the RedBoard listed in the Arduino Software. Select “Arduino Uno” instead.

Select a Serial Port

Next up we need to tell the Arduino IDE which of our computer’s serial ports the microcontroller is connected to. For this, again go up to Tools, then hover over Port (Serial Port in older Arduino versions) and select your RedBoard or Arduino’s serial port.

Download Arduino Code

You are so close to to being done with setup! Download the SIK Guide Code. Click the following link to download the code:

SIK V3.3 Code

You can also download the code from GitHub.

Once you’ve unzipped the download, copy SIK-Guide-Code-V_3.3 into examples folder in the Arduino folder.

Experiment 1: Blinking an LED

Introduction

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

Parts Needed

You will need the following parts:

Suggested Reading

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

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram and hookup table below, to see how everything is connected.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

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

LED drawing

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

Bent resistor

Fritzing Diagram for RedBoard

alt text

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

Fritzing Diagram for Arduino

alt text

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

Open Your First Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 1 by accessing the SIK Guide Code you downloaded and placed into your examples folder earlier.

To open the code, go to: File > Examples > SIK Guide Code > SIK_circuit01_blink

alt text

Click the picture above for a larger, easier-to-view image

Alternatively, you can copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/* SparkFun Inventor's Kit
   Example sketch 01 -- BLINKING A LED

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

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

 Version 2.0 6/2012 MDG
 */

void setup()
{
  pinMode(13, OUTPUT);
}

void loop()
{
  digitalWrite(13, HIGH);   // Turn on the LED
  delay(1000);              // Wait for one second
  digitalWrite(13, LOW);    // Turn off the LED
  delay(1000);              // Wait for one second
}
/*
 / Try changing the 1000 in the above delay() functions to
 / different numbers and see how it affects the timing. Smaller
 / values will make the loop run faster. (Why?)
 /
 / Other challenges:
 /   * Decrease the delay to 10 ms. Can you still see it blink?
 /         Find the smallest delay that you can still see a blink. What is this frequency?
 /   * Modify the code above to resemble a heartbeat.
 */

Code to Note

pinMode(13, OUTPUT);

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

digitalWrite(13, HIGH);

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

What You Should See

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

Real World Application

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

alt text

Troubleshooting

LED Not Lighting Up?

LEDs will only work in one direction. Try taking it out of your breadboard, turning it 180 degrees, and reinserting it.

Program Not Uploading

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

Still No Success?

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

Experiment 2: Reading a Potentiometer

Introduction

In this circuit you’ll work with a potentiometer.

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

Parts Needed

You will need the following parts:

Suggested Reading

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

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram and hookup table below to see how everything is connected.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram for RedBoard

RedBoard Fritzing Potentiometer

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

Fritzing Diagram for Arduino

Arduino Uno Fritzing Potentiometer

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

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 2 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > examples > SIK Guide Code > SIK_circuit02_potentiometer

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

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

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

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

 Version 2.0 6/2012 MDG
 */

int sensorPin = A0;    // The potentiometer is connected to analog pin 0
int ledPin = 13;      // The LED is connected to digital pin 13
int sensorValue;    //We declare another integer variable to store the value of the potentiometer

void setup() // this function runs once when the sketch starts up
{
  pinMode(ledPin, OUTPUT);
}

void loop() // this function runs repeatedly after setup() finishes
{
  sensorValue = analogRead(sensorPin);

  digitalWrite(ledPin, HIGH);     // Turn the LED on
  delay(sensorValue);             // Pause for sensorValue in milliseconds
  digitalWrite(ledPin, LOW);      // Turn the LED off
  delay(sensorValue);             // Pause for sensorValue in milliseconds
}

Code To Note

int sensorValue;

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

sensorValue = analogRead(sensorPin);

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

delay(sensorValue);

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

What You Should See

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

Real World Application

Most traditional volume knobs employ a potentiometer.

Troubleshooting

Sporadically Working

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

Not Working

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

LED Not Lighting Up?

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

Experiment 3: Driving an RGB LED

Introduction

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

Parts Needed

You will need the following parts:

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram and hookup table below, to see how everything is connected.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram for RedBoard

RedBoard Circuit 3

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

Fritzing Diagram for Arduino

Arduino Circuit 3

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

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 3 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > examples > SIK Guide Code > SIK_circuit03_rgbLED

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/******************************************************************
 * SparkFun Inventor's Kit
 * Example sketch 03 -- RGB LED
 *
 * Make an RGB LED display a rainbow of colors!
 *
 * This sketch was written by SparkFun Electronics,
 * with lots of help from the Arduino community.
 * Visit http://learn.sparkfun.com/products/2 for SIK information.
 * Visit http://www.arduino.cc to learn about the Arduino.
 *
 * Version 2.0 6/2012 MDG
 * Version 2.1 9/2014 BCH
 *****************************************************************/
const int RED_PIN = 9;
const int GREEN_PIN = 10;
const int BLUE_PIN = 11;

const int DISPLAY_TIME = 1000;  // used in mainColors() to determine the
// length of time each color is displayed.

void setup()    //Configure the Arduino pins to be outputs to drive the LEDs
{
  pinMode(RED_PIN, OUTPUT);
  pinMode(GREEN_PIN, OUTPUT);
  pinMode(BLUE_PIN, OUTPUT);
}

void loop()
{
  mainColors();        // Red, Green, Blue, Yellow, Cyan, Purple, White
  //  showSpectrum();    // Gradual fade from Red to Green to Blue to Red
}

/******************************************************************
 * void mainColors()
 * This function displays the eight "main" colors that the RGB LED
 * can produce. If you'd like to use one of these colors in your
 * own sketch, you can copy and paste that section into your code.
/*****************************************************************/
void mainColors()
{
  // all LEDs off
  digitalWrite(RED_PIN, LOW);
  digitalWrite(GREEN_PIN, LOW);
  digitalWrite(BLUE_PIN, LOW);
  delay(DISPLAY_TIME);

  // Red
  digitalWrite(RED_PIN, HIGH);
  digitalWrite(GREEN_PIN, LOW);
  digitalWrite(BLUE_PIN, LOW);
  delay(DISPLAY_TIME);

  // Green
  digitalWrite(RED_PIN, LOW);
  digitalWrite(GREEN_PIN, HIGH);
  digitalWrite(BLUE_PIN, LOW);
  delay(DISPLAY_TIME);

  // Blue
  digitalWrite(RED_PIN, LOW);
  digitalWrite(GREEN_PIN, LOW);
  digitalWrite(BLUE_PIN, HIGH);
  delay(DISPLAY_TIME);

  // Yellow (Red and Green)
  digitalWrite(RED_PIN, HIGH);
  digitalWrite(GREEN_PIN, HIGH);
  digitalWrite(BLUE_PIN, LOW);
  delay(DISPLAY_TIME);

  // Cyan (Green and Blue)
  digitalWrite(RED_PIN, LOW);
  digitalWrite(GREEN_PIN, HIGH);
  digitalWrite(BLUE_PIN, HIGH);
  delay(DISPLAY_TIME);

  // Purple (Red and Blue)
  digitalWrite(RED_PIN, HIGH);
  digitalWrite(GREEN_PIN, LOW);
  digitalWrite(BLUE_PIN, HIGH);
  delay(DISPLAY_TIME);

  // White (turn all the LEDs on)
  digitalWrite(RED_PIN, HIGH);
  digitalWrite(GREEN_PIN, HIGH);
  digitalWrite(BLUE_PIN, HIGH);
  delay(DISPLAY_TIME);
}

/******************************************************************
 * void showSpectrum()
 *
 * Steps through all the colors of the RGB LED, displaying a rainbow.
 * showSpectrum() calls a function RGB(int color) that translates a number
 * from 0 to 767 where 0 = all RED, 767 = all RED
 *
 * Breaking down tasks down into individual functions like this
 * makes your code easier to follow, and it allows.
 * parts of your code to be re-used.
/*****************************************************************/

void showSpectrum()
{
  for (int x = 0; x <= 767; x++)
  {
    RGB(x);      // Increment x and call RGB() to progress through colors.
    delay(10);   // Delay for 10 ms (1/100th of a second) - to help the "smoothing"
  }
}

/******************************************************************
 * void RGB(int color)
 *
 * RGB(###) displays a single color on the RGB LED.
 * Call RGB(###) with the number of a color you want
 * to display. For example, RGB(0) displays pure RED, RGB(255)
 * displays pure green.
 *
 * This function translates a number between 0 and 767 into a
 * specific color on the RGB LED. If you have this number count
 * through the whole range (0 to 767), the LED will smoothly
 * change color through the entire spectrum.
 *
 * The "base" numbers are:
 * 0   = pure red
 * 255 = pure green
 * 511 = pure blue
 * 767 = pure red (again)
 *
 * Numbers between the above colors will create blends. For
 * example, 640 is midway between 512 (pure blue) and 767
 * (pure red). It will give you a 50/50 mix of blue and red,
 * resulting in purple.
/*****************************************************************/
void RGB(int color)
{
  int redIntensity;
  int greenIntensity;
  int blueIntensity;

  color = constrain(color, 0, 767); // constrain the input value to a range of values from 0 to 767

    // if statement breaks down the "color" into three ranges:
  if (color <= 255)       // RANGE 1 (0 - 255) - red to green
  {
    redIntensity = 255 - color;    // red goes from on to off
    greenIntensity = color;        // green goes from off to on
    blueIntensity = 0;             // blue is always off
  }
  else if (color <= 511)  // RANGE 2 (256 - 511) - green to blue
  {
    redIntensity = 0;                     // red is always off
    greenIntensity = 511 - color;         // green on to off
    blueIntensity = color - 256;          // blue off to on
  }
  else                    // RANGE 3 ( >= 512)- blue to red
  {
    redIntensity = color - 512;         // red off to on
    greenIntensity = 0;                 // green is always off
    blueIntensity = 767 - color;        // blue on to off
  }

  // "send" intensity values to the Red, Green, Blue Pins using analogWrite()
  analogWrite(RED_PIN, redIntensity);
  analogWrite(GREEN_PIN, greenIntensity);
  analogWrite(BLUE_PIN, blueIntensity);
}

Code To Note

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

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

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

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

What You Should See

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

Real World Application

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

Troubleshooting

LED Remains Dark or Shows Incorrect Color

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

Seeing Red

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

analogWrite(RED_PIN, redIntensity);

to

analogWrite(RED_PIN, redIntensity/3);

Experiment 4: Driving Multiple LEDs

Introduction

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

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

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

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

Parts Needed

You will need the following parts:

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram and hookup table below, to see how everything is connected.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram for RedBoard

alt text

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

Fritzing Diagram for Arduino

alt text

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

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 4 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > examples > SIK Guide Code > SIK_circuit04_multipleLEDs

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/******************************************************************
 * SparkFun Inventor's Kit
 * Example sketch 04 -- MULTIPLE LEDs
 *
 *   Make eight LEDs dance. Dance LEDs, dance!
 * This sketch was written by SparkFun Electronics,
 * with lots of help from the Arduino community.
 * Visit http://learn.sparkfun.com/products/2 for SIK information.
 * Visit http://www.arduino.cc to learn about the Arduino.
 *
 * Version 2.0 6/2012 MDG
 * Version 2.1 9/2014 BCH
/*****************************************************************/

int ledPins[] = {2,3,4,5,6,7,8,9};   // Defines an array to store the pin numbers of the 8 LEDs.
// An array is like a list variable that can store multiple numbers.
// Arrays are referenced or "indexed" with a number in the brackets [ ]. See the examples in
// the pinMode() functions below.

void setup()
{
  // setup all 8 pins as OUTPUT - notice that the list is "indexed" with a base of 0.
  pinMode(ledPins[0],OUTPUT);  // ledPins[0] = 2
  pinMode(ledPins[1],OUTPUT);  // ledPins[1] = 3
  pinMode(ledPins[2],OUTPUT);  // ledPins[2] = 4
  pinMode(ledPins[3],OUTPUT);  // ledPins[3] = 5
  pinMode(ledPins[4],OUTPUT);  // ledPins[4] = 6
  pinMode(ledPins[5],OUTPUT);  // ledPins[5] = 7
  pinMode(ledPins[6],OUTPUT);  // ledPins[6] = 8
  pinMode(ledPins[7],OUTPUT);  // ledPins[7] = 9
}

void loop()
{

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

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

  //oneOnAtATime();         // Turn on one LED at a time,

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

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

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



/******************************************************************
 * oneAfterAnother()
 *
 * This function turns all the LEDs on, pauses, and then turns all
 * the LEDS off. The function takes advantage of for() loops and
 * the array to do this with minimal typing.
/*****************************************************************/
void oneAfterAnother()
{
  int index;
  int delayTime = 100; // milliseconds to pause between LEDs
                       // make this smaller for faster switching

  // Turn all the LEDs on:
  for(index = 0; index <= 7; index = index++)  // step through index from 0 to 7
  {
    digitalWrite(ledPins[index], HIGH);
    delay(delayTime);
  }

  // Turn all the LEDs off:
  for(index = 7; index >= 0; index = index--)  // step through index from 7 to 0
  {
    digitalWrite(ledPins[index], LOW);
    delay(delayTime);
  }
}

/*****************************************************************
 * oneOnAtATime()
 *
 * This function will step through the LEDs, lighting only one at
 * a time. It turns each LED ON and then OFF before going to the
 * next LED.
/****************************************************************/

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

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

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


/*****************************************************************
 * pingPong()
 *
 * This function will step through the LEDs, lighting one at at
 * time in both directions. There is no delay between the LED off
 * and turning on the next LED. This creates a smooth pattern for
 * the LED pattern.
/****************************************************************/
void pingPong()
{
  int index;
  int delayTime = 100; // milliseconds to pause between LEDs

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

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

/*****************************************************************
 * marquee()
 *
 * This function will mimic "chase lights" like those around signs.
/****************************************************************/
void marquee()
{
  int index;
  int delayTime = 200; // milliseconds to pause between LEDs

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

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

/*****************************************************************
 * randomLED()
 *
 * This function will turn on random LEDs. Can you modify it so it
 * also lights them for random times?
/****************************************************************/
void randomLED()
{
  int index;
  int delayTime;

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

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

Code To Note

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

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

digitalWrite(ledPins[0], HIGH);

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

index = random(8);

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

What You Should See

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

Real World Application

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

Troubleshooting

Some LEDs Fail to Light

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

Operating out of sequence

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

Starting Fresh

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

Experiment 5: Push Buttons

Introduction

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

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

Parts Needed

You will need the following parts:

Suggested Reading

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

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram and hookup table below, to see how everything is connected.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram for RedBoard

alt text

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

Fritzing Diagram for Arduino

alt text

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

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 5 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > examples > SIK Guide Code > SIK_circuit05_pushButton

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/******************************************************************
 * SparkFun Inventor's Kit
 * Example sketch 05 -- PUSH BUTTONS
 *
 *   Use pushbuttons for digital input
 *
 *   Connect one side of the pushbutton to GND, and the other
 *   side to a digital pin. When we press down on the pushbutton,
 *   the pin will be connected to GND, and therefore will be read
 *   as "LOW" by the Arduino.
 *
 * This sketch was written by SparkFun Electronics,
 * with lots of help from the Arduino community.
 * This code is completely free for any use.
 * Visit http://learn.sparkfun.com/products/2 for SIK information.
 * Visit http://www.arduino.cc to learn about the Arduino.
 *
 * Version 2.0 6/2012 MDG
 * Version 2.1 9/2014 BCH
/*****************************************************************/

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

int button1State, button2State;  // variables to hold the pushbutton states


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

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

void loop()
{
  button1State = digitalRead(button1Pin);
  button2State = digitalRead(button2Pin);

  // if button1 or button 2 are pressed (but not both)
  if (((button1State == LOW) && (button2State == HIGH)) || ((button1State == HIGH) && (button2State == LOW)))
  {
    digitalWrite(ledPin, HIGH);  // turn the LED on
  }
  else
  {
    digitalWrite(ledPin, LOW);  // turn the LED off
  }
}

Code To Note

pinMode(button2Pin, INPUT);

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

button1State = digitalRead(button1Pin);

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

if (button1State == LOW)

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

What You Should See

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

Real World Application

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

Troubleshooting

Light Not Turning On

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

Underwhelmed

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

Experiment 6: Reading a Photoresistor

Introduction

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

Parts Needed

You will need the following parts:

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram for RedBoard

alt text

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

Fritzing Diagram for Arduino

alt text

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

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 06 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > examples > SIK Guide Code > SIK_circuit06_photoResistor

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/******************************************************************
 * SparkFun Inventor's Kit
 * Example sketch 06
 *
 * PHOTO RESISTOR
 *
 * Use a photoresistor (light sensor) to control the brightness
 * of a LED.
 *
 * This sketch was written by SparkFun Electronics,
 * with lots of help from the Arduino community.
 * This code is completely free for any use.
 * Visit http://learn.sparkfun.com/products/2 for SIK information.
 * Visit http://www.arduino.cc to learn about the Arduino.
 *
 * Version 2.0 6/2012 MDG
 * Version 2.1 9/2014 BCH
/*****************************************************************/

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

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

// We'll also set up some global variables for the light level:
int lightLevel;
int calibratedlightLevel; // used to store the scaled / calibrated lightLevel
int maxThreshold = 0;     // used for setting the "max" light level
int minThreshold = 1023;   // used for setting the "min" light level

void setup()
{
  pinMode(ledPin, OUTPUT);    // Set up the LED pin to be an output.
  Serial.begin(9600);
}

void loop()
{
  lightLevel = analogRead(sensorPin);  // reads the voltage on the sensorPin
  Serial.print(lightLevel);
  //autoRange();  // autoRanges the min / max values you see in your room.

  calibratedlightLevel = map(lightLevel, 0, 1023, 0, 255);  // scale the lightLevel from 0 - 1023 range to 0 - 255 range.
                                                  // the map() function applies a linear scale / offset.
                                                  // map(inputValue, fromMin, fromMax, toMin, toMax);
  Serial.print("\t");         // tab character
  Serial.print(calibratedlightLevel);   // println prints an CRLF at the end (creates a new line after)

  analogWrite(ledPin, calibratedlightLevel);    // set the led level based on the input lightLevel.
}
/******************************************************************
 * void autoRange()
 *
 * This function sets a minThreshold and maxThreshold value for the
 * light levels in your setting. Move your hand / light source / etc
 * so that your light sensor sees a full range of values. This will
 * "autoCalibrate" to your range of input values.
/*****************************************************************/

void autoRange()
{
  if (lightLevel < minThreshold)  // minThreshold was initialized to 1023 -- so, if it's less, reset the threshold level.
    minThreshold = lightLevel;

  if (lightLevel > maxThreshold)  // maxThreshold was initialized to 0 -- so, if it's bigger, reset the threshold level.
    maxThreshold = lightLevel;

  // Once we have the highest and lowest values, we can stick them
  // directly into the map() function.
  //
  // This function must run a few times to get a good range of bright and dark values in order to work.

  lightLevel = map(lightLevel, minThreshold, maxThreshold, 0, 255);
  lightLevel = constrain(lightLevel, 0, 255);
}

Code To Note

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

Parameters

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

value: the number to map

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

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

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

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

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

lightLevel = constrain(lightLevel, 0, 255);

Parameters

constrain(x, a, b)

x: the number to constrain, all data types

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

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

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

What You Should See

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

Real World Application

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

Troubleshooting

LED Remains Dark

This is a mistake we continue to make time and time again, if only they could make an LED that worked both ways. Pull it out of the breadboard, and reinsert it turned 180 degrees.

It Isn’t Responding to Changes in Light

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

Still Not Quite Working

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

Experiment 7: Reading a Temperature Sensor

Introduction

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

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

Parts Needed

You will need the following parts:

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

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

Temperature Sensor

Fritzing Diagram for RedBoard

RedBoard Circuit 7

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

Fritzing Diagram for Arduino

Arduino Circuit 7

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

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 7 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > examples > SIK Guide Code > SIK_circuit07_tempSensor

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/******************************************************************
 SparkFun Inventor's Kit
 Example sketch 07 - TEMPERATURE SENSOR
  Use the "serial monitor" window to read a temperature sensor.
  The TMP36 is an easy-to-use temperature sensor that outputs
  a voltage that's proportional to the ambient temperature.
  You can use it for all kinds of automation tasks where you'd
  like to know or control the temperature of something.
  More information on the sensor is available in the datasheet:
  http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Sensors/Temp/TMP35_36_37.pdf
  Even more exciting, we'll start using the Arduino's serial port
  to send data back to your main computer! Up until now, we've
  been limited to using simple LEDs for output. We'll see that
  the Arduino can also easily output all kinds of text and data.
This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.
Version 2.0 6/2012 MDG
******************************************************************/


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

const int temperaturePin = A0;


void setup()
{

    Serial.begin(9600); //Initialize serial port & set baud rate to 9600 bits per second (bps)
}


void loop()
{


    float voltage, degreesC, degreesF; //Declare 3 floating point variables

    voltage = getVoltage(temperaturePin); //Measure the voltage at the analog pin

    degreesC = (voltage - 0.5) * 100.0; // Convert the voltage to degrees Celsius

    degreesF = degreesC * (9.0 / 5.0) + 32.0; //Convert degrees Celsius to Fahrenheit

    //Now print to the Serial monitor. Remember the baud must be 9600 on your monitor!
    // These statements will print lines of data like this:
    // "voltage: 0.73 deg C: 22.75 deg F: 72.96"

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

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


float getVoltage(int pin)   //Function to read and return
                            //floating-point value (true voltage)
                            //on analog pin
{

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

// Other things to try with this code:

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

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

Code To Note

Serial.begin(9600);

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

Serial.print(degreesC);

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

Serial.println(degreesF);

The Serial.println() has the same functionality except any serial data being printed after this command will start on the next line. By using both of these commands together, you can create easy-to-read printouts of text and data.

What You Should See

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

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

voltage: 0.73 deg C: 23.24 deg F: 73.84

voltage: 0.73 deg C: 23.24 deg F: 73.84

voltage: 0.73 deg C: 22.75 deg F: 72.96

voltage: 0.73 deg C: 23.24 deg F: 73.84

voltage: 0.73 deg C: 23.24 deg F: 73.84

voltage: 0.73 deg C: 23.24 deg F: 73.84

voltage: 0.73 deg C: 22.75 deg F: 72.96

voltage: 0.73 deg C: 23.24 deg F: 73.84

voltage: 0.73 deg C: 22.75 deg F: 72.96

voltage: 0.73 deg C: 22.75 deg F: 72.96

voltage: 0.73 deg C: 23.24 deg F: 73.84

voltage: 0.73 deg C: 22.75 deg F: 72.96

voltage: 0.73 deg C: 23.24 deg F: 73.84

Real World Application

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

Troubleshooting

Nothing Seems to Happen

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

Gibberish is Displayed

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

Temperature Value is Unchanging

Try pinching the sensor with your fingers to heat it up or pressing a bag of ice against it to cool it down. Also, make sure that the wires are connected properly to the temperature sensor.

Warm to the Touch

Make sure that you wired the temperature sensor correctly. The temperature sensor can get warm to the touch if it is wired incorrectly. You would need to disconnect your microcontroller, rewire the circuit, connect it back to your computer, and open the serial monitor.

Experiment 8: Driving a Servo Motor

Introduction

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

Parts Needed

You will need the following parts:

Suggested Reading

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

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

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

Servo Jumpers

Fritzing Diagram for RedBoard

alt text

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

Fritzing Diagram for Arduino

alt text

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

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 08 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > examples > SIK Guide Code > SIK_circuit08-1_servoSweep

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Inventor's Kit
Example sketch 08-1
SINGLE SERVO
  Sweep a servo back and forth through its full range of motion.
  A "servo", short for servomotor, is a motor that includes
  feedback circuitry that allows it to be commanded to move to
  specific positions. This one is very small, but larger servos
  are used extensively in robotics to control mechanical arms,
  hands, etc. You could use it to make a (tiny) robot arm,
  aircraft control surface, or anywhere something needs to be
  moved to specific positions.
This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.
Version 2.0 6/2012 MDG
*/


#include <Servo.h>  // servo library


Servo servo1;  // servo control object


void setup()
{

  servo1.attach(9, 900, 2100);  //Connect the servo to pin 9
                                //with a minimum pulse width of
                                //900 and a maximum pulse width of
                                //2100.

}


void loop()
{
  int position;

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

  // Change position at full speed:

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

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

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

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

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

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


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

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

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

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

Code To Note

#include <Servo.h>

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

Servo servo1;

servo1.attach(9);

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

servo1.write(180);

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

What You Should See

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

Real World Application

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

Troubleshooting

Servo Not Twisting

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

Still Not Working

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

Fits and Starts

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

More Servo Fun!

Now that you know the basics of working with servos, try to figure out how to make your servo move using the following code.

To open the code go to: File > examples > SIK Guide Code > SIK_circuit08-2_serialServo

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:c
    /*
SparkFun Inventor's Kit
Example sketch 08-2
SINGLE SERVO
  Sweep a servo back and forth through its full range of motion.
  A "servo", short for servomotor, is a motor that includes
  feedback circuitry that allows it to be commanded to move to
  specific positions. This one is very small, but larger servos
  are used extensively in robotics to control mechanical arms,
  hands, etc. You could use it to make a (tiny) robot arm,
  aircraft control surface, or anywhere something needs to be
  moved to specific positions.
This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.
Version 2.0 6/2012 MDG
*/


#include <Servo.h>  // servo library

Servo servo1;  // servo control object

int angle;

void setup()
{
  servo1.attach(9, 900, 2100);
  Serial.begin(9600);
}


void loop()
{
  serialServo();
}


void serialServo()
{
  int speed;

  Serial.println("Type an angle (0-180) into the box above,");
  Serial.println("then click [send] or press [return]");
  Serial.println();  // Print a blank line

  // In order to type out the above message only once,
  // we'll run the rest of this function in an infinite loop:

  while(true)  // "true" is always true, so this will loop forever.
  {
    // First we check to see if incoming data is available:

    while (Serial.available() > 0)
    {
      // If it is, we'll use parseInt() to pull out any numbers:
      angle = Serial.parseInt();

      // Because servo.write() only works with numbers from
      // 0 to 180, we'll be sure the input is in that range:

      angle = constrain(angle, 0, 180);

      // We'll print out a message to let you know that the
      // number was received:

      Serial.print("Setting angle to ");
      Serial.println(angle);

      // And finally, we'll move the servo to its new position!

      servo1.write(angle);
    }
  }
}

Hint: if you don’t see any servo movement, try reading the comments in the code!

Experiment 9: Using a Flex Sensor

Introduction

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

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

Parts Needed

You will need the following parts:

Suggested Reading

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

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

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

Fritzing Diagram for RedBoard

RedBoard Circuit 9

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

Fritzing Diagram for Arduino

Arduino Circuit 9

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

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 9 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > Examples > SIK Guide Code > SIK_circuit09_flexSensor

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
 /*
SparkFun Inventor's Kit
Example sketch 09
FLEX SENSOR
  Use the "flex sensor" to change the position of a servo

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

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

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


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

#include <Servo.h>

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

const int flexPin = A0; //Define analog input pin to measure
                        //flex sensor position.


void setup()
{

  Serial.begin(9600); //Set serial baud rate to 9600 bps

  servo1.attach(9); // Enable control of a servo on pin 9
}


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

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

  flexPosition = analogRead(flexPin);


  servoPosition = map(flexPosition, 600, 900, 0, 180);
  servoPosition = constrain(servoPosition, 0, 180);

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

  servo1.write(servoPosition);


  Serial.print("sensor: ");
  Serial.print(flexPosition);
  Serial.print("  servo: ");
  Serial.println(servoPosition);


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

Code To Note

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

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

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

servoposition = constrain(servoposition, 0, 180);

constrain(x, a, b)

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

What You Should See

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

Real World Application

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

Troubleshooting

Servo Not Twisting

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

Servo Not Moving as Expected

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

Servo Doesn’t Move Very Far

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

Experiment 10: Reading a Soft Potentiometer

Introduction

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

Parts Needed

You will need the following parts:

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram for RedBoard

RedBoard Circuit 10

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

Fritzing Diagram for Arduino

Arduino Circuit 10

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

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 10 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > Examples > SIK Guide Code > SIK_circuit10_softPotentiometer

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
 /*
SparkFun Inventor's Kit
Example sketch 10
SOFT POTENTIOMETER
  Use the soft potentiometer to change the color
  of the RGB LED
  The soft potentiometer is a neat input device that detects
  pressure along its length. When you press it down with a finger
  (it works best on a flat surface), it will change resistance
  depending on where you're pressing it. You might use it to make
  a piano or light dimmer; here we're going to use it to control
  the color of an RGB LED.

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


// Constants for LED connections
const int RED_LED_PIN = 9;    // Red LED Pin
const int GREEN_LED_PIN = 10; // Green LED Pin
const int BLUE_LED_PIN = 11;  // Blue LED Pin

const int SENSOR_PIN = 0;      // Analog input pin

// Global PWM brightness values for the RGB LED.
// These are global so both loop() and setRGB() can see them.

int redValue, greenValue, blueValue;


void setup()
{
  // No need for any code here
  // analogWrite() sets up the pins as outputs
}


void loop()
{
  int sensorValue;

  sensorValue = analogRead(SENSOR_PIN); // Read the voltage from the softpot (0-1023)

  setRGB(sensorValue);  //Set a RGB LED to a position on the "rainbow" of all colors
                        //based on the sensorValue
}

void setRGB(int RGBposition)
{
  int mapRGB1, mapRGB2, constrained1, constrained2;

  mapRGB1 = map(RGBposition, 0, 341, 255, 0);
  constrained1 = constrain(mapRGB1, 0, 255);

  mapRGB2 = map(RGBposition, 682, 1023, 0, 255);
  constrained2 = constrain(mapRGB2, 0, 255);

  redValue = constrained1 + constrained2; //Create the red peak

  //Create the green peak
  //Note that we are nesting functions (which requires fewer variables)

  greenValue = constrain(map(RGBposition, 0, 341, 0, 255), 0, 255)
             - constrain(map(RGBposition, 341, 682, 0,255), 0, 255);

  //Create the blue peak
  blueValue = constrain(map(RGBposition, 341, 682, 0, 255), 0, 255)
            - constrain(map(RGBposition, 682, 1023, 0, 255), 0, 255);

 // Display the new computed "rainbow" color
  analogWrite(RED_LED_PIN, redValue);
  analogWrite(GREEN_LED_PIN, greenValue);
  analogWrite(BLUE_LED_PIN, blueValue);

  }

Code To Note

language:cpp
redValue = constrain(map(RGBposition, 0, 341, 255, 0), 0, 255)
 + constrain(map(RGBposition, 682, 1023, 0, 255), 0, 255);


greenValue = constrain(map(RGBposition, 0, 341, 0, 255), 0, 255)
 - constrain(map(RGBposition, 341, 682, 0,255), 0, 255);


blueValue = constrain(map(RGBposition, 341, 682, 0, 255), 0, 255)
- constrain(map(RGBposition, 682, 1023, 0, 255), 0, 255);

These big, scary functions take a single Value (RGBposition) and calculate the three RGB values necessary to create a rainbow of color. The functions create three “peaks” for the red, green, and blue values, which overlap to mix and create new colors. See the code for more information! Even if you’re not 100% clear how it works, you can copy and paste this (or any) function into your own code and use it yourself.

What You Should See

You should see the RGB LED change colors in accordance with how you interact with the soft potentiometer. If it isn’t working, make sure you have assembled the circuit correctly and verified and uploaded the code to your board, or see the troubleshooting section.

Real World Application

The knobs found on many objects, like a radio for instance, are using similar concepts to the one you just completed for this circuit.

Troubleshooting

LED Remains Dark or Shows Incorrect Color

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

Bizarre Results

The most likely cause of this is if you’re pressing the potentiometer in more than one position. This is normal and can actually be used to create some neat results.

Experiment 11: Using a Piezo Buzzer

Introduction

In this circuit, we’ll again bridge the gap between the digital world and the analog world. We’ll be using a piezo buzzer that makes a small “click” when you apply voltage to it (try it!). By itself that isn’t terribly exciting, but if you turn the voltage on and off hundreds of times a second, the piezo buzzer will produce a tone. And if you string a bunch of tones together, you’ve got music! This circuit and sketch will play a classic tune. We’ll never let you down!

Parts Needed

You will need the following parts:

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram for RedBoard

alt text

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

Fritzing Diagram for Arduino

alt text

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

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 11 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > Examples > SIK Guide Code > SIK_circuit11_buzzer

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
 /******************************************************************
 * SparkFun Inventor's Kit
 * Example sketch 11
 *
 * BUZZER
 *
 * This sketch uses the buzzer to play songs.
 * The Arduino's tone() command will play notes of a given frequency.
 *
 * This sketch was written by SparkFun Electronics,
 * with lots of help from the Arduino community.
 * (This sketch was originally developed by D. Cuartielles for K3)
 * This code is completely free for any use.
 * Visit http://learn.sparkfun.com/products/2 for SIK information.
 * Visit http://www.arduino.cc to learn about the Arduino.
 *
 * Version 2.0 6/2012 MDG
 * Version 2.1 9/2014 BCH
 *****************************************************************/



const int buzzerPin = 9;    // connect the buzzer to pin 9
const int songLength = 18;  // sets the number of notes of the song

// Notes is an array of text characters corresponding to the notes
// in your song. A space represents a rest (no tone)

char notes[songLength] = {
  'c', 'd', 'f', 'd', 'a', ' ', 'a', 'g', ' ', 'c', 'd', 'f', 'd', 'g', ' ', 'g', 'f', ' '};

// beats[] is an array of values for each note. A "1" represents a quarter-note,
// "2" a half-note, and "4" a quarter-note.
// Don't forget that the rests (spaces) need a length as well.

int beats[songLength] = {
  1, 1, 1, 1, 1, 1, 4, 4, 2, 1, 1, 1, 1, 1, 1, 4, 4, 2};

int tempo = 113;  // The tempo is how fast to play the song (beats per second).

void setup()
{
  pinMode(buzzerPin, OUTPUT);  // sets the  buzzer pin as an OUTPUT
}


void loop()
{
  int i, duration; //

  for (i = 0; i < songLength; i++) // for loop is used to index through the arrays
  {
    duration = beats[i] * tempo;  // length of note/rest in ms

    if (notes[i] == ' ')          // is this a rest?
      delay(duration);            // then pause for a moment
    else                          // otherwise, play the note
    {
      tone(buzzerPin, frequency(notes[i]), duration);
      delay(duration);            // wait for tone to finish
    }
    delay(tempo/10);              // brief pause between notes
  }

  while(true){
  // We only want to play the song once, so we pause forever
  }
  // If you'd like your song to play over and over, remove the while(true)
  // statement above
}

int frequency(char note)
{
  int i;
  const int numNotes = 8;  // number of notes we're storing
  char names[numNotes] = {
    'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C'    };
  int frequencies[numNotes] = {
    262, 294, 330, 349, 392, 440, 494, 523    };

  // Now we'll search through the letters in the array, and if
  // we find it, we'll return the frequency for that note.

  for (i = 0; i < numNotes; i++)  // Step through the notes
  {
    if (names[i] == note)         // Is this the one?
    {
      return(frequencies[i]);     // Yes! Return the frequency and exit function.
    }
  }
  return(0);  // We looked through everything and didn't find it,
  // but we still need to return a value, so return 0.
}

Code To Note

char notes[] = "cdfda ag cdfdg gf ";

char names[] = {'c','d','e','f','g','a','b','C'};

Up until now we’ve been working solely with numerical data, but the Arduino can also work with text. Characters (single, printable, letters, numbers and other symbols) have their own type, called “char”. When you have an array of characters, it can be defined between double-quotes (also called a “string”), OR as a list of single-quoted characters.

tone(pin, frequency, duration);

One of Arduino’s many useful built-in commands is the tone() function. This function drives an output pin at a certain frequency, making it perfect for driving buzzers and speakers. If you give it a duration (in milliseconds), it will play the tone then stop. If you don’t give it a duration, it will keep playing the tone forever (but you can stop it with another function, noTone() ).

What You Should See

You should see - well, nothing! But you should be able to hear a song. If it isn’t working, make sure you have assembled the circuit correctly and verified and uploaded the code to your board or see the troubleshooting section.

Real World Application

Many modern megaphones have settings that use a loud amplified buzzer. They are usually very loud and quite good at getting people’s attention.

Troubleshooting

No Sound

Given the size and shape of the piezo buzzer it is easy to miss the right holes on the breadboard. Try double checking its placement.

Can’t Think While the Melody is Playing

Just pull up the piezo buzzer or one of the wires whilst you think, upload your program then plug it back in.

Feeling Let Down and Deserted

The code is written so you can easily add your own songs.

Experiment 12: Driving a Motor

Introduction

Back in experiment 8, you got to work with a servo motor. Now, we are going to tackle spinning a motor. This requires the use of a transistor, which can switch a larger amount of current than the RedBoard or Arduino Uno R3 can.

When using a transistor, you just need to make sure its maximum specs are high enough for your use case. The transistor we are using for this circuit is rated at 50V max and 800 milliamps max – perfect for our toy motor! When the motor is spinning and suddenly turned off, the magnetic field inside it collapses, generating a voltage spike. This can damage the transistor. To prevent this, we use a “flyback diode”, which diverts the voltage spike around the transistor.

Parts Needed

You will need the following parts:

Suggested Reading

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

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Please note: When you’re building the circuit be careful not to mix up the transistor and the temperature sensor, they’re almost identical. Look for “BC337” on the body of the transistor.

Fritzing Diagram for RedBoard

RedBoard Circuit 12

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

Fritzing Diagram for Arduino

Arduino Circuit 12

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

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 12 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > Examples > SIK Guide Code > SIK_circuit12_motorSpin

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/********************************************************************
 * SparkFun Inventor's Kit
 * Example sketch 12
 *
 * SPINNING A MOTOR
 *
 * This example requires that you drive your motor using a switching
 * transistor. The Arduino is only capable of sourcing about 40 mA of
 * current per pin and a motor requires upwards of 150 mA.
 *
 * Look at the wiring diagram in the SIK Guide - Circuit #12 or read the
 * notes in the readme tab for more information on wiring.
 *
 * This sketch was written by SparkFun Electronics,
 * with lots of help from the Arduino community.
 * This code is completely free for any use.
 * Visit http://learn.sparkfun.com/products/2 for SIK information.
 * Visit http://www.arduino.cc to learn about the Arduino.
 *
 * Version 2.0 6/2012 MDG
 * Version 2.1 8/2014 BCH
 *******************************************************************/

const int motorPin = 9;  // Connect the base of the transistor to pin 9.
                         // Even though it's not directly connected to the motor,
                         // we'll call it the 'motorPin'

void setup()
{
  pinMode(motorPin, OUTPUT);  // set up the pin as an OUTPUT
  Serial.begin(9600);         // initialize Serial communications
}


void loop()
{ // This example basically replicates a blink, but with the motorPin instead.
  int onTime = 3000;  // milliseconds to turn the motor on
  int offTime = 3000; // milliseconds to turn the motor off

  analogWrite(motorPin, 255); // turn the motor on (full speed)
  delay(onTime);                // delay for onTime milliseconds
  analogWrite(motorPin, 0);  // turn the motor off
  delay(offTime);               // delay for offTime milliseconds

  // Uncomment the functions below by taking out the //. Look below for the
  // code examples or documentation.

  // speedUpandDown();
  // serialSpeed();
}

// This function accelerates the motor to full speed,
// then decelerates back down to a stop.
void speedUpandDown()
{
  int speed;
  int delayTime = 20; // milliseconds between each speed step

  // accelerate the motor
  for(speed = 0; speed <= 255; speed++)
  {
    analogWrite(motorPin,speed);    // set the new speed
    delay(delayTime);               // delay between speed steps
  }
  // decelerate the motor
  for(speed = 255; speed >= 0; speed--)
  {
    analogWrite(motorPin,speed);    // set the new speed
    delay(delayTime);               // delay between speed steps
  }
}


// Input a speed from 0-255 over the Serial port
void serialSpeed()
{
  int speed;

  Serial.println("Type a speed (0-255) into the box above,");
  Serial.println("then click [send] or press [return]");
  Serial.println();  // Print a blank line

  // In order to type out the above message only once,
  // we'll run the rest of this function in an infinite loop:

  while(true)  // "true" is always true, so this will loop forever.
  {
    // Check to see if incoming data is available:
    while (Serial.available() > 0)
    {
      speed = Serial.parseInt();  // parseInt() reads in the first integer value from the Serial Monitor.
      speed = constrain(speed, 0, 255); // constrains the speed between 0 and 255
                                        // because analogWrite() only works in this range.

      Serial.print("Setting speed to ");  // feedback and prints out the speed that you entered.
      Serial.println(speed);

      analogWrite(motorPin, speed);  // sets the speed of the motor.
    }
  }
}

Code To Note

while (Serial.available() > 0)

The Arduino’s serial port can be used to receive as well as send data. Because data could arrive at any time, the Arduino stores, or “buffers” data coming into the port until you’re ready to use it. The Serial.available() command returns the number of characters that the port has received, but haven’t been used by your sketch yet. Zero means no data has arrived.

speed = Serial.parseInt();

If the port has data waiting for you, there are a number of ways for you to use it. Since we’re typing numbers into the port, we can use the handy Serial.parseInt() command to extract, or “parse” integer numbers from the characters it’s received. If you type “1” “0” “0” to the port, this function will return the number 100.

What You Should See

The DC Motor should spin if you have assembled the circuit’s components correctly, and also verified/uploaded the correct code. If your circuit is not working check the troubleshooting section.

Real World Application

Radio Controlled (RC) cars use Direct Current (DC) motors to turn the wheels for propulsion.

Troubleshooting

Motor Not Spinning

If you sourced your own transistor, double check with the data sheet that the pinout is compatible with a BC337 (many are reversed).

Still No Luck

If you sourced your own motor, double check that it will work with 5 volts and that it does not draw too much power.

Still Not Working

Sometimes the Arduino will disconnect from the computer. Try un-plugging and then re-plugging it into your USB port.

Experiment 13: Using Relays

Introduction

In this circuit, we are going to use some of the lessons we learned in experiment 12 to control a relay. A relay is basically an electrically controlled mechanical switch. Inside that harmless looking plastic box is an electromagnet that, when it gets a jolt of energy, causes a switch to trip. In this circuit, you’ll learn how to control a relay like a pro – giving your Arduino even more powerful abilities!

Parts Needed

You will need the following parts:

Suggested Reading

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

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram for RedBoard

RedBoard Circuit 13

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

Fritzing Diagram for Arduino

Arduino Circuit 13

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

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 13 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > Examples > SIK Guide Code > SIK_circuit13_relays

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/********************************************************************
 * SparkFun Inventor's Kit
 * Example sketch 13
 *
 * RELAYS
 *
 * A relay is a electrically-controlled mechanical switch. It has an
 * electro-magnetic coil that either opens or closes a switch. Because
 * it is a physical switch, a relay can turn on and off large devices
 * like BIG motors, spot lights, and lamps.
 *
 * To create enough current to excite the electro-magnet, we need to use
 * the transistor circuit from the last example. Each time we excite the relay
 * you should hear an audible clicking sound of the switch.
 *
 * This sketch was written by SparkFun Electronics,
 * with lots of help from the Arduino community.
 * This code is completely free for any use.
 *
 * Visit http://learn.sparkfun.com/sik for SIK information.
 * Visit http://www.arduino.cc to learn about the Arduino.
 *
 * Version 2.0 6/2012 MDG
 * Version 2.1 8/2014 BCH
 *******************************************************************/

const int relayPin = 2;     // This pin drives the transistor (which drives the relay)
const int timeDelay = 1000; // delay in ms for on and off phases

// You can make timeDelay shorter, but note that relays, being
// mechanical devices, will wear out quickly if you try to drive
// them too fast.


void setup()
{
  pinMode(relayPin, OUTPUT);  // set pin as an output
}


void loop()
{
  digitalWrite(relayPin, HIGH);  // turn the relay on

  delay(timeDelay);              // wait for one second

  digitalWrite(relayPin, LOW);   // turn the relay off

  delay(timeDelay);              // wait for one second
}

Code To Note

digitalWrite(relayPin, HIGH);

When we turn on the transistor, which in turn energizes the relay’s coil, the relay’s switch contacts are closed. This connects the relay’s COM pin to the NO (Normally Open) pin. Whatever you’ve connected using these pins will turn on. (Here we’re using LEDs, but this could be almost anything.)

digitalWrite(relayPin, LOW);

The relay has an additional contact called NC (Normally Closed). The NC pin is connected to the COM pin when the relay is OFF. You can use either pin depending on whether something should be normally on or normally off. You can also use both pins to alternate power to two devices, much like railroad crossing warning lights.

What You Should See

You should be able to hear the relay contacts click, and see the two LEDs alternate illuminating at 1-second intervals. If you don’t, double-check that you have assembled the circuit correctly, and uploaded the correct sketch to the board. Also, see the troubleshooting section.

Real World Application

Garage door openers use relays to operate. You might be able to hear the clicking if you listen closely.

Troubleshooting

LEDs Not Lighting

Double-check that you’ve plugged them in correctly. The longer lead (and non-flat edge of the plastic flange) is the positive lead.

No Clicking Sound

The transistor or coil portion of the circuit isn’t quite working. Check the transistor is plugged in the right way.

Not Quite Working

The included relays are designed to be soldered rather than used in a breadboard. As such you may need to press it in to ensure it works (and it may pop out occasionally).

When you’re building the circuit be careful not to mix up the temperature sensor and the transistor, they’re almost identical.

Experiment 14: Using a Shift Register

Introduction

Now we are going to step into the world of ICs (integrated circuits). In this circuit, you’ll learn all about using a shift register (also called a serial-to-parallel converter). The shift register will give your RedBoard or Arduino Uno R3 an additional eight outputs, using only three pins on your board. For this circuit, you’ll practice by using the shift register to control eight LEDs.

Parts Needed

You will need the following parts:

Suggested Reading

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

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

For the shift register, align notch on top, in-between “e1” and “f1” on the breadboard. The notch indicates where pin 1 is.

Fritzing Diagram for RedBoard

RedBoard Circuit 14

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

Fritzing Diagram for Arduino

Arduino Circuit 14

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

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 14 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > Examples > SIK Guide Code > SIK_circuit14_shiftRegister

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Inventor's Kit
Example sketch 14
SHIFT REGISTER
  Use a shift register to turn three pins into eight (or more!)
  outputs
  An integrated circuit ("IC"), or "chip", is a self-contained
  circuit built into a small plastic package. (If you look closely
  at your Arduino board you'll see a number of ICs.) There are
  thousands of different types of ICs available that you can use
  to perform many useful functions.
  The 74HC595 shift register in your kit is an IC that has eight
  digital outputs. To use these outputs, we'll use a new interface
  called SPI (Serial Peripheral Interface). It's like the TX and
  RX you're used to, but has an additional "clock" line that
  controls the speed of the data transfer. Many parts use SPI
  for communications, so the Arduino offers simple commands called
  shiftIn() and shiftOut() to access these parts.
  This IC lets you use three digital pins on your Arduino to
  control eight digital outputs on the chip. And if you need
  even more outputs, you can daisy-chain multiple shift registers
  together, allowing an almost unlimited number of outputs from
  the same three Arduino pins! See the shift register datasheet
  for details:

  http://www.sparkfun.com/datasheets/IC/SN74HC595.pdf

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


// Pin definitions:
// The 74HC595 uses a type of serial connection called SPI
// (Serial Peripheral Interface) that requires three pins:

int datapin = 2;
int clockpin = 3;
int latchpin = 4;

// We'll also declare a global variable for the data we're
// sending to the shift register:

byte data = 0;


void setup()
{
  // Set the three SPI pins to be outputs:

  pinMode(datapin, OUTPUT);
  pinMode(clockpin, OUTPUT);
  pinMode(latchpin, OUTPUT);
}


void loop()
{

  // To try the different functions below, uncomment the one
  // you want to run, and comment out the remaining ones to
  // disable them from running.

  oneAfterAnother();      // All on, all off

  //oneOnAtATime();       // Scroll down the line

  //pingPong();           // Like above, but back and forth

  //randomLED();          // Blink random LEDs

  //marquee();

  //binaryCount();        // Bit patterns from 0 to 255
}


void shiftWrite(int desiredPin, boolean desiredState)

// This function lets you make the shift register outputs
// HIGH or LOW in exactly the same way that you use digitalWrite().

  bitWrite(data,desiredPin,desiredState); //Change desired bit to 0 or 1 in "data"

  // Now we'll actually send that data to the shift register.
  // The shiftOut() function does all the hard work of
  // manipulating the data and clock pins to move the data
  // into the shift register:

  shiftOut(datapin, clockpin, MSBFIRST, data); //Send "data" to the shift register

  //Toggle the latchPin to make "data" appear at the outputs
  digitalWrite(latchpin, HIGH);
  digitalWrite(latchpin, LOW);
}


void oneAfterAnother()
{
// This function will turn on all the LEDs, one-by-one,
// and then turn them off all off, one-by-one.

  int index;
  int delayTime = 100; // Time (milliseconds) to pause between LEDs
                       // Make this smaller for faster switching

  // Turn all the LEDs on
  for(index = 0; index <= 7; index++)
  {
    shiftWrite(index, HIGH);
    delay(delayTime);
  }

  // Turn all the LEDs off
  for(index = 7; index >= 0; index--)
  {
    shiftWrite(index, LOW);
    delay(delayTime);
  }
}


void oneOnAtATime()
{
// This function will turn the LEDs on and off, one-by-one.
  int index;
  int delayTime = 100; // Time (milliseconds) to pause between LEDs
                       // Make this smaller for faster switching

  // step through the LEDs, from 0 to 7

  for(index = 0; index <= 7; index++)
  {
    shiftWrite(index, HIGH);    // turn LED on
    delay(delayTime);       // pause to slow down the sequence
    shiftWrite(index, LOW); // turn LED off
  }
}

void pingPong()
{
// This function turns on the LEDs, one at a time, in both directions.
  int index;
  int delayTime = 100; // time (milliseconds) to pause between LEDs
                       // make this smaller for faster switching

  // step through the LEDs, from 0 to 7

  for(index = 0; index <= 7; index++)
  {
    shiftWrite(index, HIGH);    // turn LED on
    delay(delayTime);       // pause to slow down the sequence
    shiftWrite(index, LOW); // turn LED off
  }

  // step through the LEDs, from 7 to 0

  for(index = 7; index >= 0; index--)
  {
    shiftWrite(index, HIGH);    // turn LED on
    delay(delayTime);       // pause to slow down the sequence
    shiftWrite(index, LOW); // turn LED off
  }
}

void randomLED()
{
// This function will randomly turn on and off LEDs.
  int index;
  int delayTime = 100; // time (milliseconds) to pause between LEDs
                       // make this smaller for faster switching

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

  shiftWrite(index, HIGH);  // turn LED on
  delay(delayTime);     // pause to slow down the sequence
  shiftWrite(index, LOW);   // turn LED off
}

void marquee()
{
// This function will mimic "chase lights" like those around signs.
  int index;
  int delayTime = 200; // Time (milliseconds) to pause between LEDs
                       // Make this smaller for faster switching

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

  for(index = 0; index <= 3; index++)
  {
    shiftWrite(index, HIGH);    // Turn a LED on
    shiftWrite(index+4, HIGH);  // Skip four, and turn that LED on
    delay(delayTime);       // Pause to slow down the sequence
    shiftWrite(index, LOW); // Turn both LEDs off
    shiftWrite(index+4, LOW);
  }
}


void binaryCount()
{
// This function creates a visual representation of the on/off pattern
// of bits in a byte.

  int delayTime = 1000; // time (milliseconds) to pause between LEDs
                        // make this smaller for faster switching

  // Send the data byte to the shift register:

  shiftOut(datapin, clockpin, MSBFIRST, data);

  // Toggle the latch pin to make the data appear at the outputs:

  digitalWrite(latchpin, HIGH);
  digitalWrite(latchpin, LOW);

  // Add one to data, and repeat!
  // (Because a byte type can only store numbers from 0 to 255,
  // if we add more than that, it will "roll around" back to 0
  // and start over).

  data++;

  // Delay so you can see what's going on:

  delay(delayTime);
}

Code To Note

shiftOut(datapin, clockpin, MSBFIRST, data);

You’ll communicate with the shift register (and a lot of other parts) using an interface called SPI, or Serial Peripheral Interface. This interface uses a data line and a separate clock line that work together to move data into or out of the Arduino at high speed. The MSBFIRST parameter specifies the order in which to send the individual bits, in this case we’re sending the Most Significant Bit first.

bitWrite(data, desiredPin, desiredState);

Bits are the smallest possible piece of memory in a computer; each one can store either a “1” or a “0”. Larger numbers are stored as arrays of bits. Sometimes we want to manipulate these bits directly, for example now when we’re sending eight bits to the shift register and we want to make them 1 or 0 to turn the LEDs on or off. The Arduino has several commands, such as bitWrite(), that make this easy to do.

What You Should See

You should see the LEDs light up similarly to experiment 4 (but this time, you’re using a shift register). If they aren’t, make sure you have assembled the circuit correctly and verified and uploaded the code to your board. See the troubleshooting section.

Real World Application

Similar to experiment 4, a scrolling marquee display delivers a message with multiple LEDs. Essentially the same task the shift register achieves here in experiment 14. You might be asking yourself, “why bother using a shift register if we already have more than 8 outputs?” One reason is that you may have a project where you’ve already used up most of your output pins for other uses. A shift register allows you to add eight more output pins for the price of only three!

Troubleshooting

The Arduino’s power LED goes out

This happened to us a couple of times, it happens when the chip is inserted backward. If you fix it quickly nothing will break.

Not Quite Working

Sorry to sound like a broken record, but it is probably something as simple as a crossed wire.

Frustration

Shoot us an e-mail, this circuit is both simple and complex at the same time. We want to hear about problems you have so we can address them in future editions: techsupport@sparkfun.com

Experiment 15: Using an LCD

Introduction

In this circuit, you’ll learn about how to use an LCD. An LCD, or liquid crystal display, is a simple screen that can display commands, bits of information, or readings from your sensor - all depending on how you program your board. In this circuit, you’ll learn the basics of incorporating an LCD into your project.

Parts Needed

You will need the following parts:

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram for RedBoard

alt text

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

Fritzing Diagram for Arduino

alt text

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 15 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > Examples > SIK Guide Code > SIK_circuit15_LCDscreen

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Inventor's Kit
Example sketch 15
LIQUID CRYSTAL DISPLAY (LCD)
  A Liquid Crystal Display (LCD) is a sophisticated module
  that can be used to display text or numeric data. The display
  included in your SIK features two lines of 16 characters, and
  a backlight so it can be used at night.
  If you've been using the Serial Monitor to output data,
  you'll find that a LCD provides many of the same benefits
  without needing to drag a large computer around.
  This sketch will show you how to connect an LCD to your Arduino
  and display any data you wish.
This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.
Version 1.0 2/2013 MDG
*/

// Load the LiquidCrystal library, which will give us
// commands to interface to the LCD:

#include <LiquidCrystal.h>

// Initialize the library with the pins we're using.
// (Note that you can use different pins if needed.)
// See http://arduino.cc/en/Reference/LiquidCrystal
// for more information:

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup()
{

    lcd.begin(16, 2); //Initialize the 16x2 LCD


    lcd.clear();    //Clear any old data displayed on the LCD


    lcd.print("hello, world!"); // Display a message on the LCD!


}

void loop()
{

    lcd.setCursor(0, 1);    //Set the (invisible) cursor to column 0,
                            // row 1.

    lcd.print(millis() / 1000); //Print the number of seconds
                                //since the Arduino last reset.
}

Code To Note

#include <LiquidCrystal.h>

This bit of code tells your Arduino IDE to include the library for a simple LCD display. Without it, none of the commands will work, so make sure you include it!

lcd.print(“hello, world!”);

This is the first time you’ll fire something up on your screen. You may need to adjust the contrast to make it visible. Twist the potentiometer until you can clearly see the text!

What You Should See

Initially, you should see the words “hello, world!” pop up on your LCD. Remember you can adjust the contrast using the potentiometer if you can’t make out the words clearly. If you have any issues, make sure your code is correct and double-check your connections.

Real World Application

LCDs are everywhere! From advanced LCDs like your television, to simple notification screens, this is a very common and useful display!

The Screen is Blank or Completely Lit?

Fiddle with the contrast by twisting the potentiometer. If it’s incorrectly adjusted, you won’t be able to read the text.

Not Working At All?

Double check the code, specifically that you include the LCD library.

Screen Is Flickering

Double check your connections to your breadboard and Arduino.

Experiment 16: Simon Says

Introduction

Now that we’ve learned all the basics behind the components in the SIK experiments, let’s put them all together to make something fun! This circuit will show you how to create your own Simon Says game. Using some LEDs, some buttons, a buzzer, and some resistors, you can create this and other exciting games with the RedBoard or Arduino Uno R3.

Parts Needed

You will need the following parts:

Hardware Hookup

Ready to start hooking everything up? Check out the Fritzing diagram below, to see how everything is connected.

Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Fritzing Diagram for RedBoard

RedBoard Circuit 16

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

Fritzing Diagram for Arduino

Arduino Circuit 16

Open the Sketch

Open Up the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the code for Circuit 16 by accessing the “SIK Guide Code” you downloaded and placed into your “Examples” folder earlier.

To open the code go to: File > Examples > SIK Guide Code > SIK_circuit16_simonGame

You can also copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

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

 SIMON SAYS
 Simon Says is a memory game. Start the game by pressing one of the four buttons. When a button lights up,
 press the button, repeating the sequence. The sequence will get longer and longer. The game is won after
 13 rounds.
 Generates random sequence, plays music, and displays button lights.
 Simon tones from Wikipedia
 - A (red, upper left) - 440Hz - 2.272ms - 1.136ms pulse
 - a (green, upper right, an octave higher than A) - 880Hz - 1.136ms,
 0.568ms pulse
 - D (blue, lower left, a perfect fourth higher than the upper left)
 587.33Hz - 1.702ms - 0.851ms pulse
 - G (yellow, lower right, a perfect fourth higher than the lower left) -
 784Hz - 1.276ms - 0.638ms pulse
 Simon Says game originally written in C for the PIC16F88.
 Ported for the ATmega168, then ATmega328, then Arduino 1.0.
 Fixes and cleanup by Joshua Neal <joshua[at]trochotron.com>
 This sketch was written by SparkFun Electronics,
 with lots of help from the Arduino community.
 This code is completely free for any use.
 Visit http://www.arduino.cc to learn about the Arduino.

 */

/*************************************************
* Public Constants
*************************************************/
#define NOTE_B0 31
#define NOTE_C1 33
#define NOTE_CS1 35
#define NOTE_D1 37
#define NOTE_DS1 39
#define NOTE_E1 41
#define NOTE_F1 44
#define NOTE_FS1 46
#define NOTE_G1 49
#define NOTE_GS1 52
#define NOTE_A1 55
#define NOTE_AS1 58
#define NOTE_B1 62
#define NOTE_C2 65
#define NOTE_CS2 69
#define NOTE_D2 73
#define NOTE_DS2 78
#define NOTE_E2 82
#define NOTE_F2 87
#define NOTE_FS2 93
#define NOTE_G2 98
#define NOTE_GS2 104
#define NOTE_A2 110
#define NOTE_AS2 117
#define NOTE_B2 123
#define NOTE_C3 131
#define NOTE_CS3 139
#define NOTE_D3 147
#define NOTE_DS3 156
#define NOTE_E3 165
#define NOTE_F3 175
#define NOTE_FS3 185
#define NOTE_G3 196
#define NOTE_GS3 208
#define NOTE_A3 220
#define NOTE_AS3 233
#define NOTE_B3 247
#define NOTE_C4 262
#define NOTE_CS4 277
#define NOTE_D4 294
#define NOTE_DS4 311
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_FS4 370
#define NOTE_G4 392
#define NOTE_GS4 415
#define NOTE_A4 440
#define NOTE_AS4 466
#define NOTE_B4 494
#define NOTE_C5 523
#define NOTE_CS5 554
#define NOTE_D5 587
#define NOTE_DS5 622
#define NOTE_E5 659
#define NOTE_F5 698
#define NOTE_FS5 740
#define NOTE_G5 784
#define NOTE_GS5 831
#define NOTE_A5 880
#define NOTE_AS5 932
#define NOTE_B5 988
#define NOTE_C6 1047
#define NOTE_CS6 1109
#define NOTE_D6 1175
#define NOTE_DS6 1245
#define NOTE_E6 1319
#define NOTE_F6 1397
#define NOTE_FS6 1480
#define NOTE_G6 1568
#define NOTE_GS6 1661
#define NOTE_A6 1760
#define NOTE_AS6 1865
#define NOTE_B6 1976
#define NOTE_C7 2093
#define NOTE_CS7 2217
#define NOTE_D7 2349
#define NOTE_DS7 2489
#define NOTE_E7 2637
#define NOTE_F7 2794
#define NOTE_FS7 2960
#define NOTE_G7 3136
#define NOTE_GS7 3322
#define NOTE_A7 3520
#define NOTE_AS7 3729
#define NOTE_B7 3951
#define NOTE_C8 4186
#define NOTE_CS8 4435
#define NOTE_D8 4699
#define NOTE_DS8 4978

#define CHOICE_OFF      0 //Used to control LEDs
#define CHOICE_NONE     0 //Used to check buttons
#define CHOICE_RED  (1 << 0)
#define CHOICE_GREEN    (1 << 1)
#define CHOICE_BLUE (1 << 2)
#define CHOICE_YELLOW   (1 << 3)

#define LED_RED     10
#define LED_GREEN   3
#define LED_BLUE    13
#define LED_YELLOW  5

// Button pin definitions
#define BUTTON_RED    9
#define BUTTON_GREEN  2
#define BUTTON_BLUE   12
#define BUTTON_YELLOW 6

// Buzzer pin definitions
#define BUZZER1  4
#define BUZZER2  7

// Define game parameters
#define ROUNDS_TO_WIN      13 //Number of rounds to succesfully remember before you win. 13 is do-able.
#define ENTRY_TIME_LIMIT   3000 //Amount of time to press a button before game times out. 3000ms = 3 sec

#define MODE_MEMORY  0
#define MODE_BATTLE  1
#define MODE_BEEGEES 2

// Game state variables
byte gameMode = MODE_MEMORY; //By default, let's play the memory game
byte gameBoard[32]; //Contains the combination of buttons as we advance
byte gameRound = 0; //Counts the number of succesful rounds the player has made it through

void setup()
{
  //Setup hardware inputs/outputs. These pins are defined in the hardware_versions header file

  //Enable pull ups on inputs
  pinMode(BUTTON_RED, INPUT_PULLUP);
  pinMode(BUTTON_GREEN, INPUT_PULLUP);
  pinMode(BUTTON_BLUE, INPUT_PULLUP);
  pinMode(BUTTON_YELLOW, INPUT_PULLUP);

  pinMode(LED_RED, OUTPUT);
  pinMode(LED_GREEN, OUTPUT);
  pinMode(LED_BLUE, OUTPUT);
  pinMode(LED_YELLOW, OUTPUT);

  pinMode(BUZZER1, OUTPUT);
  pinMode(BUZZER2, OUTPUT);

  //Mode checking
  gameMode = MODE_MEMORY; // By default, we're going to play the memory game

  // Check to see if the lower right button is pressed
  if (checkButton() == CHOICE_YELLOW) play_beegees();

  // Check to see if upper right button is pressed
  if (checkButton() == CHOICE_GREEN)
  {
    gameMode = MODE_BATTLE; //Put game into battle mode

    //Turn on the upper right (green) LED
    setLEDs(CHOICE_GREEN);
    toner(CHOICE_GREEN, 150);

    setLEDs(CHOICE_RED | CHOICE_BLUE | CHOICE_YELLOW); // Turn on the other LEDs until you release button

    while(checkButton() != CHOICE_NONE) ; // Wait for user to stop pressing button

    //Now do nothing. Battle mode will be serviced in the main routine
  }

  play_winner(); // After setup is complete, say hello to the world
}

void loop()
{
  attractMode(); // Blink lights while waiting for user to press a button

  // Indicate the start of game play
  setLEDs(CHOICE_RED | CHOICE_GREEN | CHOICE_BLUE | CHOICE_YELLOW); // Turn all LEDs on
  delay(1000);
  setLEDs(CHOICE_OFF); // Turn off LEDs
  delay(250);

  if (gameMode == MODE_MEMORY)
  {
    // Play memory game and handle result
    if (play_memory() == true)
      play_winner(); // Player won, play winner tones
    else
      play_loser(); // Player lost, play loser tones
  }

  if (gameMode == MODE_BATTLE)
  {
    play_battle(); // Play game until someone loses

    play_loser(); // Player lost, play loser tones
  }
}

//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//The following functions are related to game play only

// Play the regular memory game
// Returns 0 if player loses, or 1 if player wins
boolean play_memory(void)
{
  randomSeed(millis()); // Seed the random generator with random amount of millis()

  gameRound = 0; // Reset the game to the beginning

  while (gameRound < ROUNDS_TO_WIN)
  {
    add_to_moves(); // Add a button to the current moves, then play them back

    playMoves(); // Play back the current game board

    // Then require the player to repeat the sequence.
    for (byte currentMove = 0 ; currentMove < gameRound ; currentMove++)
    {
      byte choice = wait_for_button(); // See what button the user presses

      if (choice == 0) return false; // If wait timed out, player loses

      if (choice != gameBoard[currentMove]) return false; // If the choice is incorect, player loses
    }

    delay(1000); // Player was correct, delay before playing moves
  }

  return true; // Player made it through all the rounds to win!
}

// Play the special 2 player battle mode
// A player begins by pressing a button then handing it to the other player
// That player repeats the button and adds one, then passes back.
// This function returns when someone loses
boolean play_battle(void)
{
  gameRound = 0; // Reset the game frame back to one frame

  while (1) // Loop until someone fails
  {
    byte newButton = wait_for_button(); // Wait for user to input next move
    gameBoard[gameRound++] = newButton; // Add this new button to the game array

    // Then require the player to repeat the sequence.
    for (byte currentMove = 0 ; currentMove < gameRound ; currentMove++)
    {
      byte choice = wait_for_button();

      if (choice == 0) return false; // If wait timed out, player loses.

      if (choice != gameBoard[currentMove]) return false; // If the choice is incorect, player loses.
    }

    delay(100); // Give the user an extra 100ms to hand the game to the other player
  }

  return true; // We should never get here
}

// Plays the current contents of the game moves
void playMoves(void)
{
  for (byte currentMove = 0 ; currentMove < gameRound ; currentMove++)
  {
    toner(gameBoard[currentMove], 150);

    // Wait some amount of time between button playback
    // Shorten this to make game harder
    delay(150); // 150 works well. 75 gets fast.
  }
}

// Adds a new random button to the game sequence, by sampling the timer
void add_to_moves(void)
{
  byte newButton = random(0, 4); //min (included), max (exluded)

  // We have to convert this number, 0 to 3, to CHOICEs
  if(newButton == 0) newButton = CHOICE_RED;
  else if(newButton == 1) newButton = CHOICE_GREEN;
  else if(newButton == 2) newButton = CHOICE_BLUE;
  else if(newButton == 3) newButton = CHOICE_YELLOW;

  gameBoard[gameRound++] = newButton; // Add this new button to the game array
}

//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//The following functions control the hardware

// Lights a given LEDs
// Pass in a byte that is made up from CHOICE_RED, CHOICE_YELLOW, etc
void setLEDs(byte leds)
{
  if ((leds & CHOICE_RED) != 0)
    digitalWrite(LED_RED, HIGH);
  else
    digitalWrite(LED_RED, LOW);

  if ((leds & CHOICE_GREEN) != 0)
    digitalWrite(LED_GREEN, HIGH);
  else
    digitalWrite(LED_GREEN, LOW);

  if ((leds & CHOICE_BLUE) != 0)
    digitalWrite(LED_BLUE, HIGH);
  else
    digitalWrite(LED_BLUE, LOW);

  if ((leds & CHOICE_YELLOW) != 0)
    digitalWrite(LED_YELLOW, HIGH);
  else
    digitalWrite(LED_YELLOW, LOW);
}

// Wait for a button to be pressed.
// Returns one of LED colors (LED_RED, etc.) if successful, 0 if timed out
byte wait_for_button(void)
{
  long startTime = millis(); // Remember the time we started the this loop

  while ( (millis() - startTime) < ENTRY_TIME_LIMIT) // Loop until too much time has passed
  {
    byte button = checkButton();

    if (button != CHOICE_NONE)
    {
      toner(button, 150); // Play the button the user just pressed

      while(checkButton() != CHOICE_NONE) ;  // Now let's wait for user to release button

      delay(10); // This helps with debouncing and accidental double taps

      return button;
    }

  }

  return CHOICE_NONE; // If we get here, we've timed out!
}

// Returns a '1' bit in the position corresponding to CHOICE_RED, CHOICE_GREEN, etc.
byte checkButton(void)
{
  if (digitalRead(BUTTON_RED) == 0) return(CHOICE_RED);
  else if (digitalRead(BUTTON_GREEN) == 0) return(CHOICE_GREEN);
  else if (digitalRead(BUTTON_BLUE) == 0) return(CHOICE_BLUE);
  else if (digitalRead(BUTTON_YELLOW) == 0) return(CHOICE_YELLOW);

  return(CHOICE_NONE); // If no button is pressed, return none
}

// Light an LED and play tone
// Red, upper left:     440Hz - 2.272ms - 1.136ms pulse
// Green, upper right:  880Hz - 1.136ms - 0.568ms pulse
// Blue, lower left:    587.33Hz - 1.702ms - 0.851ms pulse
// Yellow, lower right: 784Hz - 1.276ms - 0.638ms pulse
void toner(byte which, int buzz_length_ms)
{
  setLEDs(which); //Turn on a given LED

  //Play the sound associated with the given LED
  switch(which)
  {
  case CHOICE_RED:
    buzz_sound(buzz_length_ms, 1136);
    break;
  case CHOICE_GREEN:
    buzz_sound(buzz_length_ms, 568);
    break;
  case CHOICE_BLUE:
    buzz_sound(buzz_length_ms, 851);
    break;
  case CHOICE_YELLOW:
    buzz_sound(buzz_length_ms, 638);
    break;
  }

  setLEDs(CHOICE_OFF); // Turn off all LEDs
}

// Toggle buzzer every buzz_delay_us, for a duration of buzz_length_ms.
void buzz_sound(int buzz_length_ms, int buzz_delay_us)
{
  // Convert total play time from milliseconds to microseconds
  long buzz_length_us = buzz_length_ms * (long)1000;

  // Loop until the remaining play time is less than a single buzz_delay_us
  while (buzz_length_us > (buzz_delay_us * 2))
  {
    buzz_length_us -= buzz_delay_us * 2; //Decrease the remaining play time

    // Toggle the buzzer at various speeds
    digitalWrite(BUZZER1, LOW);
    digitalWrite(BUZZER2, HIGH);
    delayMicroseconds(buzz_delay_us);

    digitalWrite(BUZZER1, HIGH);
    digitalWrite(BUZZER2, LOW);
    delayMicroseconds(buzz_delay_us);
  }
}

// Play the winner sound and lights
void play_winner(void)
{
  setLEDs(CHOICE_GREEN | CHOICE_BLUE);
  winner_sound();
  setLEDs(CHOICE_RED | CHOICE_YELLOW);
  winner_sound();
  setLEDs(CHOICE_GREEN | CHOICE_BLUE);
  winner_sound();
  setLEDs(CHOICE_RED | CHOICE_YELLOW);
  winner_sound();
}

// Play the winner sound
// This is just a unique (annoying) sound we came up with, there is no magic to it
void winner_sound(void)
{
  // Toggle the buzzer at various speeds
  for (byte x = 250 ; x > 70 ; x--)
  {
    for (byte y = 0 ; y < 3 ; y++)
    {
      digitalWrite(BUZZER2, HIGH);
      digitalWrite(BUZZER1, LOW);
      delayMicroseconds(x);

      digitalWrite(BUZZER2, LOW);
      digitalWrite(BUZZER1, HIGH);
      delayMicroseconds(x);
    }
  }
}

// Play the loser sound/lights
void play_loser(void)
{
  setLEDs(CHOICE_RED | CHOICE_GREEN);
  buzz_sound(255, 1500);

  setLEDs(CHOICE_BLUE | CHOICE_YELLOW);
  buzz_sound(255, 1500);

  setLEDs(CHOICE_RED | CHOICE_GREEN);
  buzz_sound(255, 1500);

  setLEDs(CHOICE_BLUE | CHOICE_YELLOW);
  buzz_sound(255, 1500);
}

// Show an "attract mode" display while waiting for user to press button.
void attractMode(void)
{
  while(1)
  {
    setLEDs(CHOICE_RED);
    delay(100);
    if (checkButton() != CHOICE_NONE) return;

    setLEDs(CHOICE_BLUE);
    delay(100);
    if (checkButton() != CHOICE_NONE) return;

    setLEDs(CHOICE_GREEN);
    delay(100);
    if (checkButton() != CHOICE_NONE) return;

    setLEDs(CHOICE_YELLOW);
    delay(100);
    if (checkButton() != CHOICE_NONE) return;
  }
}

//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// The following functions are related to Beegees Easter Egg only

// Notes in the melody. Each note is about an 1/8th note, "0"s are rests.
int melody[] = {
  NOTE_G4, NOTE_A4, 0, NOTE_C5, 0, 0, NOTE_G4, 0, 0, 0,
  NOTE_E4, 0, NOTE_D4, NOTE_E4, NOTE_G4, 0,
  NOTE_D4, NOTE_E4, 0, NOTE_G4, 0, 0,
  NOTE_D4, 0, NOTE_E4, 0, NOTE_G4, 0, NOTE_A4, 0, NOTE_C5, 0};

int noteDuration = 115; // This essentially sets the tempo, 115 is just about right for a disco groove :)
int LEDnumber = 0; // Keeps track of which LED we are on during the beegees loop

// Do nothing but play bad beegees music
// This function is activated when user holds bottom right button during power up
void play_beegees()
{
  //Turn on the bottom right (yellow) LED
  setLEDs(CHOICE_YELLOW);
  toner(CHOICE_YELLOW, 150);

  setLEDs(CHOICE_RED | CHOICE_GREEN | CHOICE_BLUE); // Turn on the other LEDs until you release button

  while(checkButton() != CHOICE_NONE) ; // Wait for user to stop pressing button

  setLEDs(CHOICE_NONE); // Turn off LEDs

  delay(1000); // Wait a second before playing song

  digitalWrite(BUZZER1, LOW); // setup the "BUZZER1" side of the buzzer to stay low, while we play the tone on the other pin.

  while(checkButton() == CHOICE_NONE) //Play song until you press a button
  {
    // iterate over the notes of the melody:
    for (int thisNote = 0; thisNote < 32; thisNote++) {
      changeLED();
      tone(BUZZER2, melody[thisNote],noteDuration);
      // to distinguish the notes, set a minimum time between them.
      // the note's duration + 30% seems to work well:
      int pauseBetweenNotes = noteDuration * 1.30;
      delay(pauseBetweenNotes);
      // stop the tone playing:
      noTone(BUZZER2);
    }
  }
}

// Each time this function is called the board moves to the next LED
void changeLED(void)
{
  setLEDs(1 << LEDnumber); // Change the LED

  LEDnumber++; // Goto the next LED
  if(LEDnumber > 3) LEDnumber = 0; // Wrap the counter if needed
}

Code To Note

#define

The #define statement is used to create constants in your code. Constants are variables that will likely only have one value during the lifespan of your code. Thus, you can assign constants a value, and then use them throughout your code wherever. Then, if you need to change that value, you can change that one line instead of going through all the code to find every instance of that variable.

byte

Bytes are another variable type. In the world of computing, a byte is a chunk of space that contains 8 bits, and a bit is a single binary value. Binary is another way of counting and uses only 1’s and 0’s. So a byte can hold all 1’s: 11111111, all 0’s: 00000000, or a combination of the two: 10010110.

What You Should See

Once the code is uploaded, the buzzer will beep a few times, and all four LEDs should begin blinking. The game begins once you press any of the four buttons. Once the game has been started, a random LED will blink. Press the button associated with that color LED to replicate the pattern. With a successful guess, the pattern will repeat, this time adding another random LED. The player is to follow the pattern for as long as possible, with each successful guess resulting in an additional layer of complexity added to the original pattern.

Real World Application

Toys and Games, such as the original Simon from Milton Bradley, have relied on electronics to provide fun and entertainment to children across the world.

Troubleshooting

LEDs not working, but the buttons and sound do

If only half of you circuit is working, make sure you added the additional wire from one ground rail to the other. Remember that breadboards have two power rails on each side and that these can be connected, or bussed, together to provide the power to both sides of the same circuit.

No Sound

Once the piezo buzzer is in the breadboard, it’s hard to see the legs and to which row they are connected. If you aren’t hearing any sound, make sure your wires are on the same row as the piezo buzzer legs.

Game is Not Working

If everything starts up ok, but you’re having trouble when it comes time to play the game, you may have a button or two misplaced. Pay close attention to which pin is connected to each button as it matters which button is pressed when a particular color lights up.

Resources and Going Further

There are tons of sensors and shields you can hookup to an Arduino that will help take your projects to the next level. Here’s some further reading that may help you along in learning more about the world of electronics.


For more inspiration and ideas for working with your SIK, check out these tutorials:

SIK Keyboard Instrument

We can use the parts and concepts in the SparkFun Invetor's Kit to make a primitive keyboard instrument.

Measuring Internal Resistance of Batteries

Classroom STEM activity that has students build a battery from a lemon, measure the open and closed circuit voltages, and determine the battery's internal resistance.

For more info on Arduino, check out these tutorials:


For more hardware related tutorials, give these a read:


We also have additional kits available that cover different microcontrollers, development environments, and robotics.

SparkFun Inventor's Kit for Intel® Edison

KIT-13742
149.95
2
SparkFun Inventor's Kit for RedBot

ROB-12649
119.95
22
Raspberry Pi 3 Starter Kit

KIT-13826
89.95
27
SparkFun Inventor's Kit for Photon

KIT-13320
114.95
12
Johnny-Five Inventor's Kit

KIT-13847
124.95
9
mbed Starter Kit

KIT-12968
139.95
4
SparkFun Inventor's Kit for LabVIEW

KIT-13271
149.95
7
SparkFun Inventor's Kit for MicroView

KIT-13205
74.95
9

Reference files are available here:

Thanks for following along!


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

Getting Started With the Micro:bit

$
0
0

Getting Started With the Micro:bit a learn.sparkfun.com tutorial

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

Introduction

So you bought this thing called a micro:bit…what is it?

micro:bit

DEV-14208
16.5

The BBC micro:bit is a pocket-sized computer that lets you get creative with digital technology. You can code, customize and control your micro:bit from anywhere! You can use your micro:bit for all sorts of unique creations, from robots to musical instruments and more.

The micro:bit is the most recent project by the BBC in an effort to bring computer science education and STEM topics to every student in the United Kingdom. It is an open development board that works in sync with other onboard hardware components to get you started down the path of programming hardware.

At half the size of a credit card, you will be surprised at the amount of hardware each board is equipped with, including 25 red LED lights that can flash messages. There are two programmable buttons that can be used to control games or pause and skip songs on a playlist. The micro:bit can even detect motion and tell you which direction you’re heading. It can also use Bluetooth Low Energy (BLE) to interact with other devices and the Internet.

The micro:bit features an embedded compass and accelerometer, and mobile and web-based programming capabilities. It is compatible with a number of online code editors across a number of different languages. This guide will focus on MakeCode, a block or JavaScript-based environment that was developed by Microsoft.

Required Materials

To follow along with this tutorial, you will only need a micro:bit, and a micro USB cable. Pretty simple!

Hardware Overview

The micro:bit has a lot to offer when it comes to onboard inputs and outputs. In fact, there are so many things packed onto this little board that you would be hard pressed to really need anything else if you were looking at just exploring the basics of programming and hardware.

Front

On the front of the board there are a number of components that are pretty visible right off the bat!

alt text

  1. LED Array— The micro:bit has a 5x5 LED array that you can use as a tiny screen to draw on and display words, numbers and other information.
  2. A/B Buttons— Two buttons in all of their clicky glory: A is on the left, B is on the right, and both are prime for controlling a game of your design.
  3. Edge “Pins”— The gold tabs at the bottom of the board are for hooking up external components. The tabs with larger holes can be easily used with alligator clips to prototype things quickly!
  4. Light Sensor— A bit of a hidden gem. The LED array doubles as a light sensor!

Back

The back is where a lot of the magic happens. Check it out…

alt text

  1. Microcontroller— The brains of the outfit. The micro:bit is powered by a 16MHz ARM Cortex-M0 microcontroller with 256KB Flash and 16KB RAM.
  2. Accelerometer/Compass— The micro:bit has an onboard accelerometer that measures gravitational force, as well as a compass that can detect its orientation using Earth’s magnetic field.
  3. Bluetooth/Radio— Communication is huge with the micro:bit. You can communicate with your phone or tablet using Bluetooth Low Energy (BLE) or between two or more micro:bits using the standard “radio”
  4. Temperature Sensor— No, the drawing is not numbered incorrectly! The microcontroller doubles as a temperature sensor!
  5. USB Port— used to upload code to your micro:bit or power from your computer or laptop.
  6. Reset Button— A button to reset your micro:bit and start your code over from the beginning.
  7. JST Battery Connector— A connector to hook up an external battery pack to your micro:bit.

Phew! That is a lot of bells and whistles…a true Swiss army knife!

Hooking It Up

The micro:bit uses a microUSB cable to hook up to your computer or Chromebook. It is as simple as plugging the cable into your micro:bit and the other end into an open USB port.

alt text

Once you plug your board in, you should see the small yellow LED on the back of your micro:bit light up and possibly blink a few times. Then whatever existing program that was put on the micro:bit will start running. If this is your first time plugging your micro:bit in, go ahead and play around with it a bit — push buttons, shake it, and you will get a bit of an Easter egg.

Once your micro:bit boots up, check out your Finder if you are on a Mac, or your My Computer Drives if you are on a PC. The micro:bit should show up as an external storage device with two files stored in it.

alt text

If you are on a Chromebook, when you plug your micro:bit in you will be greeted with a dialog box to open the drive. Feel free to do so to make sure it works!

Let’s get programming!

Using MakeCode

This guide and most of SparkFun’s content around the micro:bit will use MakeCode by Microsoft for programming.

What Is MakeCode?

MakeCode is an open programming environment built by Microsoft for the micro:bit, as well as other boards. You can navigate to MakeCode for the micro:bit by following this link:

Launch MakeCode!

Once you have launched MakeCode, you will be greeted by its basic layout with a simulator on the left and a block-based environment on the right, as shown here.

alt text

Click on the image above for a larger view.

Let’s take a quick tour and check out what is available to us!

  1. Projects— A cloud storage system connected to your computer with no account setup required.
  2. Share— Allows you to share your project code in a number of different ways with your friends!
  3. Blocks/JavaScript— Choose your own adventure by programming in blocks (default) or in JavaScript.
  4. Program Space— This is where the magic happens and where you build your program…where you “make code.”
  5. Zoom/Undo-Redo— Sometimes you need to undo things, or zoom out and look around; these are the buttons for that.
  6. Name & Save— Name your program and save it (download it) to your computer.
  7. Download— Similar to Save, download your program as a .hex file and drag it into your micro:bit.
  8. Block Library— All of the options in terms of program building blocks, which are color-coded by function.
  9. Simulator Hide/Show— You can hide/show the simulator if you would like.
  10. Simulator— You don’t need hardware! MakeCode has a real-time simulator! As you change your program, you can see what it will do on this virtual micro:bit!

Phew! Now you have a choice - blocks or text-based programming?

Blocks or Text

For this guide and the majority of the content that you will find on SparkFun for the micro:bit, we will be using block-based programming examples.

alt text

But, if you so choose there is a JavaScript option to use as well. The choice is yours, and the good news is that you can switch back and forth from one to the other in the same program; one will populate the other, which is really nice if you are new to programming!

Simulator

MakeCode includes a simulator for the micro:bit, meaning if you don’t have your micro:bit in hand you can still write code for it. Or if you want to try out an idea before you upload it to your micro:bit, you can do that too!

alt text

The simulator will update as you build your code, and if you want to run it from the beginning you can click the stop and run buttons to start it over again!

Speaking of code, let’s write a quick program and get it onto your micro:bit!

Hello World!

Now comes the good stuff — writing your first program for your micro:bit in the MakeCode programming environment!

“Hello World” is the term we use to define that first program you write in a programming language or on a new piece of hardware. Essentially it is a simple piece of code that gives you a quick win (fingers crossed) and a first step in learning. It also gives you a chance to make sure everything is up and running and A-OK.

For your first “Hello World” we are going to create a simple animation on the LED array that repeats forever. If you just want the complete program you can see it here. To see a step-by-step explanation of how we built the program, continue reading!

Note: You may need to disable your ad/pop blocker to interact with the MakeCode programming environment and simulated circuit!

Building ‘Hello World’

A “Hello World” on the micro:bit is a little different than on a normal run-of-the-mill microcontroller. The micro:bit has no single LED to blink on its own, as you would find on the Arduino or similar boards. What the micro:bit does have is an LED array! So, the “Hello World” for the micro:bit is to draw something using the LED array!

When you open MakeCode you are greeted with two blocks: the On Start block and the forever block. The On Start block is all of your code that will execute at the very beginning of your program and only run once. The forever block is code that will loop over and over again…forever.

We are going to use the forever block for building this “Hello World.” We now need to start adding blocks to forever.

alt text

First, click on the Basics category. These blocks are, well, the basic building blocks of a BuildCode program. It will expand into a number of options. Click and drag the show leds block over and place it inside of your forever block. Notice that the block is keyed to fit inside of the forever block, and if you have the volume up on your computer you will hear a satisfying ‘click’ noise when you let go of the block.

alt text

The show leds block has an array of squares that symbolize the LED array. If you click on a square, it will turn red, which means that it is ‘on’. Draw a simple pixel art shape by turning different LEDs on or off; you should be able to see the outcome in your simulator on the lefthand side of your window.

alt text

To turn this static image into an animation we need another show leds block to place just under the first block. You can then make a second drawing with this set of rectangles. In your simulator you will see the images switching really, really fast. We need to slow this down!

To slow your animation down you will use the pause block, which is under the basic block set. The pause block is just what it says; it tells the micro:bit to pause and wait for a certain amount of time. Place two pause blocks in the program as shown.

alt text

The reason we are using two and placing one at the end is that this program is a loop. Without the block at the end, the image in your animation will change really, really fast.

We have built up an example in the next section where you can download the file and try it out on your own micro:bit, or use the simulator. If you want to play around with the code and make some changes, go ahead and click the Edit button in the widget, and it will open a MakeCode editor for you to start hacking “Hello World.” Enjoy!

Getting Your Program Onto Your Micro:bit

You’ve built your first program in MakeCode, and it works in your simulator. Now, how do you get it onto your micro:bit?

Download Your Program

Once you are happy with your program, you can click the Download button in MakeCode.

alt text

This will download your program file to your standard download location, probably the Downloads folder on your computer, or whatever location you have set in your download preference.

You then simply click and drag your program file from its download location to your micro:bit drive, which shows up as an external device.

alt text

That’s it!

Your micro:bit will flash for a few seconds, and then your program will start automatically. Yes! Win!

Note: You may need to disable your ad/pop blocker to see the simulated circuit!

Powering the Micro:bit

You have your program running on your micro:bit, but it is still tethered to your computer. There are a number of ways to solve this problem…batteries, batteries and more batteries!

USB Battery Pack

USB battery packs are becoming pretty commonplace out there. You can use one to run your micro:bit project for quite a long time.

alt text

It is handy to have a shorter USB cable to keep from dragging a super-long wire around.

AAA Battery Pack

The AAA battery pack is a great solution if you are looking to power a whole lot of micro:bits for a good amount of time, such as in a classroom setting.

alt text

These batteries can be purchased in bulk for pretty cheap.

Resources and Going Further

Now that you are familiar with the basics of the micro:bit, check out these additional resources for more inspiration!


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

Getting Started With the micro:bit

$
0
0

Getting Started With the micro:bit a learn.sparkfun.com tutorial

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

Introduction

So you bought this thing called a micro:bit…what is it?

micro:bit

DEV-14208
16.5

The BBC micro:bit is a pocket-sized computer that lets you get creative with digital technology. You can code, customize and control your micro:bit from anywhere! You can use your micro:bit for all sorts of unique creations, from robots to musical instruments and more.

The micro:bit is the most recent project by the BBC in an effort to bring computer science education and STEM topics to every student in the United Kingdom. It is an open development board that works in sync with other onboard hardware components to get you started down the path of programming hardware.

At half the size of a credit card, you will be surprised at the amount of hardware each board is equipped with, including 25 red LED lights that can flash messages. There are two programmable buttons that can be used to control games or pause and skip songs on a playlist. The micro:bit can even detect motion and tell you which direction you’re heading. It can also use Bluetooth Low Energy (BLE) to interact with other devices and the Internet.

The micro:bit features an embedded compass and accelerometer, and mobile and web-based programming capabilities. It is compatible with a number of online code editors across a number of different languages. This guide will focus on MakeCode, a block or JavaScript-based environment that was developed by Microsoft.

Required Materials

To follow along with this tutorial, you will only need a micro:bit, and a micro USB cable. Pretty simple!

Hardware Overview

The micro:bit has a lot to offer when it comes to onboard inputs and outputs. In fact, there are so many things packed onto this little board that you would be hard pressed to really need anything else if you were looking at just exploring the basics of programming and hardware.

Front

On the front of the board there are a number of components that are pretty visible right off the bat!

alt text

  1. LED Array— The micro:bit has a 5x5 LED array that you can use as a tiny screen to draw on and display words, numbers and other information.
  2. A/B Buttons— Two buttons in all of their clicky glory: A is on the left, B is on the right, and both are prime for controlling a game of your design.
  3. Edge “Pins”— The gold tabs at the bottom of the board are for hooking up external components. The tabs with larger holes can be easily used with alligator clips to prototype things quickly!
  4. Light Sensor— A bit of a hidden gem. The LED array doubles as a light sensor!

Back

The back is where a lot of the magic happens. Check it out…

alt text

  1. Microcontroller— The brains of the outfit. The micro:bit is powered by a 16MHz ARM Cortex-M0 microcontroller with 256KB Flash and 16KB RAM.
  2. Accelerometer/Compass— The micro:bit has an onboard accelerometer that measures gravitational force, as well as a compass that can detect its orientation using Earth’s magnetic field.
  3. Bluetooth/Radio— Communication is huge with the micro:bit. You can communicate with your phone or tablet using Bluetooth Low Energy (BLE) or between two or more micro:bits using the standard “radio”
  4. Temperature Sensor— No, the drawing is not numbered incorrectly! The microcontroller doubles as a temperature sensor!
  5. USB Port— used to upload code to your micro:bit or power from your computer or laptop.
  6. Reset Button— A button to reset your micro:bit and start your code over from the beginning.
  7. JST Battery Connector— A connector to hook up an external battery pack to your micro:bit.

Phew! That is a lot of bells and whistles…a true Swiss army knife!

Hooking It Up

The micro:bit uses a microUSB cable to hook up to your computer or Chromebook. It is as simple as plugging the cable into your micro:bit and the other end into an open USB port.

alt text

Once you plug your board in, you should see the small yellow LED on the back of your micro:bit light up and possibly blink a few times. Then whatever existing program that was put on the micro:bit will start running. If this is your first time plugging your micro:bit in, go ahead and play around with it a bit — push buttons, shake it, and you will get a bit of an Easter egg.

Once your micro:bit boots up, check out your Finder if you are on a Mac, or your My Computer Drives if you are on a PC. The micro:bit should show up as an external storage device with two files stored in it.

alt text

If you are on a Chromebook, when you plug your micro:bit in you will be greeted with a dialog box to open the drive. Feel free to do so to make sure it works!

Let’s get programming!

Using MakeCode

This guide and most of SparkFun’s content around the micro:bit will use MakeCode by Microsoft for programming.

What Is MakeCode?

MakeCode is an open programming environment built by Microsoft for the micro:bit, as well as other boards. You can navigate to MakeCode for the micro:bit by following this link:

Launch MakeCode!

Once you have launched MakeCode, you will be greeted by its basic layout with a simulator on the left and a block-based environment on the right, as shown here.

alt text

Click on the image above for a larger view.

Let’s take a quick tour and check out what is available to us!

  1. Projects— A cloud storage system connected to your computer with no account setup required.
  2. Share— Allows you to share your project code in a number of different ways with your friends!
  3. Blocks/JavaScript— Choose your own adventure by programming in blocks (default) or in JavaScript.
  4. Program Space— This is where the magic happens and where you build your program…where you “make code.”
  5. Zoom/Undo-Redo— Sometimes you need to undo things, or zoom out and look around; these are the buttons for that.
  6. Name & Save— Name your program and save it (download it) to your computer.
  7. Download— Similar to Save, download your program as a .hex file and drag it into your micro:bit.
  8. Block Library— All of the options in terms of program building blocks, which are color-coded by function.
  9. Simulator Hide/Show— You can hide/show the simulator if you would like.
  10. Simulator— You don’t need hardware! MakeCode has a real-time simulator! As you change your program, you can see what it will do on this virtual micro:bit!

Phew! Now you have a choice - blocks or text-based programming?

Blocks or Text

For this guide and the majority of the content that you will find on SparkFun for the micro:bit, we will be using block-based programming examples.

alt text

But, if you so choose there is a JavaScript option to use as well. The choice is yours, and the good news is that you can switch back and forth from one to the other in the same program; one will populate the other, which is really nice if you are new to programming!

Simulator

MakeCode includes a simulator for the micro:bit, meaning if you don’t have your micro:bit in hand you can still write code for it. Or if you want to try out an idea before you upload it to your micro:bit, you can do that too!

alt text

The simulator will update as you build your code, and if you want to run it from the beginning you can click the stop and run buttons to start it over again!

Speaking of code, let’s write a quick program and get it onto your micro:bit!

Hello World!

Now comes the good stuff — writing your first program for your micro:bit in the MakeCode programming environment!

“Hello World” is the term we use to define that first program you write in a programming language or on a new piece of hardware. Essentially it is a simple piece of code that gives you a quick win (fingers crossed) and a first step in learning. It also gives you a chance to make sure everything is up and running and A-OK.

For your first “Hello World” we are going to create a simple animation on the LED array that repeats forever. If you just want the complete program you can see it here. To see a step-by-step explanation of how we built the program, continue reading!

Note: You may need to disable your ad/pop blocker to interact with the MakeCode programming environment and simulated circuit!

Building ‘Hello World’

A “Hello World” on the micro:bit is a little different than on a normal run-of-the-mill microcontroller. The micro:bit has no single LED to blink on its own, as you would find on the Arduino or similar boards. What the micro:bit does have is an LED array! So, the “Hello World” for the micro:bit is to draw something using the LED array!

When you open MakeCode you are greeted with two blocks: the On Start block and the forever block. The On Start block is all of your code that will execute at the very beginning of your program and only run once. The forever block is code that will loop over and over again…forever.

We are going to use the forever block for building this “Hello World.” We now need to start adding blocks to forever.

alt text

First, click on the Basics category. These blocks are, well, the basic building blocks of a BuildCode program. It will expand into a number of options. Click and drag the show leds block over and place it inside of your forever block. Notice that the block is keyed to fit inside of the forever block, and if you have the volume up on your computer you will hear a satisfying ‘click’ noise when you let go of the block.

alt text

The show leds block has an array of squares that symbolize the LED array. If you click on a square, it will turn red, which means that it is ‘on’. Draw a simple pixel art shape by turning different LEDs on or off; you should be able to see the outcome in your simulator on the lefthand side of your window.

alt text

To turn this static image into an animation we need another show leds block to place just under the first block. You can then make a second drawing with this set of rectangles. In your simulator you will see the images switching really, really fast. We need to slow this down!

To slow your animation down you will use the pause block, which is under the basic block set. The pause block is just what it says; it tells the micro:bit to pause and wait for a certain amount of time. Place two pause blocks in the program as shown.

alt text

The reason we are using two and placing one at the end is that this program is a loop. Without the block at the end, the image in your animation will change really, really fast.

We have built up an example in the next section where you can download the file and try it out on your own micro:bit, or use the simulator. If you want to play around with the code and make some changes, go ahead and click the Edit button in the widget, and it will open a MakeCode editor for you to start hacking “Hello World.” Enjoy!

Getting Your Program Onto Your Micro:bit

You’ve built your first program in MakeCode, and it works in your simulator. Now, how do you get it onto your micro:bit?

Download Your Program

Once you are happy with your program, you can click the Download button in MakeCode.

alt text

This will download your program file to your standard download location, probably the Downloads folder on your computer, or whatever location you have set in your download preference.

You then simply click and drag your program file from its download location to your micro:bit drive, which shows up as an external device.

alt text

That’s it!

Your micro:bit will flash for a few seconds, and then your program will start automatically. Yes! Win!

Note: You may need to disable your ad/pop blocker to see the simulated circuit!

Powering the Micro:bit

You have your program running on your micro:bit, but it is still tethered to your computer. There are a number of ways to solve this problem…batteries, batteries and more batteries!

USB Battery Pack

USB battery packs are becoming pretty commonplace out there. You can use one to run your micro:bit project for quite a long time.

alt text

It is handy to have a shorter USB cable to keep from dragging a super-long wire around.

AAA Battery Pack

The AAA battery pack is a great solution if you are looking to power a whole lot of micro:bits for a good amount of time, such as in a classroom setting.

alt text

These batteries can be purchased in bulk for pretty cheap.

Resources and Going Further

Now that you are familiar with the basics of the micro:bit, check out these additional resources for more inspiration!


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

Building a Safe Cracking Robot

$
0
0

Building a Safe Cracking Robot a learn.sparkfun.com tutorial

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

Introduction

My wife is amazing; for Christmas this year, she gave me a fire safe she purchased off of Craigslist. It was super cheap because the seller didn’t have the combination. Best present ever.

Step 1) Get a safe that hasn’t been opened.

Step 2) Deploy robot army.

Cracked combination safe

Combination 24/0/66

We were able to crack our Craigslist safe in 40 minutes and 42 seconds! You can re-watch the live cracking, if you’d like. The magic moment occurs at 45:20, but start around 44:30 to get the full scope of what’s happening.

SparkFun Safe Cracker

Brute force robots for combination safes are not new. They are sometimes called an “Autodialer”. And, the robots that use audio feedback are sometimes called “SoftDrill”. The SparkFun Safe Cracker is a variant of the Autodialer. Instead of attempting every combination in the solution domain (called brute forcing), we use some tricks to reduce the domain and shortcuts to speed up the testing process. In addition, the SparkFun Safe Cracker is cheap (~$200), magnetically adheres to the safe, and is non-destructive; when we’re done you’ll never know we were there.

Isn't this a bad idea?

We believe knowledge and education is the best protection against fear and tyranny. The SparkFun Safe Cracker is designed to open very low security combination fire safes. There are high-end, secure, expensive combination safes available that have the ability to detect and thwart this type of dialer attack. Or, you could use a keypad safe.

Build Your Own!

We’ve documented and shared all the lessons we’ve learned in hopes that you can possibly build your own. You’ll need a 3D printer, soldering iron, and the ability to write code and modify 3D files to fit the type of safe you’re trying to open.

This is a complex build so here’s a list of documents:

All in all, we’ve spent about $200 on our safe cracker, which is a fraction of what professional devices cost.

For the latest files, check out the repo here.

Dial and Coupler

Dial coupler

The dial on our safe was modeled, and a coupler was 3D printed. This was attached to our motor with a 6mm clamping hub. We found that hubs with set screws would loosen quickly and wreak havoc with our control algorithms. Use a clamping hub!

We used a motor from Pololu for $40 that has the following specs

  • 12V motor
  • 350mA Free Run
  • 5A stall
  • 80RPM
  • 8400 counts per revolution

The counts per revolution was most important. We wanted a lower cost motor that had LOTS of resolution to measure the internal indents in disc C (covered in a later section). 12V was good because we had used a similar power supply and display for our Speed Trap project.

The encoder uses two interrupt pins connected to the interrupt pins on the Arduino. Once we zero the dial, the step count is used to determine on which digit the dial is.

Quick example:

100 / 8400 = 84 ticks per digit 3226 steps = dial number 34

It’s worth noting that the tolerances of the coupler to dial and the rigidness of the hub and motor mounts are important. Any slack in the system will cause problems later.

Home Calibration

We tried a few different methods to calibrate the dial. Originally, we tried a reed switch with a magnet built into the 3D printed coupler. This was a horrible idea: reed switches detect relative proximity but are bad at detecting exact location. I had a few instances where the reed switch would open when the magnet was directly under the switch and close again when the magnet moved a few millimeters away. Don’t use a reed switch.

Photo gate above dial coupler

We ended up using a photogate with a small flag designed into the coupler. It’s straightforward to detect when the gate is broken by the flag. When the robot is magnetically attached to the safe, the dial is in an unknown position. There’s an offset variable that can be set so that when you say, “go home”, the robot figures out that the flag is at dial position 43, and it needs to travel 57 more to arrive at home.

Once calibrated (and after lots of code revisions), we found that the control of the dial was very reliable. During cracking, we recalibrate every time we adjust disc A just to be safe.

Handle Puller

Handle puller with nautilus gear

We tried a few different methods to non-permanently attach to the handle. First, we had to model the safe handle then design and print a connector. It’s basically a shroud with an idler pin to rotate around with a 40 lbs cord attached to the end of the shroud. A small spring is used to bring the shroud and handle back to return position when the servo returns to the rest position. You don’t want to let the handle rest under its own weight or it might fall onto the dials and get caught in the indents on disc C.

We really wanted to use an off-the-shelf servo for cost and ease of use. A basic 83 oz-in servo worked ok, but it didn’t have enough throw to guarantee that it could pull the handle down far enough to the open position. Rob had the breakthrough: using a nautilus design we can apply increasing torque to the handle as the servo head pulls on the string. It works extremely well.

Additionally, we modified our servo to give us analog feedback (there are good tutorials 1 and 2 on how to do this). Analog feedback is important; when you tell the servo head to go to position 175, did it actually get there? Doing an analogRead() lets us know if we’ve arrived.

To detect if the safe is opened, we tell the servo to pull on the handle by going to PWM value 80. If we’ve dialed in the right combination, the the servo is free to fully pull down and move to this PWM value. The analog value when the handle is pulled down is approximately 273. If the servo gets blocked (wrong combination) the servo’s analog feedback will be less than 250. The tryHandle() function does all this for us and returns true if the analog feedback goes above 260. The PWM and analog values will be different for each robot setup, so we’ve written a few functions to manually adjust the servo to get the opening conditions.

Brains

Robot cracking Arduino shield

We used the trusty RedBoard to control everything. The Safe Cracker shield is a simple two layer PCB.

Bits on the shield:

  • The 12V/5V power supply provides the power to the current sensor and motor controller.
  • Current sensor: We originally planned on using the current sensor to detect motor stall when the edge of an indent in disc C was hit. It turned out being much faster and more accurate to detect the indent edge with the encoder; if the encoder had not changed in 5 milliseconds then the motor was stopped and we had hit the edge of the indent.
  • Motor controller: 15A was more than enough to handle the motor’s 5A stall current
  • Servo connector with feedback
  • Photogate connector
  • Display connector for the large 6.5” 7-segment display (needed only for our live stream event)
  • Buzzer to announce when we’ve cracked it
  • ‘GO’ button connector if we wanted to make the apparatus headless

Safe Cracker Schematic

Code

You can find the firmware here. While the code to control the SparkFun Safe Cracker got a bit large, it’s fairly straight forward. In essence, we go to a given dial location, pull on the handle, see if the handle moved far enough that we’re open, repeat. Additionally, we created functions to allow us to measure, as precisely as possible, the widths of the indents on disc C.

Frame

alt text

To build an apparatus that could be easily and quickly attached to our safe, we first modeled the safe in 3D.

alt text

The frame is built with Actobotics parts with magnets hot glued to the three feet. The magnets provide excellent adhesive strength while still being able to attach and detach the robot.

alt text

The handle cover, coupler, base plate to hold the electronics, and nautilus gear were printed on our trusty Taz 6 printer.

alt text

This frame is specifically designed for our model safe, but the variety of Actobotics parts and the ability to print custom parts means the SparkFun Safe Cracker could be modified to fit any particular model of safe.

How Combination Safes Work

In order to understand some of the shortcuts we took, you’ll need to know how the discs inside a combination lock operate. Here’s a quick primer!

Combination lock

If you’ve ever used a combination padlock you know the basics:

  • Spin the dial a few times to reset everything
  • Turn the dial in a certain direction until you get to the first combination number. Let’s call that AA.
  • Turn the dial in the opposite direction one full turn, then continue until you get to the second number - BB
  • Turn the dial in the opposite direction until get you get to the third number - CC
  • Pull on the handle to open lock

The most common padlocks have a dial from 0 to 39 with a combination AA/BB/CC. Combination safes work exactly the same but with larger dials, usually 0 to 99. Some safes have additional combination numbers (for example: AA/BB/CC/DD/EE), but the general home-store fire safe is 3 numbers.

But, how do the internals of a combination safe actually work?

Here’s a video to show you the basics:

There are three discs, let’s call them discs A, B and C. Each disc has a notch in it called a gate. When you pull down on the handle, a rod (sometimes called the fence) hits the three dials. If the three gates are lined up correctly, the rod slides into the notches. This allows the handle to travel far enough to disengage the lock on the door, and the safe can be opened.

Turning the dial on the outside of the lock directly controls disc C (sometimes called the drive wheel). Twist it clockwise (CW) or counterclockwise (CCW), and you directly manipulating the C disc. But, how do you move the other two discs?

Combination lock discs with raised tabs

Discs from the inside of a fire safe

Each disc has a raised plastic tab. When the discs are next to each other, a disc can move freely for about 350 degrees until its raised tab hits the tab on the next disc and begins moving it.

If you turn disc C a full turn, the tab hits the tab on disc B and begins to turn it. Similarly, disc B has a tab on the opposite side of the disc that will hit disc A’s tab. Turn the dial far enough, and C will pick up and start turning B, which will then pick up and start turning A.

Clear as mud? Check out Woodgears. They have a great breakdown of the pieces and a video showing how the discs are manipulated.

The Problem Domain

The dial on our SafeSentry safe is 100 digits. If there are three discs, our domain is 100 * 100 * 100 or 1 million possible combinations. Testing on a safe at the store, we found it took about ten seconds on average to reset the dial then dial in the three solution numbers. So, worst case, it will take 115.74 days to try every combination. And 10 seconds is pretty fast; humans get tired and less precise over time. Luckily, there are some tricks we can do.

On some high-end, secure safes, if you turn the dial to 81.5 and the combination is 81, it won’t open. With these lower cost home-brand safes the manufacturing tolerances are much larger. On the safe we tried at the store if one of the numbers in the combination is 53 then 52 and 54 will also work.

The first part of this video will show you the tolerances on the combination dial are +/-1 digit.

This quickly reduces the domain to 33 * 33 * 33 = 35,937 combinations. That’s still over 4 days of trying.

One of the ways to pick a safe is by feel. Manufacturers know this, so, to prevent it, the last disc (we’ll call it disc C) has a series of indents. If you press down on the handle and spin the dial, the thing trying to push down into the notches on the dials, called the fence, will fall into these false indents and lock up the dials. Bummer. But, you quickly figure out that there are 12 indents. And, one of these ‘indents’ must be the correct slot when you dial in the combination.

The problem domain is now 33 * 33 * 12 = 13,068 combinations or 1.51 days. About the speed of paint drying.

The locations of these indents are found easily by hand. 100 / 24 (12 indents, 12 raised bits) = 4.17 dial positions per indent. It’s not super clean, but, if an indent ranges 21 to 25.2, then it’s safe to go to 24 to ‘test’ that indent to see if it’s actually a solution slot.

On our safe we located the indents as follows:

case 0: return (99); //98 to 1 on the wheel
case 1: return (8); //6-9
case 2: return (16); //14-17
case 3: return (24); //23-26
case 4: return (33); //31-34
case 5: return (41); //39-42
case 6: return (50); //48-51
case 7: return (58); //56-59
case 8: return (66); //64-67
case 9: return (74); //73-76
case 10: return (83); //81-84
case 11: return (91); //90-93

Here’s what disc C looks like:

Disc from combination safe showing indents

11 false gates, 1 solution gate

Disc C has the following dimensions:

  • Outer diameter: 2.815” (55.5mm)
  • Width of solution slot: 0.239”
  • Width of 11 indents: 0.249” +/- 0.002”

C = 2πr, so our circumference is 17.69”. Our motor has an 8400 tick encoder. Each encoder tick is therefore approximately 0.0021”. So, we’re looking for a difference of about 5 ticks. Eeek! That’s not many.

If we can externally measure the widths of the various slots, we may be able to discern which slot is the skinniest and therefor the solution slot. This would reduce our combination domain to 33 * 33 * 1 = 1,089 and a crack time of 3 hours, worst case.

The function measureDiscC() is designed to take a series of readings and add them together. The motor is a gear head motor and has a tremendous amount of torque, so, if there is any flexing or give in your apparatus, this will show up in the readings as noise. However, if we take many simultaneous readings, any flexion should be replicated to all indent measurements allowing the skinny slot to bubble to the top.

Set screws will not work. A hub that uses a set screw to connect to the D-shaft on a motor will not survive the constant torture of indent measuring. Once we switched to a 6mm clamping hub we had much less noisy readings.

Here’s the output from five measureDiscC() tests on our Craigslist safe with no combination:

Measuring complete
Smallest to largest width [Width]/[Depth]
Indent 8: [1911] / [1130]
Indent 1: [1925] / [1122]
Indent 3: [1953] / [1091]
Indent 0: [1955] / [1099]
Indent 11: [1966] / [1105]
Indent 2: [1992] / [1100]
Indent 9: [1994] / [1126]
Indent 7: [2011] / [1098]
Indent 10: [2036] / [1096]
Indent 4: [2077] / [1109]
Indent 5: [2083] / [1100]
Indent 6: [2114] / [1096]

Indent 8 bubbles to the top on almost all the tests we have run on our safe. We also output the depth measurements (how far does the handle go down), but I am much more suspicious of these readings.

We can’t be sure the smallest indent is the solution ident, or if we’ve even measured the indents correctly so the Safe Cracker firmware allows the user to control which indents are to be tested. Turn them all on, turn on 5, or turn on only one, it’s up to you. We recommend trying to crack your safe with the smallest four indents. If you fail to open the safe then turn these 4 off, turn the other 8 indents to true, and run again.

We are down to 33 * 33 * 4 = 4,356 or a little over 12 hours. Still not great. What other tricks can we do?

Quick Note: When we live streamed the safe cracking, we were conservative and selected four indents to try. The winning indent was indent 8, the skinniest indent. So with two data points, I’d say this vulnerability has potential. You can re-watch the stream if you’d like. The magic moment occurs at 45:20, but start around 44:30 to get the full scope.

Set Testing

If each three combination attempt takes 10 seconds, what can we reduce the time per attempt? We can dial faster of course. But, we can also get sneaky with how we adjust the dials. It takes me 10 seconds because I can’t back up a digit without fouling where the discs are sitting. The robot can be much more precise.

To crack our safe, we set discs A and B, test the indents on disc C, move backwards to adjust disc B, then test the indents again. We call this set testing as opposed to reset testing (where a full reset is done between tests).

The robot attempts combinations this way:

  1. Reset dials by spinning CCW, past zero, continue until we arrive at zero.
  2. Continue CCW to 3. This sets disc A to 3.
  3. Rotate CW to 3. Continue CW to 0. Disc B is now set to 0.
  4. Rotate CCW to the first allowed indent; ours is 8. Disc C is now set to 8.
  5. Try the handle. Failed? Continue…
  6. Rotate CCW to next allowed indent; ours is 24.
  7. Try the handle. Failed? Continue…
  8. Rotate CCW to next allowed indent; ours is 66.
  9. Try the handle. Failed? Continue…
  10. Rotate CCW to next allowed indent; ours is 74.
  11. Try the handle. Failed? Continue…
  12. Rotate CW to 6. Disc B is now set to 6.
  13. Loop to step 4.
  14. Rotate CW to 9. Disc B is now set to 9.
  15. etc…

Here’s a video of set testing, done by hand, to demonstrate what we’re talking about. Jump to 0:41 to see Set Testing in action.

Using this method we can test the AA/BB/xx combinations (set Disc B to 8 then test four indents) in approximately 8 seconds vs. 40 seconds (4 test @ 10s per test). Much faster!

Originally: 33 * 33 * 40s = 12.1 hours

Using Set Testing: 33 * 33 * 8.3s = 2.5 hours worst case!

And, if we’re confident in our single indent the test time comes down to approximately 4 seconds per test (it’s not linear because of the time to move disc B).

Set Testing with one indent: 33 * 33 * 4s = 1.2 hours.

Additional Resources

We hope you enjoyed reading about our safe cracking robot. If you have any questions or discover any other tricks, please let us know!

There are some great videos on how to crack safes, just have a poke around. Eric Schmiedl’s talk Safecracking Without a Trace at DEFCON 14 was especially good.


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

THAT InGenuis and OutSmarts Breakout Hookup Guide

$
0
0

THAT InGenuis and OutSmarts Breakout Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The THAT 1206 and 1646 breakout boards offer an easy solution to adding balanced audio inputs and outputs to your circuits.

SparkFun THAT 1206 InGenius Breakout

BOB-14002
14.95
SparkFun THAT 1646 OutSmarts Breakout

BOB-14003
14.95

The THAT InGenius and OutSmarts technologies are designed for high grade analog audio transmission and reception. They offer low distortion and high common mode rejection in real-world audio applications.

The breakout boards combine the THAT IC, supporting components, and a ¼" TRS socket. They make it easy to use the input and output drivers on breadboards and in projects.

Required Materials

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

Tools

For the breadboard exercises, we used the following tools and test equipment.

  • A signal generator.
  • A biploar power supply. We used two different supplies.
    • For bench testing, we’re using an old HP 6205c adjustable supply.
    • We also used a MeanWell +/-15V supply.
  • An oscilloscope to observe the results

Suggested Reading

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

Analog to Digital Conversion

The world is analog. Use analog to digital conversion to help digital devices interpret the world.

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.

Analog vs. Digital

This tutorial covers the concept of analog and digital signals, as they relate to electronics.

Background

Before we look more closely at the THAT breakout boards, let’s explore what they’re used for: driving and receiving differential (AKA balanced or double-ended) signals.

Signaling Model

A typical model for analog electronic commmunication involves a transmitting device, which sends signals to a receiving device. In between, they’re connected with a conductor: traces on the printed circuit board, or wire between the devices.

alt text

Transmitter connected to receiver.

In a simplistic approach to analog signaling, the transmitter simply puts voltage on the line, and the receiver observes that voltage.

alt text

Transmitter sends voltage, receiver observes.

Sometimes, the connection runs through a less-than-ideal electronic environment. It could pick up additional unwanted voltage from sources along it’s path. In signaling theory, unwanted signals are known as noise. Sources of noise could include digital signals on the same PCB, or nearby radio or electromagnetic equipment.

alt text

Antenna causes unwanted interference.

In these cases, the receiver receives the combination of the original signal, plus the noise picked up along the way.

If you've ever heard your cellphone make your radio chirp, or your microwave makes snow on your TV, you've seen an example of noise pickup.

Differential Signals

Differential signals use a bit of clever algebra to achieve noise cancellation.

The output generates two signals, one in original polarity (known as the hot leg), the other inverted (the cold leg).

alt text

Differential output driver.

The receiver subtracts them from each other, to restore the original signal.

alt text

Recovering the original signal.

Any noise picked up along the way will be the same on both signals. When they’re subtracted, the inverse polarity signal is reinforced, but the noise is canceled! N - N = 0!

alt text

Canceling the induced noise.

Differential signaling takes advantage of the principle of common mode rejection. When the signals are subtracted, anything that they have in common gets canceled. The degree of common mode rejection achieved is typically expressed in decibels, known as the common mode rejection ratio, abbreviated CMRR.

The keen reader will have noticed that the differential receiver in the examples above is doubling the amplitude of the received signal (that factor of 2B). In real-world differential receivers, the incoming differential signal is frequently attenuated by half, removing that term.

The Difference between Differential and Balanced?

In this hookup guide, we’re specifically talking about the analog audio application of differential signaling. In audio literature, this is usually referred to as balanced interfacing. It’s a problem-domain specific term, used to describe the more general principle of differential signaling.

Differential signaling is not limited to audio or analog interfacing. A modern computer is full of differential digital interfaces: USB, LVDS RAM, displayport, and SATA all use variants of differential digital signals.

Balanced Signals In Audio Systems

Any audio system involves devices that employ a wide number of connectors and signaling standards. To properly connect everything, you need not only an understanding of the different connectors being used, but also the circuits behind them! The following table summarizes some of the possibilities.

alt text

An excerpt from Rane App Note 110.

There are some particular pitfalls what await in the audio interfacing world.

  • ¼" TS and TRS sockets look the same from outside, but aren’t functionally equivalent.
  • TRS jacks are used for balanced outputs, headphone connectors, and insert-point connections. The connector is the same, but they’re not compatible with each other.
  • There’s no guarantee that an XLR is actually balanced. There have been devices that left a pin disconnected!
  • There was also a period of disagreement as to which pin on an XLR was hot. Today things have mostly settled on pin 2 being hot, but if you’re having problems, you might have a pin-3 hot device.
  • No matter how carefully selected the equipment is, Murphy’s Law dictates there will be one essential piece of unbalanced equipment.

With some equipment, you’re lucky, and the interfacing details are printed near the connector in question. Other times, they’re described in the users manual, and sometimes you’re left to figure it out on your own!

Sometimes, just using the right combination of connectors or adapters gets things into decent shape. Other times, it might be easier to modify or retrofit a better input or output stage…

…which is where the THAT 1206 and 1646 breakout boards come in!

Hardware Overview

The THAT InGenius and OutSmarts integrated circuit families implement high quality balanced input and output amplifiers with a minimum of external components. The circuit topologies were invented by Bill Whitlock, the President and Chief Engineer of Jensen Transformers. Mr. Whitlock is also a recognized expert on audio interfacing, having published manypapers and troubleshooting guides on the subject. They are manufactured by THAT Semiconductor, who specialize in high-quality analog audio ICs.

alt text

InGenius and OutSmarts.

These two breakouts perform mirror-image signal conversion. The 1646 OutSmarts is a unbalanced-to-balanced output driver, and the 1206 InGenius is a balanced-to-unbalanced input receiver.

alt text

Back of THAT breakout boards.

The breakout boards add passive components to support each IC, plus TRS jacks.

The circuits come from the THAT datasheets, and include the recommended RF filtering, DC offset reduction, and transient suppression networks.

THAT Breakout Boards

alt text

Connections on the THAT breakout boards.

The external interface on each board (the output of the 1646 and the input of the 1206) is on a ¼" TRS socket. The TRS is wired with the regular-polarity signal on the Tip, and the inverted signal on the Ring. Adjacent to each leg of the socket are test points for the signal (T, R, S) and normal (TN, RN, SN) contacts. When nothing is plugged into the socket, the normals connect to the corresponding signal pad. When a jack is plugged in, it connects to the signal pads, and the normals float.

alt text

1206 output matched to 1646 input.

The internal connections are on four 0.1" header pads.

Pad LabelFunction
In 1646 unbalanced input
Out 1206 unbalanced output
V+ Positive power supply rail
V- Negative power supply rail
GND Ground

Grounding

There is a jumper on the back of the PCB that allows for two different grounding configurations.

By default, the board assumes a single ground connection through the 0.1" header. This is how you’d deploy these breakouts on a breadboard, or in a plastic enclosure.

However, if you have a grounded metal enclosure, it’s considered bad practice to run the shield of the cable around inside the Faraday cage of the enclosure – it creates an antenna within the cage that re-radiates any noise induced in the shield.

The solution to this is to tie the shield to the enclosure right at the connector. On these breakouts, there is a jumper to separate the connector from the circuit ground, and pads that allow for a short ground wire to run under the collar of the TRS.

alt text

Closeup of ground jumper.

We’ll examine how these are applied in the example project below.

Power and Headroom

Before we build some circuits with the THAT breakouts, let’s discuss how to power them, and what that means for headroom.

Analog audio circuits usually run from bipolar power supplies, meaning the supply provides two rails, of equal and opposite voltages. The THAT breakouts follow this convention, and function across a wide range of supply voltages, from +/-5V, to an absolute maximum of +/-20V.

The power supply voltage determines how large a signal the IC can handle before clipping: for the THAT ICs, the clipping voltage is roughly 2 V below the supply rails. For example, running on +/- 12V rails, the ICs can handle 20 Vpeak-to-peak signals, which swing between -10V and 10V. If the signal exceeds that range, it will clip, resulting in distortion.

alt text

Increasing the supply voltage (blue and purple traces) causes headroom (clipping point) to increase.

As the supply voltage changes, the point at which the IC clips move correspondingly. Typical pro-audio devices run on +/-15V to +/-17V supplies, while consumer hi-fi devices frequently have +/- 12V supply rails.

Finally, there is a bit of cleverness at play with the maximum signal levels from these ICs. The 6 in the name of each IC refers to how much gain or attenuation is applied to the signals they pass: 6 dB. The 1646 drives each leg of the balanced output with a signal that is as strong as the input – the differential voltage is double the input voltage, or 6 dB hotter. The 1206 does the reverse: it cuts the input voltages in half (-6 dB) – its unbalanced output is the same amplitude as either of the input legs.

alt text

Signal levels ovbseved at 1646 input (yellow), each 1646 output (purple and blue), and 1206 output (green).

If you daisychain a 1646 into a 1206, the output of the 1206 will be equal to the input to the 1646.

Breadboard Experiments

To get started with these boards, lets build a few circuits on a breadboard, and observe their performance on an oscilloscope. You’ll need the materials listed above, in the required materials section.

You’ll also need a bipolar power supply, signal generator, and an oscilloscope to follow along.

Balanced Output With 1646

First, we’ll convert the unbalanced output of our signal generator into a balanced output, using the 1646 breakout.

alt text

1646 breakout on breadboard.

We assembled the circuit on a solderless breadboard. Because we’re using a bipolar power supply, we had to run three wires (V+, ground and V-) from the power supply. We also connected the output of our signal generator to the input of the breakout.

alt text

Testing 1646 on breadboard.

With the generator, adjustable power supply, and oscilloscope, we can evaluate the behavior of the 1646.

Set the signal generator to produce a 1 kHz sine wave at 5 Vpp, and set the power rails to +/- 12V. Then switch the power supply on, and use the oscilloscope to observe the signals at various points in the circuit, as discussed below:

  • The breakout draws about 5 mA from each supply rail. If the draw is higher than that, switch the supply off and double check your wiring.
  • Probe the signal generator output and Tip of the TRS connector: the signal polarity and amplitude are identical.

alt text

Input (yellow) compared to signal at tip (blue).

  • Compare Tip and Ring outputs: they should be same amplitude, but with opposite polarity.

alt text

Signals at tip (yellow) compared to ring (blue).

  • Keeping the probes on the Tip and Ring outputs, short the ring connection to ground (we used a snip of wire to bridge the ring to the sleeve). The voltage observed at the tip doubles to 10 Vpp, and the ring goes to 0V. The 1646 keeps the differential amplitude the same (10V - 0V is equivalent to (5V - (-5V)) ), and the 1646 still exhibits 6dB gain. The supply current remains at 5 mA per rail.

alt text

Tip (yellow) doubles amplitude when ring (blue) is shorted to ground.

  • Finally, let’s check the clipping amplitude of the 1646. Reduce the supply rails to +/- 5V, then increase the generator amplitude while monitoring the output signal. The output will start to clip when the generator reaches 6 Vpp. Once you see the clipping, increase the supply rails slightly, and notice that the clipping point tracks the rails.

alt text

Output (yellow) clips at about 2V shy of the +/- 5V supply rails (blue and purple).

Balanced Input With 1206.

Moving on, we’ll add a 1206 breakout to the circuit we built above.

alt text

1646 and 1206 breakouts on breadboard.

We plugged them together with a TRS cable.

alt text

Using 1646 to generate balanced test signals for the 1206.

Checking the behavior of the circuit with the oscilloscope, we observe:

  • The 1206 OUT pin matches the original input.

->alt text<-

Input to 1646 (yellow), outputs of 1646 (blue and purple), and output of 1206 line receiver (green).

  • As with the previous experiment, shorting one leg of the interconnection to ground results in no change to received amplitude.

Common Mode Rejection Test

As illustrated in Figure 5 of the 1206 datasheet, we can test common mode rejection by applying the same output from a signal generator to the Tip and Ring of the 1206 input connector, and observe the output with an oscilloscope.

alt text

To make the connection a little easier, we used a TRS breakout board, and connected it’s T and R pads with a wire on the breadboard. Then we ran a TRS cable from the TRS breakout to the THAT 1206 board.

alt text

Common mode rejection test.

Set the signal generator for a 1 kHz sine wave, and slowly increase the signal generator amplitude, while keeping an eye on the board output. The output will be extremely small when compared to the input. On our test system, we applied 5 Vpp and could not measure any significant signal at the output – the scope’s finest input range is 20 mV per division. THAT state the 1206’s CMRR as better than 90 dB, which translates an algebraic factor of about 32,000.

alt text

Applying same input to 1206 tip and ring (yellow), and resulting output (green).
Notice that the output scale is 20 mV per division.

By adjusting the generator frequency, we can observe that the CMRR is similar across the audio spectrum, from 20 Hz to 20 kHz.

Example Application

Next, let’s take our newfound skills with these breakouts, and use them to retrofit balanced outputs onto a device that doesn’t have them already.

The candidate device is a Sony hi-fi component CD player. From the factory, it only had RCA jack outputs, but we’re going to augment them with balanced TRS outputs, using a pair of THAT 1646 OutSmarts breakout boards.

alt text

The Patient: a Sony CD player.

This particular unit was selected for a couple of specific reasons.

  • First, it was working to begin with – it’s easier to add a feature to something that’s already working, than to have to start with troubleshooting and repair work.
  • Second, as a stereo component, it’s in a reasonably large chassis, with plenty of room inside for the added components. There simply wouldn’t be room inside for more components in a Discman-style portable player.
  • Finally, it’s a little older – there’s a sticker on the back panel indicating it was manufactured in 1991. That means that the components inside larger and less highly integrated, making it a little easier to accomplish the retrofit.

First step: Analysis

To add the THAT 1646 breakouts to this player, we needed to know several things:

  1. First, we need to find a place to mount them, where they won’t cause problems with the inner workings of the player.
  2. Second, we need to identify the power supply rails in the player, and figure out how to power the breakouts. We’re operating under the assumption that there will be a bipolar power supply that we can tap into.
  3. Finally, we need to figure out where we can tap the audio outputs, and verify that the signal we’re extracting meets the 1646’s allowable headroom levels

Mechanical Analysis

Finding a place to mount the breakouts was as simple as undoing the four screws to remove the top of the player. With the top off, it’s apparent that the chassis is mostly empty space, and there’s plenty of room for added circuitry.

alt text

Plenty of empty space inside.

We opted to mount the breakouts to the back panel, next to the existing RCA jacks. The breakouts will be mounted using the nuts on the TRS jacks.

Power Supply Analysis

We then needed to figure out how to power the breakouts. We know each board draws about 5 mA from each power supply rail, and can function on supplies from +/-5 to +/- 20 VDC.

Looking in the player, there are a number of labeled wire jumpers on the PCB. In particular, there were jumpers labeled +5V, -5V, +10V, -10V and GND. +/- 10V sounds like a good starting point for the 1646, leaving plenty of headroom, but more careful inspection contradicted that thinking!

alt text

Conveniently labeled power jumpers.

Just inside the RCA jack are the player’s output stages, a pair of TL082 op amps, which were powered from the +/- 5V rails. A little more careful inspection with the oscilloscope revealed what was going on. The 10V lines are the raw output from the bridge rectifiers, and exhibit 60 Hz ripple. The 5V lines are the output of an M5209P voltage regulator, with no visible ripple.

Signal and Headroom Analysis

It was easy to find the output signals. Near the RCA jacks are a pair of wire jumpers, clearly labeled L and R. Those jumpers measure continuous with the tips of the RCA jacks.

To evaluate the headroom required, we burned a CDr with full amplitude sine wave test signals. Playing those tracks resulted in output amplitude of 5.6 Vpp, and we verified this as several frequencies across the audio spectrum.

The 5.6 Vpp level just happens to dovetail with the headroom that we measured on the breadboard. Powered from +/- 5V, the 1646 can handle input signals up 6 Vpp.

Putting It All Together

Materials

Aside from the CD player, we needed the 1646 breakout boards and some hookup wire.

We also used a drill press with a set of graduated metal bits, cutting oil, and soldering tools including an iron and wire strippers.

Mounting The Breakouts

The rear panel comes completely off the back of the unit, which allowed us to drill holes to mount the breakouts without being concerned about metal chips falling into the rest of the unit. Since the panel and chassis are metal, we cut the shield jumper on the bottom of the board, and soldered a loop of stranded hookup wire to the ground pad.

alt text

Preparing the TRS grounding.

When the breakout is mounted in the panel, the loop makes contact with the chassis.

alt text

Breakout installed on rear panel.

We then ran some short pieces of stranded wire to the points identified in the analysis. The wiring went like this:

Wire color Connection in CD player Point on breakouts
Red +5V V+ (both boards)
Green GND GND (both boards)
Blue -5V V- (both boards)
Yellow L IN (Left board)
Black R IN (Right board)

Each board got it’s own power wires; the far ends of those wires were twisted together, and tack soldered to the corresponding points on the CD player board.

alt text

The finished balanced output conversion.

With everything assembled, it’s time to test it out, then close the player back up!

Resources and Going Further

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

Resources

For more information about the THAT InGenius and OutSmarts ICs, please refer to the datasheets and application notes below.

Going Further

For more information about balanced audio and sound system design, please refer to the following materials.

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

Interactive Hanging LED Array

Learn how we converted 72 lightbulbs into an interactive LED array for our conference room.

MEMS Microphone Hookup Guide

Get started with the SparkFun MEMES Microphone breakout board.

MIDI Shield Hookup Guide

How to assemble the SparkFun MIDI Shield, plus several example projects.

Proto Pedal Example: Programmable Digital Pedal

Building a pedal around the Teensy 3.2 and Teensy Audio shield. Changing the effect in the pedal is as easy as uploading a new sketch!

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


Ardumoto Kit Hookup Guide

$
0
0

Ardumoto Kit Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The Ardumoto Shield is a dual-motor controller for Arduino. Combined with an Arduino, the Ardumoto makes a fantastic controller platform for RC vehicles or even small autonomous robots. It’s now easier to use, featuring control signal LEDs, while also being much more flexible for advanced users.

alt text

Ardumoto Shield assembled and situated on a RedBoard.

We sell the Ardumoto Shield either alone or with a set of motors and wheels in our Ardumoto Shield Kit. This kit includes the shield as well as pairs of tires, motors and connectors. And, of course, it’s all stuffed in a classic SparkFun red box (which may come in handy as a robot chassis).

alt text

Contents of the Ardumoto Shield Kit.

Covered in This Tutorial

This tutorial covers assembly and use of both the Ardumoto Shield and the Ardumoto Shield Kit. Digging deeper, we’ll get into some assembly tips and an example Arduino sketch. We will also present some additional resources that can help you get the most out of your board.

This guide assumes you are familiar with the Arduino platform and can successfully compile and load a program to an ATmega328P based board, such as blink.ino.

Required Tools & Materials

To follow along with this tutorial, you’ll need an Ardumoto Shield or the Ardumoto Shield Kit, and an Arduino or Arduino-compatible development board.

Arduino Uno - R3

DEV-11021
24.95
92
SparkFun RedBoard - Programmed with Arduino

DEV-13975
19.95
2
SparkFun Ardumoto Shield Kit

KIT-14180
24.95
SparkFun Ardumoto - Motor Driver Shield

DEV-14129
19.95

Equipping the Ardumoto Shield (Non-Kit Version)

If all you have is the shield, you will also probably want a couple of DC motors to drive. The Ardumoto can control most small DC motors, like any of those in our DC motor category.

You’ll also need a handful of connectors to get everything wired up together. We recommend Stackable Headers to connect your Ardumoto to your Arduino, and two or three 3.5mm Screw Terminals to help connect motors to your Ardumoto.

To upgrade an Ardumoto Shield to a kit, add the following components:

Powering the Shield

Both the shield and the kit will require a power source. Batteries are usually your best bet — we recommend a 9V alkaline battery, which will work perfectly with the included 9V-to-Barrel Jack Adapter.

Required Tools

Finally, you’ll also need a few tools, including a soldering iron, solder, wire strippers and a screwdriver:

Soldering Iron - 30W (US, 110V)

TOL-09507
9.95
6
Solder Lead Free - 15-gram Tube

TOL-09163
3.5
2
Pocket Screwdriver Set

TOL-12891
3.95
3

Suggested Reading

The Ardumoto is a great platform for first-time motor users (and experienced ones too!). There are, however, a few concepts you should be familiar with before clicking over to the next few pages. Here are some tutorials we recommend reading first:

Meet the L298

At the heart of the Ardumoto — the big, black chip right in the middle — is an L298, one of our favorite dual-channel motor drivers around. On this page, we’ll give you some background information on the chip we’ll be depending on to drive our motors.

But First…Why a Motor Driver?

DC motors are the easiest motors to use. They’re dumb (they don’t provide feedback), but they’re good at spinning in one direction or the other when we tell them to. Unlike servos or steppers, DC motors don’t require any special signals — just a straight DC voltage. So why can’t we just connect them directly to the Arduino?

Well, motors tend to draw a lot of current, and trying to drive a motor straight from your Arduino output pins will make your Arduino quite cross with you. Wiring an Arduino straight to the motors will damage the microcontroller’s I/O pins due to the absolute maximum ratings. The Ardumoto lets you control a whole bunch of current (good for motors) safely with an itty-bitty signal (good for Arduinos). Everyone’s happy!


Here are some of the important features and specifications of the L298. These extend out to be the specifications of the Ardumoto as well:

Two Channels @ 2A Each

The L298 is a two-channel motor driver. That means it can individually drive up to two motors. So it’s perfect for a two-wheel-drive vehicle. But if you have a special four-wheel-drive platform, you might need something else (or just two L298s).

Each channel on the L298 can deliver up to 2A to the motor to which it’s connected. Keep in mind, though, that the amount of current available to your motor also depends on your system’s power source. Batteries are great power sources because they’re mobile and can discharge a lot of current. However, high current draw also means they’ll drain faster.

The Control Signals

Controlling the L298 is very easy. If you’ve ever blinked or dimmed an LED, you already have all the tools necessary to control the L298.

  • All of the control signals are limited to a maximum of 7V, which is great because our Arduino is only going to supply a maximum of 5V.

  • For each of the L298’s channels, there are two types of input we need to send to drive a motor: direction and enable. Each of these inputs are Boolean — either high or low.

  • Using the direction inputs, we can control whether the motor spins clockwise or counterclockwise. The L298 actually has two direction inputs for each channel. However, we’ve merged those two inputs into one on the Ardumoto, as we’ll show in the next section.

  • The enable input can be driven either high or low to make the motor spin or stop. But, with Pulse Width Modulation (PWM), we can actually use this input to control the speed of our motor. Just as it can be used to dim LEDs, PWM is perfect for controlling how fast our DC motor spins.


That covers the basics of the L298. If you’re curious, or want to know more about the chip, checking out the datasheet is a good place to start.

Ardumoto Overview

Before you get your soldering iron out, or start attaching motors, it’d be best if we briefly covered the basics of the Ardumoto Shield. On this page, we’ll highlight the important inputs and outputs of the shield, so you can get a better idea of how you want to assemble it later.

Pins and Connectors

Here’s an annotated view of the shield, highlighting the important pins and components:

alt text

The top side of the Ardumoto

alt text

The bottom side of the Ardumoto and jumpers

Each motor uses two pins: the digital output for direction and the PWM for speed. The factory configuration uses Arduino pins 2, 3, 4 and 11. The alternate configuration uses pins 7, 8, 9 and 10. If the alternate pins are needed, you’ll have to cut the copper links on the bottom and apply solder to bridge to the other selection where necessary. For this guide, just leave everything in the default positions.

If the shield is used on a 3.3V Arduino (such as the Arduino Pro 328 - 3.3V/8MHz), chances are there’s no 5V supply, so you’ll have to move the VCCIO jumper to the 3.3V side. This jumper selects the voltage for the L298’s logic. If you’re using an Uno, or 5V 328p of another variety, leave this in the default position.

This table describes the pin function for each configuration.

Default Pin
Alternate Pin
Ardumoto Shield Pin LabelNotes
28DIR AA digital signal to control the rotation direction of motor A (e.g., HIGH drives current from output 4 to 3).
39PWM A
A PWM signal to control the speed of motor B. 0=off, 255=max speed.
47DIR B
A digital signal to control the rotation direction of motor A (e.g., HIGH drives current from output 2 to 1).
1110PWM B
A PWM signal to control the speed of motor B. 0=off, 255=max speed.

While the Ardumoto Shield is attached to an Arduino, the used pins shouldn’t be connected to anything else.

Motor Outputs

Both of the L298’s motor driver outputs are broken out to the edge of the shield. These 2-pin outputs are broken out to two footprints: a 3.5mm-pitch screw terminal and a 0.1"-pitch header. You can use either to wire up your motor, but screw terminals make life much easier if you need to disconnect your motor. The L298 is perfect for building simple two-wheel-drive robot platforms — connect one motor to port A and the other motor to port B.

alt text

Technically, there is no right or wrong way to connect your motor’s wires to the two output pins, but to help keep things straight, we suggest connecting the red / black wire for each motor to pins 1 / 2 on port A and pins 3 / 4 on port B, respectively.

The right and left motors of a robot spin different directions with the same polarity drive because of the orientation. If you want to keep DIR consistently moving that side of the bot “forward,” you may end up swapping either the motor leads of one side or the logic in the code, but not both. Play around with the leads of the motors on their respective sides and watch the indicator LEDs to see the effect.

LED Indicators

Next to each of the motor outputs is a pair of blue and yellow LEDs, which indicate the direction your motor is spinning. These are great once you get to debugging your project. They’re also useful if you want to test your sketch without wiring up any motors.

There are also four red LEDs (PWMA, DIRA, PWMB, DIRB) that are wired to the control lines directly, showing what your code is doing and also if the pins are configured correctly.

alt text

The control signals are connected to LEDs on this revision so you can see what your program is doing! In this photo, DIRA is illuminated (meaning the direction is reversed), and PWMA is half-illuminated, indicating that the signal is being pulse width modulated.

When the DIR LED of a side is illuminated, the driver will allow current from pin 2 to 1, and the blue LED will be lit. Alternately, the yellow LEDs will be lit. With a motor connected, the inductive effects can cause the opposite drive LED to illuminate slightly; this is OK. The blue and yellow LEDs are there to help show what the actual outputs of the driver are doing. Use the red LEDs to debug your code.

alt text

LEDs in operation

Supply Voltage

The Ardumoto Shield should be powered through one of two power supply inputs. Pick one or the other:

  1. The barrel jack input on the Arduino.
  2. The VIN input on the shield

If you don’t want to use the Arduino’s barrel jack input, you can use the VIN input on the shield instead. This voltage input will supply both the shield and the Arduino. Like the motor outputs, this connection is broken out to both a 3.5mm screw terminal and a 0.1"-pitch header.

Do not supply power to both the Arduino barrel jack input and VIN on the shield! Doing this will cause current to flow from one power supply to the other if the voltages are not identical.

Spec'ing a Power Supply

Because VIN powers both your Arduino and your motors, you need to take extra care in deciding what you’ll use to power your Arduino/Ardumoto combo. Not only does VIN have to fall within the acceptable range of your Arduino (usually 6–15V), but it also has to meet the specifications of your motor.

Check the voltage and current requirements of your motor before deciding how to power your Ardumoto project. These specifications vary. The 65 RPM Hobby Gearmotors, for example, have a recommended range of 3–6V, but can be safely powered at up to 9V.

We recommend 9V alkaline batteries as an easy, if not very sustainable, option. Dual-cell LiPo battery packs (7.4V nominal, 1,000mAh capacity) are also a good option if you’re looking for something mobile. A 9V wall wart can work if your project is stationary. For more help picking a power supply, check out our How to Power a Project tutorial.

Ardumoto Shield Assembly Tips

Before you can start using the Ardumoto Shield, you have to do a little assembly. Embrace your inner electronics technician and whip out that soldering iron! Time to turn a mish-mash of parts into a fully functional ‘duino shield!

alt text

Parts laid out, ready to assemble

On this page we’ll go over some assembly tips. You don’t have to follow these steps exactly (assemble the shield as best fits your project’s needs), but this is good for general use of the shield.

Add Screw Terminals (Optional)

If you please, you can add screw terminals to both of the motor outputs and/or the VIN input.

If you’re adding screw terminals to the motor outputs, slide them together first:

alt text

Then insert them into the shield and solder.

alt text

Soldering in the screw terminals

Solder the Arduino Headers

To interface the shield with your Arduino, soldering male connectors to the 28 header pins is a must. Soldering ensures a reliable physical and electrical connection. If you’ve never soldered before, check out our through-hole soldering tutorial.

There are usually two options for connectors when you’re assembling a shield: stackable or straight. We recommend stackable headers because they allow you to stack other shields or jumper wires on top. The smaller male headers are a good option if you’re looking for lower-profile installation.

If this is your first shield assembly, we recommend reading through our shield assembly guide. There are all sorts of tricks to installing shield headers, and making them look as good and straight as possible!

There are too many holes! The stackable header kit includes two 6-position, and two 8-position headers. These go in the rows of pins toward the outside edge of the board. Also, both 6-positions go on the same side, and the 8-positions go on the other. There will be two extra unused pins on each side, toward the motor connection.

alt text

In the process of soldering stackable headers. Still a lot of pins to go!

Once you’re done soldering the headers, plug the shield in to make sure everything fits nice and cozy.

alt text

Assembled shield on a RedBoard/Arduino

Prototyping Area

Let’s address the elephant in the room. There’s almost half a shield that we’ve failed to talk about thus far: the prototyping area! These rows and columns of 0.1"-spaced plated through-holes can be used to solder in all sorts of fun components.

Near the proto area is a set of six pins. With the isolation jumpers opened underneath, these allow you to interface directly to the inputs of the L298.

The six pins of the ISP connector are outlined within the proto area. These are just plated through holes, and are labeled to warn you that the pins underneath come up really close. If you absolutely need these, you may end up removing the ISP header from the attached Arduino.

Here are some ideas of what to do with it:

  • Leave it alone! — If you’re happy with just driving motors, you’re good to go.
  • Add an accelerometer to enable bump detection in your robot.
  • Fill it with LEDs to make your project as blinky as possible.
  • Add current sense resistors, an op-amp, and measure the current of the motors being driven.
  • Disconnect all the jumpers and wire up the L298 in any way you please.

Unlike other prototyping areas you may have encountered in the past, these holes are not wired together. You don’t need to do any trace-slicing, but you will need to do some soldering and wire routing.

Motor and Wheel Assembly

This is where the shield assembly gets very project-specific. Have you picked out which motors you’ll be driving with the shield? Do you know how long the wires need to be trimmed? There’s a lot to be answered here before continuing on…

Motor Wiring

alt text

If you have the kit, the motors come with wires attached, but take the time to notice how they are wired. They are a left-right pair, which can be seen by holding the motors in the same orientation and looking at how the red and black wires are attached. When they are installed with the wire-side facing each other, a positive polarity drives either motor “forward,” even though one is spinning clockwise while the other spins counterclockwise.

Connecting Motors

If you added screw terminals in the last step, break out your screwdriver, slide the wires in, and tighten the terminals down.

In lieu of screw terminals, you can solder the motor wires into either the 0.1" header or the screw terminal header.

alt text

The basic orientation of the motors, wires and connections to build a robot. In this configuration, the drive LEDs will make sense, and operations on the control signals will generate similar movement from side to side.

If you’ve got the kit, install one motor’s red to output ‘1’, and black to output ‘2’. Install the other motor’s red to output ‘3’, and black to output ‘4’.

Upcycling the SparkFun Box

If you have the Ardumoto Shield Kit, you probably also have a robust, resplendently red SparkFun box. These SparkFun boxes come in handy for all sorts of projects — including robot chassis!

With some measured hobby knife incisions, you can cut out some mounts for the motors and tie your Arduino/shield combo down as well:

alt text

This shape of robot relies mostly on balance, and slides across the floor. If driving on carpet, slick clear tape can be added to the corners to prevent catching.

Example Code

Controlling the Ardumoto Shield is super easy. If you can blink LEDs, you can make the Ardumoto Shield spin its motors. Here, we’ll provide a simple, expandable example sketch to show how to drive the pair of motors on the Ardumoto.

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 read our tutorial on installing Arduino IDE.

If you have not previously installed an Arduino library, please check out our installation guide.

The Example Sketch

Download the example sketch and upload it to your board.

Ardumoto Shield Example Direct Link

language:c
    /* Ardumoto Example Sketch
  by: Jim Lindblom
  date: November 8, 2013
  license: Public domain. Please use, reuse, and modify this
  sketch!

  Adapted to v20 hardware by: Marshall Taylor
  date: March 31, 2017

  Three useful functions are defined:
    setupArdumoto() -- Setup the Ardumoto Shield pins
    driveArdumoto([motor], [direction], [speed]) -- Drive [motor]
      (0 for A, 1 for B) in [direction] (0 or 1) at a [speed]
      between 0 and 255. It will spin until told to stop.
    stopArdumoto([motor]) -- Stop driving [motor] (0 or 1).

  setupArdumoto() is called in the setup().
  The loop() demonstrates use of the motor driving functions.
*/

// Clockwise and counter-clockwise definitions.
// Depending on how you wired your motors, you may need to swap.
#define FORWARD  0
#define REVERSE 1

// Motor definitions to make life easier:
#define MOTOR_A 0
#define MOTOR_B 1

// Pin Assignments //
//Default pins:
#define DIRA 2 // Direction control for motor A
#define PWMA 3  // PWM control (speed) for motor A
#define DIRB 4 // Direction control for motor B
#define PWMB 11 // PWM control (speed) for motor B

////Alternate pins:
//#define DIRA 8 // Direction control for motor A
//#define PWMA 9 // PWM control (speed) for motor A
//#define DIRB 7 // Direction control for motor B
//#define PWMB 10 // PWM control (speed) for motor B


void setup()
{
  setupArdumoto(); // Set all pins as outputs
}

void loop()
{
  // Drive motor A (and only motor A) at various speeds, then stop.
  driveArdumoto(MOTOR_A, REVERSE, 255); // Set motor A to REVERSE at max
  delay(1000);  // Motor A will spin as set for 1 second
  driveArdumoto(MOTOR_A, FORWARD, 127);  // Set motor A to FORWARD at half
  delay(1000);  // Motor A will keep trucking for 1 second
  stopArdumoto(MOTOR_A);  // STOP motor A

  // Drive motor B (and only motor B) at various speeds, then stop.
  driveArdumoto(MOTOR_B, REVERSE, 255); // Set motor B to REVERSE at max
  delay(1000);  // Motor B will spin as set for 1 second
  driveArdumoto(MOTOR_B, FORWARD, 127);  // Set motor B to FORWARD at half
  delay(1000);  // Motor B will keep trucking for 1 second
  stopArdumoto(MOTOR_B);  // STOP motor B

  // Drive both
  driveArdumoto(MOTOR_A, FORWARD, 255);  // Motor A at max speed.
  driveArdumoto(MOTOR_B, FORWARD, 255);  // Motor B at max speed.
  delay(1000);  // Drive forward for a second
  // Now go backwards at half that speed:
  driveArdumoto(MOTOR_A, REVERSE, 127);  // Motor A at max speed.
  driveArdumoto(MOTOR_B, REVERSE, 127);  // Motor B at max speed.
  delay(1000);  // Drive forward for a second

  // Now spin in place!
  driveArdumoto(MOTOR_A, FORWARD, 255);  // Motor A at max speed.
  driveArdumoto(MOTOR_B, REVERSE, 255);  // Motor B at max speed.
  delay(2000);  // Drive forward for a second
  stopArdumoto(MOTOR_A);  // STOP motor A
  stopArdumoto(MOTOR_B);  // STOP motor B

}

// driveArdumoto drives 'motor' in 'dir' direction at 'spd' speed
void driveArdumoto(byte motor, byte dir, byte spd)
{
  if (motor == MOTOR_A)
  {
    digitalWrite(DIRA, dir);
    analogWrite(PWMA, spd);
  }
  else if (motor == MOTOR_B)
  {
    digitalWrite(DIRB, dir);
    analogWrite(PWMB, spd);
  }
}

// stopArdumoto makes a motor stop
void stopArdumoto(byte motor)
{
  driveArdumoto(motor, 0, 0);
}

// setupArdumoto initialize all pins
void setupArdumoto()
{
  // All pins should be setup as outputs:
  pinMode(PWMA, OUTPUT);
  pinMode(PWMB, OUTPUT);
  pinMode(DIRA, OUTPUT);
  pinMode(DIRB, OUTPUT);

  // Initialize all pins as low:
  digitalWrite(PWMA, LOW);
  digitalWrite(PWMB, LOW);
  digitalWrite(DIRA, LOW);
  digitalWrite(DIRB, LOW);
}

Then upload to your Arduino and watch your motors spin! If you want to dig really deep into the sketch, check out the comments.

Explaining the Sketch

For each motor there are two mechanisms we can control — the direction of rotation and the speed. Each of those mechanisms is controlled by one pin on the Arduino.

Controlling Rotation Direction

We can only spin the motor in two directions — clockwise or counterclockwise — so we only need two values — 0 or 1 — to control that from the Arduino. We can simply digitalWrite either of the direction pins (pin 12 for motor A, pin 13 for motor B) HIGH or LOW to go forward or backward.

For example, if you want motor A to spin clockwise, you simply need to digitalWrite pin 12 LOW:

language:c
digitalWrite(12, LOW);  // Motor A will spin clockwise

To make it spin the other way, write the pin HIGH.

language:c
digitalWrite(12, HIGH);  // Motor A will spin counter-clockwise

(Note: The rotation direction depends on how you wired the motor to your shield. If you swapped the red and black wires, the motor will spin opposite of how we’ve described it here.)

Speeding

To control the speed of a motor we need to analogWrite to the PWM pins (pin 3 for motor A, pin 11 for motor B). A higher analogWrite value means a faster spin. Writing the pin LOW (or 0) will stop the motor.

PWM ValueMotor Spin Speed
0Off (Stop)
127Half Speed
255Full Speed

If we want to turn motor A up to maximum speed, this is all we need:

language:c
analogWrite(3, 255);  // Motor A at max speed

After that line of code is executed, the motor will spin until stopped. To stop the motor, replace 255 with 0:

language:c
analogWrite(3, 0);  // Stop motor A

Don’t forget to set your direction before spinning your motor!

Resources and Going Further

The Ardumoto has been designed primarily to be a motor driver, but we’ve taken extra time to make sure the L298 IC can be fully controlled, given the user understands the way it works. The datasheet contains a schematic diagram of the internal functions of the IC, which is the first thing to look at and contemplate before trying to do wacky things with your Ardumoto.

alt text

A block diagram of the L298 internals from the L298 datasheet

As can be seen from the block diagram, the L298 is actually four totem drives with two common grounds, intended for full-bridge motor-driving applications.

alt text

A section of the Ardumoto Schematic

To make the Ardumoto, we’ve connected the pairs with one of each inverted, to allow a direction control. The enable pin is then PWM’d such that the output goes between drive enabled and high impedance. This allows coasting of the motors when not driven.

Another way the motors could have been hooked up is to PWM the input pins and keep enable high. This would provide motor resistance against movement when not under power, and a PWM value of ½ would be “off.”

Advanced Pins and Connections

The other jumpers and pins are for flexible configuration. They allow the L298 to be completely isolated from the control lines so that it may be connected in very specific ways, but it’s up to you to figure out how to solve the engineering problems you’ll face.

alt text

The top side of the Ardumoto

alt text

The bottom side of the Ardumoto and jumpers

The A/B Isolate jumpers and the A/B inputs work together. If the ‘ISOLATE’ jumpers are all opened, and the ‘SELECT’ pins are all opened, the inputs to the L298 are not connected to anything but the six input pins by the proto area. They can then be used however the designer wishes in conjuction with the proto area.

The other curious feature is the pairs of pins labeled ‘SENSE’. If you look closely, you’ll notice each pair is shorted together, and connected to ground. It is possible to detect current through each motor by cutting the jumper between these pins, supplying a low-ohm resistor and measuring the voltage across it. Not for the faint of heart.

Possible uses:

  • Current sense — break the current sense link between through-holes and insert a 0.05 or 0.1 ohm resistor. Then, use an op-amp to amplify the voltage across the resistor to measure current with an ADC.
  • Four independent totem drive circuits using both timer one and timer two.
  • Non-coasting drive configuration.
  • Bridging output (and control lines) for 4A single drive — add a heatsink with thermal tape!

Resources

Going Further

  • HUB-ee Buggy Project— Build your own buggy using an Ardumoto shield.
  • Assembly Guide for RedBot— If you’re looking for a complete, beginner-level robotics platform, check out the RedBot Kit. It’s Arduino-compatible, and the RedBot Mainboard has a motor driver built into it, so you don’t even need an Ardumoto Shield.
  • Getting Started with the MiniMoto— The MiniMoto is a more advanced, digitally controlled, low-voltage DC motor driver. Great if you need a smaller form-factor motor controller.
  • How to Power a Project— Batteries? Wall warts? Solar? If you’re not sure how to power your Ardumoto Shield project, take a trip over to this tutorial.

How to Power a Project

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

MiniMoto DRV8830 Hookup Guide

MiniMoto is an I2C-based low-voltage DC motor driver.

Assembly Guide for RedBot with Shadow Chassis

Assembly Guide for the RedBot Kit. This tutorial includes extra parts to follow to go along with the RedBot Inventor's Kit tutorial.

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

Introduction to Operational Amplifiers with LTSpice

$
0
0

Introduction to Operational Amplifiers with LTSpice a learn.sparkfun.com tutorial

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

Introduction

If you haven’t already been through the Getting Started with LTSpice guide, you should definitely wait as an update to the audio quality is desperately needed. For those of you who watched it and finished it - bless you. I’d thought I’d kill two birds with one stone here and continue the LTSpice tutorial with an introduction to operational amplifiers – or op amp for short. We will be covering just the basics here - what are op amps, some common configurations, and a couple examples - and we’ll end with a nice, simple project to hopefully get you inspired to work with analog circuits a bit more.

To get started, download the schematics, symbols and simulations by clicking the button below.

LTSpice SIMs DOWNLOAD

Introduction to Operational Amplifiers

An op amp is a voltage amplifying device. With the help of some external components, an op amp, which is an active circuit element, can perform mathematical operations such as addition, subtraction, multiplication, division, differentiation and integration. If we look at a general op amp package (innards to come in a later tutorial) such as the ubiquitous 741, we’ll notice a standard 8-pin DIP (dual in-line package):

alt text

Photo courtesy of Learning About Electronics

We are mainly concerned with five of the pins. The circuit symbol for an op amp is a triangle with five pins shown below.

alt text

Photo courtesy of Virtual Labs

An op amp has a wide range of uses and, depending how each pin is connected, the resulting circuit can be some of the following (this is by no means a comprehensive list):

  • Comparator
  • An Inverting Amplifier such as a summing amplifier
  • A Non-Inverting Amplifier such as a voltage follower
  • Difference Amplifier
  • Differentiator or Integrator
  • Filter
  • Peak Detector
  • Analog-to-Digital Converter
  • Oscillator

Throughout this tutorial I will show you how to measure typical op amp characteristics such as gain, bandwidth, error, slew-rate, current draw, output swing and other characteristics found on device data sheets.

The Ideal Op Amp

The op amp is designed to detect the difference in voltage applied at the input (the plus (v2) and the minus (v1) terminals, or pins 2 and 3 of the op amp package). The difference is also known as the differential input voltage. The output, then, is the difference sensed at the input multiplied by some value A - the open-loop gain. An op amp behaves as a voltage-controlled voltage source, which we will model now. We will simulate both an open-loop and a closed-loop amplifier configuration.

An ideal op amp has the following characteristics:

  • Infinite open-loop gain
  • Infinite input resistance
  • Zero output resistance
  • Zero common-mode gain = infinite common mode-rejection
  • Infinite bandwidth
  • Zero noise
  • Zero input offset

alt text

Op amp model courtesy of wikipedia

Because the input resistance (Rin) is infinite, we can deduce that the current seen at the (+)(v2) and (-)(v1) terminals are zero, using Kirchhoff’s laws. Since the output resistance (Rout) is zero, there is no voltage loss at the output. The diamond-shaped voltage source in the image above is known as ( C ) voltage-dependent voltage source, and in this case the voltage is the gain (G) multiplied by the difference between the input terminals (Vin). The gain is normally referred to as (A) in texts, so the equation for the output is given by:

alt text

Let’s model a voltage-controlled voltage source and see if we can’t get its behavior to mimic an ideal op amp.

Feedback

Op amps are not meant to be used as stand-alone devices. We simply verified the Vout equation in the ideal op amp video to show why it is commonly referred to as a voltage-controlled voltage source. We are going to talk about feedback and closed-loop gain and application. What is feedback? Feedback occurs when the output of a system is fed back into as input(s). There are two types of feedback: positive (regenerative) and negative (degenerative). Feedback is applied to the system to affect one or more of the following properties:

  • Desensitize the gain - the value of the gain becomes less sensitive to variations in the values of the circuit component, such as temperature effects on transistors.
  • Reduce non-linear distortion - the output is proportional to the input.
  • Reduce the effect of noise - reduces the amount of unwanted electrical interference on the output. This interference could be external or from the circuit components themselves.
  • Control the input and output resistances - with an appropriate feedback configuration the input and output resistances can be controlled.
  • Extend the bandwidth of the amplifier.

All of the feedback comes at a price, and that cost is the gain. Negative feedback trades gain for more desirable properties; increasing the input resistance also increases the bandwidth.

Closed-Loop Gain

Unlike open-loop gain, the closed-loop gain is dependent on the external circuitry because of the feedback. However, it can be generalized.

alt text

Photo Courtesy of https://paginas.fe.up.pt/~fff/eBook/MDA/Teo_realim.html

alt text

Inverting Amplifiers

An example of an inverting configuration consists of one op amp and two resistors, R1 and R2. R2 is connected from the output terminal of the op amp to the inverting or minus terminal of the op amp. R2 closes the loop around the op amp.

One thing not mentioned in the video below, but is considered implied because we are still using the ideal op amp, is that no current flows through the op amp. All the current (I1) flowing through R1 is also flowing through R2. Another thing to note is that if R1 and R2 are equal in value then this circuit is typically used as a buffer to convert -vout to +vout-. This is known as the unity-gain inverter.

Project: The Summing Amplifier

A typical application for an inverting amplifier is a summing amplifier, also known as a virtual earth mixer, used in audio mixing. I happen to have quite a few LM741 op amps lying around, so I went ahead and built a summing amplifier. First I modeled it in LTSpice.

Non-Inverting Amplifiers

The Voltage Follower

The voltage follower is a nice example of a non-inverting amplifier. The property of very high input impedance is a desirable feature of the non-inverting configuration. The voltage follower can used as a unity-gain buffer amplifier connected from a high impedance source to a low impedance source - this helps to avoid loading effects on the driving circuit.

Difference Amplifiers

Difference amplifiers respond to the difference between two signals applied at its input, and rejects signals that are common to the two inputs.

A Single Op Amp Difference Amplifier

alt text

Remember that the gain of a non-inverting amplifier is positive and is given by:

alt text

and that the gain of an inverting amplifier is negative and is given by:

alt text

By combining these two topologies we are getting closer to be able to design a circuit that will be able to obtain the difference between the two input signals. In order to accomplish this, we must first make sure the gain magnitudes (think absolute values that are always positive) of each are equal. By attenuating the gain of the positive path from (1+ R2/R1) to (R2/R1), we’ve done exactly that. We now have four resistors; we need to make sure the gains are equal so the ratio of the resistors is important:

alt text

The problem with this circuit is that in order to obtain high gain, R1 must be relatively low. This causes the input resistance to drop. Another issue is that it isn’t easy to vary the gain of this amplifier. Both of these issues are solved with the implementation of the instrumentation amplifier. Using three op amps, we can get a fine-tuned differential amplifier. Since we have the problem of low input resistance using one op amp, we can add an additional voltage follower or buffer at each input. Even more awesome is that the buffers can add to the gain, easing the burden on the difference amplifier in the second stage.

alt text

The instrumentation amplifier perfectly combines all the previous material: inverting and non-inverting amplifiers in cascade.

We will not cover integrators, differentiators, oscillators or AD converters in this tutorial. Once we start adding capacitors and inductors, the math gets a bit more specialized and generalized in terms of impedance rather than resistance. These will be a separate tutorial.

Performance Characteristics

If we look at a data sheet for the LM386 audio amplifier, we’ll see a ton of parameters that help characterize the op amp. Most of these can be verified with simulation in LTSpice. Before we can get there let’s define some of these characteristics.

Common Mode Rejection Ratio

Common mode rejection ratio (CMRR) measures the amount of signal common to both inputs that is not amplified. It is desirable for the common mode gain to be very low, which corresponds with a very high CMRR.

alt text

The common mode rejection ratio is the ratio of the absolute value of differential gain to the absolute value of the common mode gain. The differential gain is typically half the intrinsic gain of the MOS transistor set by the manufacturer. Op amps with high output resistance will feature the best CMRR.

Power Supply Rejection Ratio

Power Supply Rejection Ratio or PSRR is the measure of the influence of the power supply ripple on the op amp output voltage. PSSR is important to MOSFET devices as they are usually on mixed-signal ICs where the digital switching in the circuit causes increased power supply ripple. The last thing you want in your design is to have that ripple amplified through your op amp.

alt text

The takeaway here is that to minimize the effects of ripple in power supplies, the Op Amp is required to have a large PSRR. So keep that in mind when looking at data sheets for any upcoming projects.

Slew Rate

Slew rate refers to the maximum rate of change possible at the output of an op amp. Most op amps are slew rate-limited, and that is calculated by taking the max of the derivative, with respect to time of the output voltage of the op amp.

alt text

Total Harmonic Distortion

The task of an audio amplifier is to take a small signal and amplify it without making any changes other than amplifying it. This is a difficult task because unwanted signals (i.e. ripple) may be amplified along with the desired signal. Any deviation from linearity is considered a distortion. Harmonic distortion is a common form of distortion in audio applications where the peaks of the output signal get “clipped.” The lower the percentage listed for THD the better, but after a certain point it is hardly perceptible to human ears.

The LM386 Audio Amplifier - or, the Case for Analog Electronics - or, When You Go Too Far

Simulate, verify, build – my motto. In this case, the mini portable guitar amp project case, I took it too far. I couldn’t find a model I could import into LTSpice and I started from scratch. Below is a button where you can download the project files for what I am about to show you. I designed an op amp based on the LM386, but with MOSFETs instead of BJTs. I actually got this design to slightly outperform the part I based my design off of, but it only works from 2 to 6 volts. Even though my LM386 model is not exactly like the part used in the project, it is still practical for looking at the electrical characteristics of op amps and getting more familiar with LTSpice.

Let’s take a look at the project first and then look at the internal op amp design and simulation.

Project: Mini Portable Guitar Amplifier

I built a small, battery-powered amplifier into the case of my guitar using the LM386 and minimal extra parts. The whole build cost about $5.00 and took less than an hour to put together. The circuit I took directly from the data sheet applications section (Gain of 200):

alt text

The only changes I made were to the output capacitor. I didn’t have a 250uF capacitor handy to I swapped it out for a 470uF. I also added the ¼" mono audio female receptacle for the guitar cable and added a status LED so I knew when I was ready to rock. My guitar case has a little cubby for cables and picks so I used that space to build the amplifier into.

alt text

See it in action:

The Op Amp Design

Ok, this is where things got a little out of hand. I coudn’t find a model to import into LTSpice for the LM386, so I spent a few days designing one from scratch. I have to admit I have done this twice before but by no means is this my forté. This design is available for download in the Sims.zip folder from the beginning of the tutorial.

alt text

Getting the bias just right: All the transistors you see here are in the box in the upper left of the op amp design.

alt text

Gain Enhancement (NMOS): The NMOS gain enhancement circuit is found in the box in the upper right side of the op amp design.

alt text

Gain Enhancement (PMOS): The PMOS gain enhancement circuit is found in the box in the lower right side of the op amp design.

alt text

Final Circuit with gain of 200 for the portable guitar amp application:

alt text

Resources and Going Further

The Virtual Op Amp Lab:

Music from Outer Space creator Ray Wilson made this MFOS Virtual Operational Amplifier Application, which allows us to experiment with op amps while viewing the output on a simulated oscilloscope.

Music From Outer Space

Ever wanted to get into DIY-synths but don’t know where to start? Music From Outer Space is a great resource offering hundreds of schematics designed by Ray Wilson.

Hobbyists

If you are just getting into analog electronics projects, I cannot recommend Forrest Mims' Engineer’s Mini Notebooks enough.

Measuring CMRR

EE Times has a fantastic article about common mode rejection ratio and differential amplifiers.


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

OpenPIR Hookup Guide

$
0
0

OpenPIR Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Passive Infrared (PIR) sensors detect motion in a local area and are the sensor of choice in security systems, home automation and proximity-sensing applications.

SparkFun OpenPIR

SEN-13968
14.95

The SparkFun OpenPIR is a highly customizable PIR sensor based around the NCS36000 PIR controller. The OpenPIR allows you to set the sensitivity, trigger time and pulse mode of the motion sensor, so you can tailor-fit it to your application.

Required Materials

To follow along with this hookup guide, a handful of components are suggested in addition to the OpenPIR. A microcontroller development board, like an Arduino, RedBoard, Photon or Teensy is recommended. The development board can be used to both power the OpenPIR and act on its motion triggers.

Arduino Uno - R3

DEV-11021
24.95
92
SparkFun RedBoard - Programmed with Arduino

DEV-13975
19.95
3
Teensy 3.2

DEV-13736
19.95
44
Particle Photon (Headers)

WRL-13774
19
24

You’ll also need something to electrically connect the OpenPIR’s power and signal pins to that microcontroller. The OpenPIR includes both a 0.1" header and a 4-pin JST connector footprint, so you can use male headers or a 4-pin JST cable assembly to interface with the sensor.

Break Away Headers - Straight

PRT-00116
1.5
20
Jumper Wires Premium 6" M/F Pack of 100

PRT-09139
24.95
7
Jumper Wires Premium 6" M/M Pack of 100

PRT-10897
24.95
6
JST Jumper 4 Wire Assembly

PRT-09916
1.5
2

Tools

Finally, you’ll need soldering tools to electrically connect the connector of your choice to the OpenPIR. A simple soldering iron and solder should be all you need.

You may also need a small Phillips-head screwdriver to adjust the pair of trimpots on the back of the OpenPIR. Our pocket screwdriver includes a small enough bit, as does the larger screwdriver and bit set.

Soldering Iron - 30W (US, 110V)

TOL-09507
9.95
6
Solder Lead Free - 15-gram Tube

TOL-09163
3.5
2
Pocket Screwdriver Set

TOL-12891
3.95
3
Tool Kit - Screwdriver and Bit Set

TOL-10865
9.95
2

Suggested Reading

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

Analog to Digital Conversion

The world is analog. Use analog to digital conversion to help digital devices interpret the world.

Logic Levels

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

Analog vs. Digital

This tutorial covers the concept of analog and digital signals, as they relate to electronics.

PIR Motion Sensor Hookup Guide

An overview of passive infrared (PIR) motion detecting sensors, and how to hook them up to an Arduino.

Hardware Overview

Power/output header

Powering and interfacing with the OpenPIR is accomplished using the four pins broken out on the bottom of the board. Those pins are:

Pin LabelDescription
AAnalog output of NCS36000 differential amplifiers.
VCCPower supply input
GNDGround supply input
OUTDigital output signal – active-high.

More on those pins in the sections below.

Supplying Power

Power to the OpenPIR should be supplied to the VCC and GND pins. The OpenPIR’s operating voltage supply range is 3V to 5.75V— as specified by the board’s NCS36000 PIR controller. That means it should work with any 3.3V or 5V system.

Electrical characteristics:

  • Voltage supply range: 3VDC to 5.75VDC
  • Standby average current: 80µA
  • Motion-detected average current: 3mA (LED enabled)

The OpenPIR consumes relatively little power. When the sensor isn’t triggered — and the activity LED is not illuminated — the OpenPIR will consume about 80µA. When active, the onboard LED’s current draw dwarfs the PIR’s operating current, consuming about 3mA. That LED can be disabled using the xLED jumper (see applicable section below).

Digital Motion Trigger Output

The OUT pin is an active-high digital signal, which indicates the OpenPIR’s motion detection. When motion is detected, the pin is driven HIGH; otherwise it will be LOW.

This pin can drive up to 10mA — so you can hook an LED or other small load up to it. Otherwise it can be connected directly to a microcontroller input pin (no pull-up or pull-down resistor required).

The operation of this pin is mirrored by the green, reverse-entry “DET”-labeled LED — if the LED is on, the OUT pin should be HIGH.

The duration of a HIGH signal on the OUT pin is set by the “OSC” trimpot, which is discussed more in-depth later in this section.

Analog Output

The “A”-labeled output breaks out the amplified PIR signal before it’s sent to a window comparator, and then to the OUT pin.

Block diagram location of "A" pin breakout

Absent of any motion, the voltage at this pin will hover around 2.1V (about 430 on a 5V Arduino’s 10-bit ADC input). As motion is detected, though, that voltage may swing wildly.

Output from "A" pin, plotted in Arduino

This pin can be used to get a better idea of what kind of motion triggered the PIR. Single passes by the PIR may only produce a small “blip” on the “A” pin, while vigorous motion may produce a large, spiky wave output.

LED Output

A reverse-entry green LED is included on the board, which duplicates the status of the OUT pin. When motion is detected, the LED will illuminate; otherwise it will remain off.

Indicator LED On

On initial power-up, the LED will blink, indicating the NCS36000 is in start-up mode. Start-up mode can last for a few seconds or a couple of minutes — the length of time spent in start-up depends on the position of the “OSC” trimpot. The start-up mode time upon shipment is about two minutes.

The LED can be disabled by opening the “xLED” jumper. Note that the LED will still blink during start-up mode, regardless of the jumper’s state.

Trimpots — Sensitivity and Oscillator Window

The pair of trimming potentiometers (trimpots) on the backside of the OpenPIR can be used to customize the behavior of your motion sensor.

Trimpots highlighted

The sensitivity trimpot— labeled “SEN” — can be used to adjust the view distance of the OpenPIR. The more clockwise you turn this trimpot, the further your sensor should be able to see. When you receive the board, the trimpot will be centered, and the sensor will react to a person moving about in the 6 to 8 foot (2 to 2.5m) range. At the maximum sensitivity, the sensor will detect a person walking by at about 16 feet (5m).

Avoid turning the "SEN" trimpot all the way down (counter-clockwise). This will disable the OpenPIR's output – even the most mobile environments will not trigger an active output.

The “OSC” trimpot ultimately controls the length of time the output remains HIGH. This trimpot is used to adjust the oscillator frequency of the NCS36000. Turning this trimpot clockwise increases the length of time OUT remains high.

With the OSC trimpot cranked all the way in the counterclockwise direction, the OUT pin will remain HIGH for about 400 milliseconds. Conversely, when the trimpot is turned to the far-clockwise, the OSC pin will remain HIGH for about 7.5 seconds. The trigger time should adjust relatively linearly between those two values. When you receive the board, it will be centered, and the trigger pulse will last a bit less than four seconds.

Trigger Mode — Dual vs. Single

The NCS36000 supports two motion-detection modes: single-pulse and dual-pulse. Either of these modes can be selected using the switch adjacent to the trimpots on the back of the board.

Switch highlighted

The NCS36000 uses a window comparator — a pair of comparators with upper and lower voltage limits — to trigger a pulse on the OUT pin. In single-pulse mode, a voltage above or below the upper or lower comparators will trigger an output pulse. But in dual-pulse mode, the voltage must swing above the high comparator voltage and below the low comparator voltage — within a set time limit — to trigger an output.

These timing diagrams from the NCS36000 datasheet can help to clarify single-pulse versus dual-pulse:

Single vs. dual pulse mode detection

Single-pulse mode can be used to detect an object entering or exiting the PIR’s field-of-view, while dual-pulse detection can be used to detect an object entering and leaving the view area.

Hardware Assembly

Before you can power the OpenPIR and connect it to a project, you’ll need to solder something to the quartet of pins on the bottom of the board.

New to soldering? Check out our Through-Hole Soldering Tutorial for a quick introduction!

The OpenPIR’s power and output pins are broken out to both a standard 0.1" header and a 4-pin JST PH connector, leaving you a number of options for what, exactly, you’ll solder to the sensor. To the 0.1" header, you can solder male headers (or the right-angle version), female headers or wire.

Right angle header pins, in a breadboard

Or you can solder a 4-Pin JST connector to the smaller-pitch footprint.

4-pin JST shown connected to sensor

As a bonus, plugging our 4-wire JST cable assembly into the OpenPIR will logically color-code the power supply pins — VCC on red, GND on black, OUT on yellow, and the analog output connected to blue.

Firmware Example

The firmware example below uses Arduino to demonstrate how both the digital output and analog output can be used. Here is the example circuit used in the example code:

Fritzing diagram for this sketch

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Then upload the example code below so you can begin to get a feel for the OpenPIR’s output pins:

language:c
//////////////////////////
// Hardware Definitions //
//////////////////////////
#define PIR_AOUT A0  // PIR analog output on A0
#define PIR_DOUT 2   // PIR digital output on D2
#define LED_PIN  13  // LED to illuminate on motion

#define PRINT_TIME 100 // Rate of serial printouts
unsigned long lastPrint = 0; // Keep track of last serial out

void setup()
{
  Serial.begin(115200);  // Serial is used to view Analog out
  // Analog and digital pins should both be set as inputs:
  pinMode(PIR_AOUT, INPUT);
  pinMode(PIR_DOUT, INPUT);

  // Configure the motion indicator LED pin as an output
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, LOW); // Turn the LED off
}

void loop()
{
  // Read OUT pin, and set onboard LED to mirror output
  readDigitalValue();

  // Read A pin, print that value to serial port:
  printAnalogValue();
}

void readDigitalValue()
{
  // The OpenPIR's digital output is active high
  int motionStatus = digitalRead(PIR_DOUT);

  // If motion is detected, turn the onboard LED on:
  if (motionStatus == HIGH)
    digitalWrite(LED_PIN, HIGH);
  else // Otherwise turn the LED off:
    digitalWrite(LED_PIN, LOW);
}

void printAnalogValue()
{
  if ( (lastPrint + PRINT_TIME) < millis() )
  {
    lastPrint = millis();
    // Read in analog value:
    unsigned int analogPIR = analogRead(PIR_AOUT);
    // Convert 10-bit analog value to a voltage
    // (Assume high voltage is 5.0V.)
    float voltage = (float) analogPIR / 1024.0 * 5.0;
    // Print the reading from the digital pin.
    // Mutliply by 5 to maintain scale with AOUT.
    Serial.print(5 * digitalRead(PIR_DOUT));
    Serial.print(',');    // Print a comma
    Serial.print(2.5);    // Print the upper limit
    Serial.print(',');    // Print a comma
    Serial.print(1.7);    // Print the lower limit
    Serial.print(',');    // Print a comma
    Serial.print(voltage); // Print voltage
    Serial.println();
  }
}

This code uses the Arduino’s onboard LED — on pin 13 — to reflect the OpenPIR’s digital motion output. When motion is detected, the Arduino’s LED should illuminate.

Four values are printed to the serial terminal — the reading from the digital pin (multiplied by 5…for a reason), the upper and lower comparator voltage thresholds and the reading from the analog pin. Open up your serial monitor — setting the baud rate to 115200 — to see them stream by:

Serial terminal output example

Since it may be difficult to visualize the sensor’s analog output using the serial terminal, try opening up the serial plotter (found under the “Tools” >“Serial Plotter” menu).

Serial plotter example

You should see two separate line graphs: the light blue indicating the analog value and the dark blue representing the digital output. The orange and red straight lines represent the upper and lower thresholds, which the analog value must exceed to trigger motion.

Wave at the sensor to get a better feel for the analog output’s behavior. And make sure you try both single and dual modes to see how the switch alters the sensor’s functionality.

Resources & Going Further

Now that you’ve successfully got your OpenPIR 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:

Vernier Photogate

Vernier Photogate Timer -- using the Serial Enabled LCD Kit.

Are You Okay? Widget

Use an Electric Imp and accelerometer to create an "Are You OK" widget. A cozy piece of technology your friend or loved one can nudge to let you know they're OK from half-a-world away.

ZX Distance and Gesture Sensor Hookup Guide

How to connect and use the SparkFun ZX Distance and Gesture Sensor with an Arduino.

Boss Alarm

Build a Boss Alarm that alerts you of anyone walking into your office and automatically changes your computer screen.

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

CCS811 Air Quality Breakout Hookup Guide

$
0
0

CCS811 Air Quality Breakout Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The CCS811 Air Quality Breakout is a digital gas sensor solution that senses a wide range of Total Volatile Organic Compounds (TVOCs), including equivalent carbon dioxide (eCO2) and metal oxide (MOX) levels. It is intended for indoor air quality monitoring in personal devices such as watches and phones, but we’ve put it on a breakout board so you can use it as a regular I2C device.

SparkFun Air Quality Breakout - CCS811

SEN-14193
29.95

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.

How to Solder: Through-Hole Soldering

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

Installing an Arduino Library

How do I install a custom Arduino library? It's easy!

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.

I2C

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

Hardware Overview

The CCS811 is supported by only a few passives, and so the breakout board is relatively simple. This section discusses the various pins on the board.

alt text

Connections available to the user are shown on the top side

alt text

Jumpers are available on the bottom

Pins

PinDescriptionDirection
RSTReset (active low)In
INTInterrupt (active low)Out
WAKWake (active low)In
SCLClockIn
SDADataIn
3.3VPowerIn
GNDGroundIn
NTC (2 pins)Negative thermal coefficient resistorN/A

Power and I2C Bus

The minimum required connections are power, ground SDA and SCL. Supply a regulated 3.3V between the board’s 3.3V pin and ground terminals. The sensor consumes an average of 12mA of current.

The I2C bus has pull-up resistors enabled by default. If not desired, these can be removed by separating the “I2C PU” triple jumper on the bottom side with a hobby knife.

An I2C address can be either 0x5A or 0x5B. The “ADDR” jumper is connected with copper from the factory, corresponding to a default address of 0x5B. Separate this jumper to use the address 0x5A.

Settling time: This sensor takes about 20 minutes to get fully settled to a point where it generates good data. The I2C bus is active, and data can be collected before the 20 minutes is up, but it may not be accurate.

Control lines

Additionally, the three control lines RST, INT and WAK can be used to further the degree of control.

  • RST— Pull this line low to reset the IC.
  • INT— After configuring the sensor to emit interrupt requests, read this line to determine the state of the interrupt.
  • WAK— Pull this line high to put the sensor to sleep. This can be used to save power but is not necessary if power is not an issue.

NTC Thermistor operation

A thermistor can be used to determine the temperature of the CCS811’s surroundings, which can be used to help compensate the readings. You’ll need your own 10K NTC thermistor, such as our 10K Thermistor, soldered between the “NTC” pins. A thermistor is a nonpolarized device, so it can go in either way.

Hardware Assembly

Attach Headers

To prepare the sensor for the examples, attach seven pins from a Break Away Header to the through holes. Even though we only need the four I2C pins, we’ll populate all of them for this guide in case we want to try them out.

alt text

Place the strip of seven pins in a breadboard.

alt text

Solder a single pin and then check that the board is square to the pins.

alt text

Solder the remaining pins.

Attach NTC thermistor (Optional)

If you would like to use a thermistor to compensate for temperature, solder in a 10K Thermistor (Vishay part number NTCLE100E3103JB0).

alt text

Attaching an NTC thermistor

Example Assemblies

You’re ready to start communicating with the CCS811! Here’s an example with the NTC Thermistor populated, and one using right-angle headers instead.

alt text

Arduino Library and Usage

Getting the CCS811 Arduino Library

To get the Arduino library, download from GitHub or use the Arduino Library Manager.

Download the GitHub repository

Visit the GitHub repository to download the most recent version of the library, or click the button below:

Download the SparkFun CCS811 Arduino Library

Use the Library Manager or install in the Arduino IDE

For help installing the library, check out our Installing an Arduino Library tutorial.

If you don’t end up using the manager, you’ll need to move the SparkFun_CCS811_Arduino_Library folder into a libraries folder within your Arduino sketchbook. If you downloaded the zip, you can remove “master” from the name, but it’s not required.

Using the Library

The library is fairly normal to use compared with our other sensors. You’ll have to include the library, create a sensor object in the global space, and then use functions of that object to begin and control the sensor. With this one, pass the I2C address must to the object during construction.

To get the library included, and to take care of all the gritty compiler stuff, place the following at the beginning of the sketch before void setup()

language:c
#include <SparkFunCCS811.h>

#define CCS811_ADDR 0x5B //Default I2C Address
//#define CCS811_ADDR 0x5A //Alternate I2C Address

CCS811 myCCS811(CCS811_ADDR);

Now, functions of the object named myCCS811 can be called to set up and get data, while all the wire stuff is kept under the hood.

To make the sensor get ready during program boot, myCCS811.begin() must be called. Here’s an example of the minimal usage of begin.

Error Status: The .begin() function has a special feature: it returns the status of the function call! If there was a problem during begin, it will return a non-zero code indicating what happened. It's optional, and is described in the "Custom Types and Literals" section below.
language:c
void setup()
{
    myCCS811.begin();
}

Then, in the main loop of the program, call sensor functions such as mySensor.readAlgorithmResults() to operate the sensor. The following snippet shows a simple check for data, to call on the sensor to calculate and get values, and to access those values. It doesn’t do anything with the data, though! Check out the examples for fully functional code.

language:c
void loop()
{
  if (myCCS811.dataAvailable())
  {
    myCCS811.readAlgorithmResults();
    int tempCO2 = myCCS811.getCO2();
    int tempVOC = myCCS811.gettVOC();
  }
  else if (myCCS811.checkForStatusError())
  {
    while(1);
  }

  delay(1000); //Wait for next reading
}

Function Reference

The following functions exist for the CCS811 object.

Functions with scoped return type CCS811Core::status report an error state as defined in the literals section below. It is optional and can be used to determine success or failure of call.

  • CCS811Core::status begin( void )— This starts wire, checks the ID register, checks for valid app data, starts the app, and establishes a drive mode.

  • CCS811Core::status readAlgorithmResults( void )— Call to cause the sensor to read its hardware and calculate TVOC and eCO2 levels.

  • bool checkForStatusError( void )— Returns true if there is an error pending. This checks the status register.

  • bool dataAvailable( void )— Returns true if a new sample is ready and hasn’t been read.

  • bool appValid( void )— Returns true if there is a valid application within the internal CCS811 memory.

  • uint8_t getErrorRegister( void )— Returns the state of the ERROR_ID register.

  • uint16_t getBaseline( void )— Returns the baseline value.

  • CCS811Core::status setBaseline( uint16_t )— Apply a saved baseline to the CCS811.

  • CCS811Core::status enableInterrupts( void )— Enables the interrupt pin for data ready.

  • CCS811Core::status disableInterrupts( void )— Disables the interrupt pin.

  • CCS811Core::status setDriveMode( uint8_t mode )— Sets the drive mode (mode can be 0 through 4).

    • 0: Measurement off
    • 1: Measurement every 1 second
    • 2: Measurement every 10 seconds
    • 3: Measurement every 60 seconds
    • 4: Measurement every 0.25 seconds — for use with external algorithms

  • CCS811Core::status setEnvironmentalData( float relativeHumidity, float temperature )— Sets the environmental conditions for compensation.
    • relativeHumidity in units of %, 0.00 through 100.0
    • temperature in degrees C, -25.0 through 50.0

  • void setRefResistance( float )— If you’ve changed the thermistor pull-up, call this to give the sensor the new resistor value. Otherwise, it will be 10000.

  • CCS811Core::status readNTC( void )— Cause the CCS811 to get and calculate a temperature from the thermistor input.

  • uint16_t getTVOC( void )— Collect the last calculated TVOC value, in parts per billion (ppb).

  • uint16_t getCO2( void )— Collect the last calculated eC02 value, in parts per million (ppm).

  • float getResistance( void )— Collect the last calculated resistance value of the NTC terminals.

  • float getTemperature( void )— Collect the last calculated temperature.

Custom Types and Literals

The CCS811 library defines the following special data type to deal with error states of functions. In most places the library can be used without paying attention to the function return types, but if they are needed, here are the values the data type status can hold:

language:c
// Return values
typedef enum
{
    SENSOR_SUCCESS,
    SENSOR_ID_ERROR,
    SENSOR_I2C_ERROR,
    SENSOR_INTERNAL_ERROR
    //...
} status;

To avoid the possibility of multiple libraries using the same status name, the enum is actually inside the scope of the CCS811 object, buried in the CCS811Core, which is the base class. Phew, don’t worry about that too much; just place CCSCore:: before the status name when you want to use it, and use it like a regular enum (e.g., CCS811Core::status myLocalReturnStatus;). This just tells the compiler that the variable name is in a specific place. You’ll also have to add the scope operator to the enum names.

Here’s an example that shows how the status enum can be used:

language:c
CCS811Core::status returnCode = mySensor.beginCore();
Serial.print("beginCore exited with: ");
switch ( returnCode )
{
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.");
}

The library also defines names for CCS811 registers, if you’re using direct read and write functions. These are globally scoped and can be used anywhere.

language:c
//Register addresses
#define CSS811_STATUS 0x00
#define CSS811_MEAS_MODE 0x01
#define CSS811_ALG_RESULT_DATA 0x02
#define CSS811_RAW_DATA 0x03
#define CSS811_ENV_DATA 0x05
#define CSS811_NTC 0x06
#define CSS811_THRESHOLDS 0x10
#define CSS811_BASELINE 0x11
#define CSS811_HW_ID 0x20
#define CSS811_HW_VERSION 0x21
#define CSS811_FW_BOOT_VERSION 0x23
#define CSS811_FW_APP_VERSION 0x24
#define CSS811_ERROR_ID 0xE0
#define CSS811_APP_START 0xF4
#define CSS811_SW_RESET 0xFF

Example: Basic Reading

After you’ve got pins attached to your breakout board, the first example to use should be BasicReadings. Select it from examples or copy from below.

Connect the sensor as follows as a starting place for the examples.

alt text

Wiring diagram showing basic connection to RedBoard. Click for a closer look.

For this example, only 3.3V, GND, SDA and SCL are needed. The jumpers on the board are left in the default positions.

language:c
/******************************************************************************
  BasicReadings.ino

  Marshall Taylor @ SparkFun Electronics
  Nathan Seidle @ SparkFun Electronics

  April 4, 2017

  https://github.com/sparkfun/CCS811_Air_Quality_Breakout
  https://github.com/sparkfun/SparkFun_CCS811_Arduino_Library

  Read the TVOC and CO2 values from the SparkFun CSS811 breakout board

  This is the simplest example.  It throws away most error information and
  runs at the default 1 sample per second.

  A new sensor requires at 48-burn in. Once burned in a sensor requires
  20 minutes of run in before readings are considered good.

  Hardware Connections (Breakoutboard to Arduino):
  3.3V to 3.3V pin
  GND to GND pin
  SDA to A4
  SCL to A5

  Resources:
  Uses Wire.h for i2c operation

  Development environment specifics:
  Arduino IDE 1.8.1

  This code is released under the [MIT License](http://opensource.org/licenses/MIT).

  Please review the LICENSE.md file included with this example. If you have any questions
  or concerns with licensing, please contact techsupport@sparkfun.com.

  Distributed as-is; no warranty is given.
******************************************************************************/
#include "SparkFunCCS811.h"

#define CCS811_ADDR 0x5B //Default I2C Address
//#define CCS811_ADDR 0x5A //Alternate I2C Address

CCS811 mySensor(CCS811_ADDR);

void setup()
{
  Serial.begin(9600);
  Serial.println("CCS811 Basic Example");

  //It is recommended to check return status on .begin(), but it is not
  //required.
  status_t returnCode = mySensor.begin();
  if (returnCode != SENSOR_SUCCESS)
  {
    Serial.println(".begin() returned with an error.");
    while (1); //Hang if there was a problem.
  }
}

void loop()
{
  //Check to see if data is ready with .dataAvailable()
  if (mySensor.dataAvailable())
  {
    //If so, have the sensor read and calculate the results.
    //Get them later
    mySensor.readAlgorithmResults();

    Serial.print("CO2[");
    //Returns calculated CO2 reading
    Serial.print(mySensor.getCO2());
    Serial.print("] tVOC[");
    //Returns calculated TVOC reading
    Serial.print(mySensor.getTVOC());
    Serial.print("] millis[");
    //Simply the time since program start
    Serial.print(millis());
    Serial.print("]");
    Serial.println();
  }

  delay(10); //Don't spam the I2C bus
}

At the beginning, an object is created in the global space CCS811 mySensor(CCS811_ADDR); and is constructed with the address as a parameter. During the setup phase, the library is told to configure with status_t returnCode = mySensor.begin(); Using the return parameter to check for errors is optional, and in this example if the return code is not valid, the program enters a captive while loop.

To get data from the sensor, mySensor.dataAvailable() is checked until a new reading is ready, mySensor.readAlgorithmResults(); is called to have the sensor process the reading, then mySensor.getCO2() and mySensor.getTVOC() are used to retrieve the calculated values for gas levels.

alt text

Example terminal output

If everything is connected correctly, the serial window will report gas levels every second. Remember the sensor takes 20 minutes to properly warm up, so values reported will rise up in the early stages of operation!

Summary:

To get data from the CCS811, these minimum requirements must be met:

  • Create a CCS811 object in the global space
  • Run .begin() of your object (Return type monitoring optional)
  • Check for the availability of new data with .dataAvailable()
  • Use .readAlgorithmResults() to perform a measurement
    • .getCO2() to get the last equivalent CO2 reading (no I2C bus operation)
    • .getTVOC() to get the last TVOC reading (no I2C bus operation)

Example: Additional Control Lines

The CCS811 has a couple extra control lines that are not part of the I2C bus, which can be utilized to improve the system. There’s a pin to flag that data is ready, and a pin to make the sensor go to sleep.

alt text

Wiring diagram including the wake and interrupt pins. Click for a closer look.

To connect the interrupt line, connect it directly to an input pin. This is a 3.3V output from the sensor, so it’s OK to drive the input logic of a 5V device from it. The example has nInt connected to pin 6.

To connect the wake stat line, use a voltage divider to divide the 5V coming from the Arduino down to something below 3.3V for the sensor. The example has nWake connected to pin 5 through a voltage divider made from two 4.7K resistors for a 2.5V output.

The example for these additional lines is called WakeAndInterrupt and is listed here:

language:c
/******************************************************************************
  WakeAndInterrupt.ino

  Marshall Taylor @ SparkFun Electronics

  April 4, 2017

  https://github.com/sparkfun/CCS811_Air_Quality_Breakout
  https://github.com/sparkfun/SparkFun_CCS811_Arduino_Library

  This example configures the nWAKE and nINT pins.
  The interrupt pin is configured to pull low when the data is
  ready to be collected.
  The wake pin is configured to enable the sensor during I2C communications

  Hardware Connections (Breakoutboard to Arduino):
  3.3V to 3.3V pin
  GND to GND pin
  SDA to A4
  SCL to A5
  NOT_INT to D6
  NOT_WAKE to D5 (For 5V arduinos, use resistor divider)
    D5---
         |
         R1 = 4.7K
         |
         --------NOT_WAKE
         |
         R2 = 4.7K
         |
        GND

  Resources:
  Uses Wire.h for i2c operation

  Development environment specifics:
  Arduino IDE 1.8.1

  This code is released under the [MIT License](http://opensource.org/licenses/MIT).

  Please review the LICENSE.md file included with this example. If you have any questions
  or concerns with licensing, please contact techsupport@sparkfun.com.

  Distributed as-is; no warranty is given.
******************************************************************************/
#include <SparkFunCCS811.h>

#define CCS811_ADDR 0x5B //Default I2C Address
//#define CCS811_ADDR 0x5A //Alternate I2C Address

#define PIN_NOT_WAKE 5
#define PIN_NOT_INT 6

CCS811 myCCS811(CCS811_ADDR);

//Global sensor object
//---------------------------------------------------------------
void setup()
{
  //Start the serial
  Serial.begin(9600);
  Serial.println();
  Serial.println("...");

  status_t returnCode;

  //This begins the CCS811 sensor and prints error status of .begin()
  returnCode = myCCS811.begin();
  Serial.print("CCS811 begin exited with: ");
  printDriverError( returnCode );
  Serial.println();

  //This sets the mode to 60 second reads, and prints returned error status.
  returnCode = myCCS811.setDriveMode(2);
  Serial.print("Mode request exited with: ");
  printDriverError( returnCode );
  Serial.println();

  //Configure and enable the interrupt line,
  //then print error status
  pinMode(PIN_NOT_INT, INPUT_PULLUP);
  returnCode = myCCS811.enableInterrupts();
  Serial.print("Interrupt configuation exited with: ");
  printDriverError( returnCode );
  Serial.println();

  //Configure the wake line
  pinMode(PIN_NOT_WAKE, OUTPUT);
  digitalWrite(PIN_NOT_WAKE, 1); //Start asleep

}
//---------------------------------------------------------------
void loop()
{
  //Look for interrupt request from CCS811
  if (digitalRead(PIN_NOT_INT) == 0)
  {
    //Wake up the CCS811 logic engine
    digitalWrite(PIN_NOT_WAKE, 0);
    //Need to wait at least 50 us
    delay(1);
    //Interrupt signal caught, so cause the CCS811 to run its algorithm
    myCCS811.readAlgorithmResults(); //Calling this function updates the global tVOC and CO2 variables

    Serial.print("CO2[");
    Serial.print(myCCS811.getCO2());
    Serial.print("] tVOC[");
    Serial.print(myCCS811.getTVOC());
    Serial.print("] millis[");
    Serial.print(millis());
    Serial.print("]");
    Serial.println();

    //Now put the CCS811's logic engine to sleep
    digitalWrite(PIN_NOT_WAKE, 1);
    //Need to be asleep for at least 20 us
    delay(1);
  }
  delay(1); //cycle kinda fast
}


//printDriverError decodes the status_t type and prints the
//type of error to the serial terminal.
//
//Save the return value of any function of type status_t, then pass
//to this function to see what the output was.
void printDriverError( status_t errorCode )
{
  switch ( errorCode )
  {
    case SENSOR_SUCCESS:
      Serial.print("SUCCESS");
      break;
    case SENSOR_ID_ERROR:
      Serial.print("ID_ERROR");
      break;
    case SENSOR_I2C_ERROR:
      Serial.print("I2C_ERROR");
      break;
    case SENSOR_INTERNAL_ERROR:
      Serial.print("INTERNAL_ERROR");
      break;
    case SENSOR_GENERIC_ERROR:
      Serial.print("GENERIC_ERROR");
      break;
    default:
      Serial.print("Unspecified error.");
  }
}

//printSensorError gets, clears, then prints the errors
//saved within the error register.
void printSensorError()
{
  uint8_t error = myCCS811.getErrorRegister();

  if ( error == 0xFF ) //comm error
  {
    Serial.println("Failed to get ERROR_ID register.");
  }
  else
  {
    Serial.print("Error: ");
    if (error & 1 << 5) Serial.print("HeaterSupply");
    if (error & 1 << 4) Serial.print("HeaterFault");
    if (error & 1 << 3) Serial.print("MaxResistance");
    if (error & 1 << 2) Serial.print("MeasModeInvalid");
    if (error & 1 << 1) Serial.print("ReadRegInvalid");
    if (error & 1 << 0) Serial.print("MsgInvalid");
    Serial.println();
  }
}

Notice that this example doesn’t poll dataAvailable() to check if data is ready; instead it reads the state of a digital input. When the input is low, data is ready in the sensor and readAlgorithmResults(), then .getCO2() and getTVOC() are used as normal.

The WAK pin can be used to control the logic engine on the CCS811 to save a bit of power. When the WAK pin is low (or disconnected), the I2C bus will respond to commands, but when the pin is high it will not. Tens of microseconds are required to wake or sleep, so in this example, commands are wrapped with a 1ms delay.

alt text

Example terminal output

The terminal displays the calculation every 10 seconds. You can see that it take a few samples for the algorithm to spit out data, even at a slow rate of acquisition. Between the sampling, power is decreased as much as possible.

Summary:

To use WAK,

  • Set up a digital output for the wake pin
  • To communicate with a sleeping sensor,
    • Set WAK low
    • Wait 50us
    • Do your communication
    • Set WAK high
    • Wait 20us

To use INT,

  • Set up a digital input for the interrupt pin
  • Enable interrupts with enableInterrupts()
  • Look for a falling edge on the input to detect the availability of new data

Example: Compensating for Climate

To have the CCS811 compensate for pressure and temperature conditions, obtain those metrics and pass to the sensor object with setEnvironmentalData.

The examples from the library show three different sources of data that can be used to calibrate the CCS811:

  1. Randomly generated temperature and humidity data
  2. Data from a supplemental BME280 sensor
  3. Data collected by reading the NTC pins

This guide only shows the example that uses randomized data, as it can be used without additional components yet still illustrate the effects of different climates.

From Arduino Library and Usage,

  • status_t setEnvironmentalData( float relativeHumidity, float temperature )— Sets the environmental conditions for compensation.
    • relativeHumidity in units of %, 0.00 through 100.0
    • temperature in degrees C, -25.0 through 50.0

Compensating with Random Data

A starting place for working with the compensation is the setEnvironmentalReadings example. After the same configuration from the basic example, this sketch applies a random temperature and humidity, then takes 10 reads and repeats.

language:c
/******************************************************************************
setEnvironmentalReadings.ino

Marshall Taylor @ SparkFun Electronics

April 4, 2017

https://github.com/sparkfun/CCS811_Air_Quality_Breakout
https://github.com/sparkfun/SparkFun_CCS811_Arduino_Library

Hardware Connections (Breakoutboard to Arduino):
  3.3V to 3.3V pin
  GND to GND pin
  SDA to A4
  SCL to A5

Generates random temperature and humidity data, and uses it to compensate the CCS811.
This just demonstrates how the algorithm responds to various compensation points.
Use NTCCompensated or BME280Compensated for real-world examples.

Resources:
Uses Wire.h for i2c operation

Development environment specifics:
Arduino IDE 1.8.1

This code is released under the [MIT License](http://opensource.org/licenses/MIT).

Please review the LICENSE.md file included with this example. If you have any questions
or concerns with licensing, please contact techsupport@sparkfun.com.

Distributed as-is; no warranty is given.
******************************************************************************/
float temperatureVariable = 25.0; //in degrees C
float humidityVariable = 65.0; //in % relative

#include <Wire.h>
#include "SparkFunCCS811.h"

#define CCS811_ADDR 0x5B //Default I2C Address
//#define CCS811_ADDR 0x5A //Alternate I2C Address

CCS811 myCCS811(CCS811_ADDR);

void setup()
{
    Serial.begin(9600);
    Serial.println("CCS811 EnvironmentalReadings Example");

    //This begins the CCS811 sensor and prints error status of .begin()
    status_t returnCode = myCCS811.begin();
    Serial.print("begin exited with: ");
    printDriverError( returnCode );
    Serial.println();

}

void loop()
{
    Serial.println();
    //Randomize the Temperature and Humidity
    humidityVariable = (float)random(0, 10000)/100; //0 to 100%
    temperatureVariable = (float)random(500, 7000)/100; // 5C to 70C
    Serial.println("New humidity and temperature:");
    Serial.print("  Humidity: ");
    Serial.print(humidityVariable, 2);
    Serial.println("% relative");
    Serial.print("  Temperature: ");
    Serial.print(temperatureVariable, 2);
    Serial.println(" degrees C");
    myCCS811.setEnvironmentalData(humidityVariable, temperatureVariable);

    Serial.println("Environmental data applied!");
    myCCS811.readAlgorithmResults(); //Dump a reading and wait
    delay(1000);
    //Print data points
    for( int i = 0; i < 10; i++)
    {
        if (myCCS811.dataAvailable())
        {
            //Calling readAlgorithmResults() function updates the global tVOC and CO2 variables
            myCCS811.readAlgorithmResults();

            Serial.print("CO2[");
            Serial.print(myCCS811.getCO2());
            Serial.print("] tVOC[");
            Serial.print(myCCS811.getTVOC());
            Serial.print("] millis[");
            Serial.print(millis());
            Serial.print("]");
            Serial.println();
        }
        else if (myCCS811.checkForStatusError())
        {
            //If the CCS811 found an internal error, print it.
            printSensorError();
        }
        delay(1000); //Wait for next reading
    }
}


//printDriverError decodes the status_t type and prints the
//type of error to the serial terminal.
//
//Save the return value of any function of type status_t, then pass
//to this function to see what the output was.
void printDriverError( status_t errorCode )
{
    switch( errorCode )
    {
    case SENSOR_SUCCESS:
        Serial.print("SUCCESS");
        break;
    case SENSOR_ID_ERROR:
        Serial.print("ID_ERROR");
        break;
    case SENSOR_I2C_ERROR:
        Serial.print("I2C_ERROR");
        break;
    case SENSOR_INTERNAL_ERROR:
        Serial.print("INTERNAL_ERROR");
        break;
    case SENSOR_GENERIC_ERROR:
        Serial.print("GENERIC_ERROR");
        break;
    default:
        Serial.print("Unspecified error.");
    }
}

//printSensorError gets, clears, then prints the errors
//saved within the error register.
void printSensorError()
{
    uint8_t error = myCCS811.getErrorRegister();

    if( error == 0xFF )//comm error
    {
        Serial.println("Failed to get ERROR_ID register.");
    }
    else
    {
        Serial.print("Error: ");
        if (error & 1 << 5) Serial.print("HeaterSupply");
        if (error & 1 << 4) Serial.print("HeaterFault");
        if (error & 1 << 3) Serial.print("MaxResistance");
        if (error & 1 << 2) Serial.print("MeasModeInvalid");
        if (error & 1 << 1) Serial.print("ReadRegInvalid");
        if (error & 1 << 0) Serial.print("MsgInvalid");
        Serial.println();
    }
}

Compensating with BME280 Data

If you have a BME280 sensor, they work great for getting the compensation parameters. Use the example BME280Compensated to see compensation using another sensor.

Connecting the two devices is as simple as putting them on the bus together.

alt text

A BME280 used in conjunction with the CCS811

View BME280Compensated.ino on github, or use the example from Arduino.

Compensating from NTC Thermistor Readings

Alternately, an NTC resistor can be placed in the provide PTH terminals, and the example PTHCompensated can be used to see how the internal ADC is used to calibrate for temperature only.

There is one caveat to this method: no humidity data! Partially compensated is better than uncompensated, so punch in an average humidity for your area, or leave the example’s default at 50 percent.

View NTCCompensated.ino on github, or use the example from Arduino.

Resources and Going Further

Now that you’ve successfully got your CCS811 breakout up and running, and have scientifically proved which family member is the smelliest, here are some additional resources:

Also, the following examples are included with the library but not discussed. They may help you on your way!

  • BaselineOperator— Save and restore baselines to the EEPROM
  • Core— Show how the underlying hardware object works
  • TwentyMinuteTest— Report data with timestamp

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

MicroView Digital Compass

Build a portable digital compass using the SparkFun MicroView and the MAG3110 Magnetometer Breakout.

ZX Distance and Gesture Sensor Hookup Guide

How to connect and use the SparkFun ZX Distance and Gesture Sensor with an Arduino.

LSM303C 6DoF Hookup Guide

A basic guide to get started with the LSM303C 6 Degrees of Freedom Breakout.

Force Sensitive Resistor Hookup Guide

How to hook a force-sensitive resistor up to an Arduino to measure pressure variances.

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

Spectacle Motion Board Hookup Guide

$
0
0

Spectacle Motion Board Hookup Guide a learn.sparkfun.com tutorial

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

Spectacle Motion Board

The Spectacle Motion Board makes it easy to add movement to your Spectacle projects. It can control up to 5 servo motors, either of standard or continuous rotation type.

Spectacle Motion Board

DEV-13993
14.95

tl;dr

  1. The USB Micro B port on the servo board is only for providing power to the attached motors.
  2. A single servo, or a couple of small servos, can be powered over the Spectacle control cable.
  3. Servo motors can be of the standard or continuous rotation type.

Meet the Spectacle Motion Board

Designed to make it easy to add simple motions to your Spectacle projects, the Spectacle Motion Board integrates with the rest of the Spectacle ecosystem to allow you to control motion effects relatively effortlessly.

Motion board IO jacks

It has two 1/8" (3.5mm) jacks for Spectacle control signals. Pay attention to the directionality of the jacks! The one labeled “In” should be plugged into a board that is closer to the Director Board than the Motion Board is, or into the Director Board itself.

Servo headers

The Motion Board supports up to 5 servo motors. The servo motors can be either standard motion or continuous rotation servos. There’s a note on the board (“O/W/Y”) for the color which should be on the top row of the header: orange, white, or yellow. Most servo motors will have one wire which is one of these colors, and that wire should line up with this note.

Micro USB jack

The Motion Board has a Micro B USB connector to allow it to be directly powered by an external power supply. The relatively slender audio cables the Spectacle data travels over are not adequate for the large amount of current drawn by larger servo motors or by multiple motors.

Suggested Reading

Before proceeding, you should read through the Spectacle User’s Guide. It will give you the basics you’ll need to know about how Spectacle works to follow the rest of this tutorial.

The Configuration Utility

Spectacle Motion Board

The Motion Board page in the Utility provides the following options.

Motion Board Actions

There are four actions associated with the Motion Board, all of which should be used with a single trigger pulse type input signal.

Sweep to Position

Toggle position action

This action moves the motor between two positions, one motion on each trigger event.

  • “listen to channel number …” - This is the channel which triggers the action.
  • “control servo number …” - The servo to be controlled, numbered from 0-4.
  • “wait … seconds and move to” - Delay before motion for the first position.
    • slider control - Choose the position for the first motion. The servo starts at 90° on power up and can be rotated to 0° in one direction or to 180° in the other direction. This is equivalent to starting at 12 o'clock and turning to either 9 o'clock or 3 o'clock.
  • “wait … seconds and move to” - Delay before motion for the second position.
    • slider control - Choose the position for the second motion. The servo starts at 90° and can be rotated to 0° in one direction or to 180° in the other direction. This is equivalent to starting at 12 o'clock and turning to either 9 o'clock or 3 o'clock.
Sweep and Return

Sweep and return action options

This action waits for a moment, moves the servo to a position, then waits for a moment at the new position, then moves back to the first position.

  • “listen to channel number …” - Which channel controls this action.
  • “control servo number …” - The servo to be controlled, numbered from 0-4.
  • “wait … seconds and move to” - Delay before motion for the first position.
    • slider control - Choose the position for the first motion. The servo starts at 90° and can be rotated to 0° in one direction or to 180° in the other direction. This is equivalent to starting at 12 o'clock and turning to either 9 o'clock or 3 o'clock.
  • “wait … seconds and move to” - Delay before motion for the second position.
    • slider control - Choose the position for the second motion. The servo starts at 90° and can be rotated to 0° in one direction or to 180° in the other direction. This is equivalent to starting at 12 o'clock and turning to either 9 o'clock or 3 o'clock.
Wagging Effect

Wagging action

This action behaves much like sweep and return, but runs continuously until turned off by receipt of another signal pulse on the designated channel.

  • “listen to channel number …” - Which channel controls this action.
  • “control servo number …” - The servo to be controlled, numbered from 0-4.
  • “wait … seconds and move to” - Delay before motion for the first position.
    • slider control - Choose the position for the first motion. The servo starts at 90° and can be rotated to 0° in one direction or to 180° in the other direction. This is equivalent to starting at 12 o'clock and turning to either 9 o'clock or 3 o'clock.
  • “wait … seconds and move to” - Delay before motion for the second position.
    • slider control - Choose the position for the second motion. The servo starts at 90° and can be rotated to 0° in one direction or to 180° in the other direction. This is equivalent to starting at 12 o'clock and turning to either 9 o'clock or 3 o'clock.
Go to Position

Go to position options

Move the servo motor from where ever it currently is to this new location after some delay.

  • “listen to channel number …” - Which channel controls this action.
  • “control servo number …” - The servo to be controlled, numbered from 0-4.
  • “wait … seconds and move to” - Delay before motion for the first position.
    • slider control - Choose the position for the first motion. The servo starts at 90° and can be rotated to 0° in one direction or to 180° in the other direction. This is equivalent to starting at 12 o'clock and turning to either 9 o'clock or 3 o'clock.

Example Project

Let’s use the Spectacle Motion Board to make a project! We’re going to program the project to move the servo from one position to another and back at regular intervals.

Connect the boards

Start by connecting up the boards. You’ll need the following hardware:

Servo - Generic (Sub-Micro Size)

ROB-09065
8.95
7
Wall Adapter Power Supply - 5.25V DC 2.4A (USB Micro-B)

TOL-13831
7.95
6
Spectacle Director Board

DEV-13912
24.95
Spectacle Motion Board

DEV-13993
14.95
Audio Cable TRRS - 3ft

CAB-14164
2.5

Note that you’ll need two of the TRRS cables.

First, plug one end of one of the TRRS cables into the “Direct” jack on the Director Board.

Cable into direct port

Next, plug a cable into the “Program” jack on the Director Board.

Cable into program jack

Plug the end of this cable into the audio output jack on your phone, tablet, or whatever device you’re using to program the system.

Into the phone audio jack

Plug the other end of the first cable (the one plugged into the “Direct” jack) into the “In” jack on your Motion Board.

alt text

Now, plug the servo connector onto the Motion Board

Servo connection

Finally, plug the Micro B end of the USB cable into the Director Board, and the other end into the wall adapter. Plug the adapter into the wall. You should see one solid light and one blinking light on the Motion Board. On the Director Board, you’ll see one solid light and one light which blinks one time, then pauses, then repeats. This shows that power is present and the boards are up and running.

Setting up the board configuration

When you first open the Spectacle app webpage, this is what you’ll see.

Your project name will differ from mine, as Spectacle assigns a random name to each project.

Blank project page

To continue, we must tell the project which boards we wish to use. Start by clicking the “Add a Board” button at the bottom of the page.

add a board button

This brings up a list of available boards. We’re going to start with a Motion Board and add a Virtual Board later. Click anywhere in the “Motion” box to add it to the project.

List of available boards

Here you can see that the Motion Board has been added to the list of boards in the main window.

Motion board added to list

To add actions to a board, click on the clapboard icon highlighted below.

Add action button

This is the action list, empty. To add an action click the highlighted “Add an Action” button at the bottom of the page.

Empty action list

You’ll be presented with this list of available actions. Select the “Sweep and Return” action.

List of available actions

There are a number of settings needed for the Sweep and Return action. In the image below, you’ll find that I’ve already entered the data needed to drive the servo actions we want for our system.

Sweep and return settings

Click the “Go Back” button at the bottom of the screen to return to the main board list. This will automatically save your work.

Now, click the “Add a Board” button again to bring up the boards list and this time, choose “Virtual”.

Virtual Boards provide a number of functions outside of the normal operation of Spectacle boards. In this case, we want "Periodic Input", which generates a signal at a fixed timing rate.

Here’s the board list with the Virtual Board added to it. Again, click the clapboard icon followed by “Add an Action” to bring up the actions menu.

Boards list with virtual board

Virtual board actions

Here are the options for “Periodic Input”. We tied the action on the Motion Board to channel 0, so we’ll do the same here. We only need a short signal to trigger the Motion Board, so we’ll set it to 0.1 seconds. Finally, we want the motor to activate every 10 seconds.

Again, click the “Go Back” button to return to the main page and save your actions.

Periodic input

Congratulations! You’ve finished the configuration step of the process. Now it’s time to move on to loading the project onto your Director Board.

Finished project

Uploading

Now that you’ve created your Spectacle program it’s time to upload it to the Director Board. If you followed the instructions above, your uploading device is connected to the board and ready to go, so all you need to do is touch the “Install Script” button at the bottom of the page. That will bring up the page seen below.

Upload page

Make sure the volume on your device is turned all the way up, and that no other audio source (music, video, etc) is playing in the background. Then press and hold the “RST” button on the Director Board, press and hold the “PROG” button, then release the “RST” button.

This will put the Director Board into program mode. You’ll see the light on the board blink three times, pause, then repeat. This is your visual indicator that the board is in program mode. Once you’ve established that the board is in program mode, you can begin programming by touching the “Install” button on the Spectacle app screen. The button will gray out during the programming process, which should only last for a few seconds. Once programming is done, you’ll see the light on the Director Board blink 10 times, pause, then repeat. That’s your cue that the program was uploaded successfully.

Press the “RST” button again to reset the system and begin the program!

If you have any troubles, visit the troubleshooting page for help resolving your issues.

Further reading

For general Spectacle information, please check out the user guide:

New!

Spectacle User's Guide

May 4, 2017

The Spectacle system is designed to help those without electronics or programming experience integrate electronics into projects.
New!

Spectacle Motion Board Hookup Guide

All the information you need to use the Spectacle Motion Kit in one place.
New!

Spectacle Light Board Hookup Guide

All the information you need to use the Spectacle Light Board in one place.
New!

Spectacle User's Guide

The Spectacle system is designed to help those without electronics or programming experience integrate electronics into projects.

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

Spectacle User's Guide

$
0
0

Spectacle User's Guide a learn.sparkfun.com tutorial

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

Introduction

Spectacle is a product ecosystem centered around a simple idea: creative people shouldn’t have to learn new skills to use electronics in their projects. You’ve spent years developing the skills you use, and SparkFun wants to recognize that and help you expand your creations to include electronics without requiring you to spend years learning about electronics and programming.

Spectacle family portrait

Spectacle launched with six modules: the Director Board, an Audio Output Board, a Motor Control Board, a Lighting Control Board, an Inertia Sensing Board, and a Button Input Board. Every Spectacle project consists of at least two boards: one Director Board and at least one of the output-type modules.

Director Board

Spectacle Director Board

DEV-13912
24.95

The Director Board controls all the actions in a Spectacle project. Input-type modules report data on their state back to it, and output-type modules receive their marching orders from it.

Audio Output Board

Spectacle Audio Board

DEV-14034
14.95

The Audio Output Board adds the ability to play sounds from a Micro SD card to your Spectacle system. It provides a line-level output ready to be amplified.

Motor Control Board

Spectacle Motion Board

DEV-13993
14.95

The Motor Control Board is made to drive conventional hobby servo motors, either normal type or continuous rotation type. It can be powered via the Director Board connection or via a local input port for higher power servo motors.

Light Board

Spectacle Light Board

DEV-14052
14.95

The Light Board controls strands of addressable LEDs, allowing it to realize quite a few interesting effects that otherwise wouldn’t be possible.

Inertia Sensing Board

Spectacle Inertia Board

DEV-13992
19.95

The Inertia Sensing Board allows you to trigger events on motion, stillness, or orientation.

Button Input Board

Spectacle Button Board

DEV-14044
14.95

The Button Input Board takes its input from all manner of button, switches, or other contact type sensing devices. It has 8 external inputs and one onboard button, allowing for a large number of inputs to a single module.

Spectacle Director Board

The Spectacle Director Board is at the core of all Spectacle systems. It stores the program, connects to and sends power to the other boards in the system, and passes messages between the other boards.

Director Board Hardware Tour

Director Buttons

There are two buttons on the Director Board: one labeled RST and one labeled PROG. These buttons allow you to enter programming mode, so new behaviors can be loaded into your Spectacle system.

To enter programming mode, press and hold the RST button, press and hold the PROG button, and then release the RST button.

Micro USB Jack

Power for your Spectacle system is delivered via a Micro USB jack on the Director Board. Power is then delivered to additional boards in the system via the cables connecting the other boards together, although some boards (such as the Motion Board and the Light Board) may require locally delivered power.

Program Jack

The “Program” jack is where you’ll connect the device you use for programming. A cable connecting this jack to the audio output of your programming device is needed to upload a new set of behaviors to your Spectacle system.

Direct Jack

Other Spectacle boards will be connected to the “Direct” jack. Power is delivered via this jack to the other boards, and power to those boards is disconnected while the RST button is held down.

Spectacle Example

Spectacle actions are mediated by “Channels”, which represent information sent from input modules to output modules by way of the Director Board. More than one board may listen to a single channel, and more than one board may write to a single channel by use of “virtual” boards to combine signals.

An Example

In our simple example, we’ve created a system with only two boards: the Director Board and the Audio Output Board. This simple example is going to play a sound at random intervals, with a minimum of 10 seconds between playback.

Here we see the opening screen of the Spectacle App. The default name (in this case) is “my talented project” but you can, of course, change this to be anything that you’d like. We’ll just leave it as is. Next, we need to add our Audio Output Board to the project. Click the “ADD A BOARD” button at the bottom of the page.

Blank project

You’ll now see a list of the various types of boards which are currently available. We’ve discussed five of these six entries, and we’ll cover what a virtual board is in a second. For now, just click on “Audio” to add our Audio Output Board.

List of available boards

We’re now back at the beginning screen, with the addition of another line below the project info line for a “painstaking sound board”. You can rename this as you please by simply clicking in the text field holding the board’s name.

Main page with a new board

Now click the clapboard icon to bring up a list of actions assigned to the board.

This is the edit button

Unsurprisingly, it’s empty. We have to add something! At the bottom of the page, find the “ADD AN ACTION” button. Click it and a list of actions will descend from the top of the page.

Audio board empty action page

For the Audio Output Board, only two options exist: “Cancel” and “Play Sound”. Click on “Play Sound” to add that action to our actions list.

Audio board action options

You’ll find this screen has appeared. There are four blanks, for four user inputs, and a slider at the bottom which we’re going to ignore. Here are the uses of the other fields.
* “Listen to channel number…” - This is the channel number which triggers the audio to start playing. As long as this channel’s value is above the threshold level (set by that slider that we’re not going to mess with), the sound will repeat playing at a rate determined by the two time intervals specified lower down.
* “wait … seconds and play…” - This is the first delay in the system. By delaying when a sound plays, you can sequence events however you see fit.
* “…and play file number…” - This is where you tell the board which file to play. Remember, when copying the audio files to the Micro SD card, they should be named as 00.ogg, 01.ogg, 02.ogg, etc. The number in this field corresponds to the number in the name of the audio file. If there is no audio file with the corresponding number, no sound will play.
* “do not allow another sound to interrupt until … seconds” - The number in this field should correspond to the length of the audio file. If this value is less than the length of the sound file, another trigger sent to the audio board will interrupt the sound before it finishes. If it is longer than the sound, there will be a period of silence after playback before another playback can be initiated.

Play sound setup page

Here are the settings to put into the fields. Note that we are listening on channel 0, as we’ll need that information later. We want to play our sound immediately, play sound file 00.ogg, and not interrupt that sound for at least one second.

Setting for play sound action

There! We’ve added the instruction to play back a sound. Now we need to tell the system when to play the sound. Click the “GO BACK” button at the bottom of the screen. Don’t worry, the action you added has been saved automatically.

This is the go back button

We’re back at the opening screen again, and you can see that “play sound on channel 0” has been added to the Sound Board’s entry. If we had created more actions, they would show up there, as well. Click the “ADD A BOARD” button to continue.

Audio board in list witih action

We’re back at the list of boards. This time, we’re going to add a virtual board. This special subset of “boards” adds functionality that otherwise isn’t added by any particular hardware board.

List of boards again

Now a virtual board entry appears in our project list. The Virtual Board entry is special, in that it can only exist once in the boards list, and it will always “sink” to the bottom of the list, even if you try to rearrange boards beneath it or if you create boards after the virtual board. Again, click on the clapboard icon to enter the add/edit actions view.

Virtual board in list

When you click on “ADD AN ACTION”, you’ll see a greater variety of options than you did with the Sound Board. The first four allow for input signals from external boards to be combined or changed in some way, while the bottom four require no external hardware to use. Choose “Random Input” from the list.

Virtual board actions

There are only two blanks here: one for channel number, and one for timing. Basically, this action flips a coin every few seconds (how often is determined by the value in the blank) and outputs the result to the channel you set in the blank field. Put ‘0’ in the channel number field and ‘10’ in the “every ___ seconds” field.

Now, click the “GO BACK” button at the bottom of the screen to return to the main menu.

Random output settings

Congratulations! You’ve just finished setting up the configuration for our random sound player!

Start menu with both boards

Programming the system

Programming the system is done via your headphone output jack. Plug one of the included 3.5mm cables into the headphone jack on your computer, smartphone, or tablet, and plug the other end into the “Program” jack on the Director Board.

Supply power to the Director Board via the micro USB jack on the end of the board, then hold down the RST button. Hold down the PROG button, and release the RST button. After a moment, you should see the LED on the board blinking. It should blink three times, pause, blink three times, pause, repeatedly. Turn your system’s volume up all the way, then touch or click the “Install Script” button at the bottom of the screen. That will pull up the page below.

Upload page

Click or touch the “Install” button at the bottom. The button will gray out during the installation process. When it has returned to its normal color, the installation is done. If the installation was successful, you should see the LED on the Director Board blink 10 times, then pause, then 10 times, then pause, etc. Press the RST button on the Director. Again, you’ll see 10 blinks, then a pause on the Director LED. That means the program is loaded and everything is working.

Spectacle Concepts

Momentary versus continuous events

Some events in Spectacle will generate a “one-and-done” pulse, and some will generate a continuous signal. What happens with these signals depends upon what sort of action the signal is connected to.

Example: Inertia board and Sound board

Example configuration 00

Imagine we have system with an inertia board and a sound board, configured as above.

By the settings you can imagine what will happen: a sound will play when the inertia board is moved. But what happens if the inertia board keeps moving? It will continue to send its signal on channel 0, and the sound board will continue to receive it, and two seconds after the sound starts playing (regardless of the actual length of the sound), the sound will play again. This will continue until the inertia board is allowed to stop moving–a continuous output signal.

To play the sound only once, upon the first motion of the inertia board, what should we change? We would change the check box on the “sense motion” action from “while” to “if”.

Example: Button board and Light board

Example 01 configuration

Now let’s look at a momentary example, and how not to use it.

Consider the system described above. One may assume that, when pressed, the flame effect would begin on strip 1 of the light board. And that’s true, it will. However, since the flame effect is a continuous effect (that we want to run indefinitely) and the button press is momentary (it only issues a signal when the button is initially pressed), the effect will be brief–probably so brief as to not even be visible to the user.

So what should we change to get what we want? We have a couple of options, looking at the actions available to the button board:

Button board available actions

Looking over our available choices, “Action while Holding” and “Latch On/Latch Off” sound like they’ll produce a continuous output suitable for triggering our continuous flame effect. Using one of them (depending on whether you want to have to hold the button or just turn it on and off) will get us the behavior we desire.

Troubleshooting

Sometimes things just don’t work out the way we envisioned them working out. Here are some tips for troubleshooting a non-functioning (or malfunctioning) Spectacle project.

Board order is wrong

A limitation of the Spectacle application and system is that the boards must be attached to the Director Board in the same order in which they appear in the application list. This means that a system with a Button Board as the top item in the list and a Sound Board second is different to and incompatible with a Spectacle script which has the Button Board at the bottom. It also means that no Spectacle system can have unused boards in it. All of the boards in the system must be included in the script. It is permissible to have a board in a system with no actions assigned to it, however.

Insufficient power

All Spectacle boards can be powered over the 1/8" (3.5mm) TRRS jack cable which connects them. However, a couple of boards (currently, the Motion and Light boards) have a USB micro B connector on board to provide extra power to the motors or LED strips attached to the board.

How do you know if you need to attach another power supply? Well, the easiest way is to try and see. If your system behaves oddly, or doesn’t work at all, you probably need more power than can be provided by the Director Board and should attach a supply at the output board.

If you are attaching more than 20 LEDs or more than one of the smallest size servos (or any of the larger servo motors), you should power the output board locally.

Configuration failed to install properly

Sometimes, the upload just doesn’t take properly. Usually this is due to the volume on the programming device having been set too low, or to another sound (a notification tone, for instance) playing on the programming device during the configuration installation process.

The solution here is simple: try installing again. If your volume is all the way up, it’s possible that your device can’t make a strong enough signal to work with Spectacle. This may be especially true of cellular phones in the EU, where maximum volume output is limited by statute.

Single LED blink on Director Board at power up

This means the system failed to initialize properly. This can be because the board order is wrong, there’s an extra board in the system, one of the cables isn’t connected firmly, one of the cables has been damaged, or because the installation of the program went badly.

Typically, the best way to fix this is by checking connections and board order, reinstalling the code, and (if possible) swapping out the interboard connection cables with other, known good cables.

Further Reading

Ready to move on with Spectacle? Check out detailed instructions for each board below.

New!

Spectacle Light Board Hookup Guide

All the information you need to use the Spectacle Light Board in one place.
New!

Spectacle Motion Board Hookup Guide

All the information you need to use the Spectacle Motion Kit in one place.

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

Spectacle Light Board Hookup Guide

$
0
0

Spectacle Light Board Hookup Guide a learn.sparkfun.com tutorial

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

Spectacle Light Board

The Spectacle Light Board allows you to add some fairly complex lighting effects to your Spectacle projects. It has connections for up to three strands of addressable LEDs and a connector for external power.

Spectacle Light Board

DEV-14052
14.95

tl;dr

  1. If more than approximately 10 pixels will be on at once, we recommend powering the Light Board through the onboard micro B USB port.
  2. For smaller numbers of pixels, it is possible to power them directly over the Spectacle control cable.
  3. Most of the LED effects want a continuous type signal, such as the Button board “Latch On/Latch Off” function.
  4. Only WS2812 (NeoPixel) type addressable LED strips will work with the Spectacle Light Board.

Meet the Spectacle Light Board

Designed to make it easy to add relatively complex lighting effects to your Spectacle projects, the Spectacle Light Board integrates with the rest of the Spectacle ecosystem to allow you to control lighting effects relatively effortlessly.

It has two 1/8" (3.5mm) jacks for Spectacle control signals. Pay attention to the directionality of the jacks! The one labeled “In” should be plugged into a board that is closer to the Director Board than the Light Board is, or into the Director Board itself.

Signal jacks

The Light Board supports up to three strands of addressable LEDs. Each strand can have up to 60 individual pixels. Not all types of addressable LEDs are compatible with the Spectacle Light Board. If you have questions about whether or not a particular type of LED strip is compatible with the Light Board, contact SparkFun technical support.

LED Strand Connectors

The Light Board has a Micro B USB connector to allow it to be directly powered by an external power supply. The relatively slender audio cables the Spectacle data travels over are not adequate for the large amount of current drawn by more than a few pixels.

USB Power Jack

Suggested Reading

Before proceeding, you should read through the Spectacle User’s Guide. It will give you the basics you’ll need to know about how Spectacle works to follow the rest of this tutorial.

The Configuration Utility

Spectacle Light Board

Action list for light board

The Light board supports 9 different actions. Most of them want a continuous-type signal input, although a couple of them can be used with momentary input signals. We’ll cover the difference under each action. Each action will have a field for the number of pixels the lightstrip that action is being applied to has, the use of which should be fairly apparent, and which we won’t mention again.

Rainbow Effect

Rainbow effect settings

The rainbow effect displays a rainbow of colors across the strip, changing the color of each pixel indvidually to make it appear as though the rainbow is scrolling along the lightstrip.

  • “While channel number … is active” - The rainbow effect persists only while the channel is active, so a continuous input signal is needed.
  • “rainbow scroll lightstrip number …” - Select which lightstrip you wish the rainbow effect to operate on. To have the same effect on multiple lightstrips, you must create multiple actions.
  • scroll speed slider - controls how fast the pattern moves as it scrolls past.

Theater chase

Theater chase settings

Theater chase mode behaves like a marquee light border. The lights will march along making it appear as though the lightstrip is moving in steps.

  • “While channel number … is active” - The theater chase effect persists only while the channel is active, so a continuous input signal is needed.
  • “theater chase lightstrip number …” - Select which lightstrip you wish the theater chase effect to operate on. To have the same effect on multiple lightstrips, you must create multiple actions.
  • chase speed slider - controls how fast the pattern moves as it scrolls past.
  • color picker input - allows you to select the color of the lights.

Scanning effect

Scanning effect settings

Scanning mode sees a small group of lights bouncing back and forth along the length of the lightstrip, reminiscent of Cylons from Battlestar Galactica.

  • “While channel number … is active” - The scanning effect persists only while the channel is active, so a continuous input signal is needed.
  • “scan lightstrip number …” - Select which lightstrip you wish the scanning effect to operate on. To have the same effect on multiple lightstrips, you must create multiple actions.
  • scan speed slider - controls how fast the pattern moves as it scrolls past.
  • color picker input - allows you to select the color of the lights.

Twinkle effect

Twinkle effect settings

Causes individual lights on the selected strip to perform a twinkling action.

  • “While channel number … is active” - The twinkle effect persists only while the channel is active, so a continuous input signal is needed.
  • “twinkle lightstrip number …” - Select which lightstrip you wish the twinkle effect to operate on. To have the same effect on multiple lightstrips, you must create multiple actions.
  • color picker input - allows you to select the color of the lights.
  • speed slider - controls how often the twinkles occur.
  • magic slider - controls how magical the twinkles are. Play with it!

Lightning effect

Lightning effect settings

Causes the entire strip to strobe in a manner that looks a lot like a lightning flash.

  • “While channel number … is active” - The lightning effect persists only while the channel is active, so a continuous input signal is needed.
  • “lightning on lightstrip number …” - Select which lightstrip you wish the lightning effect to operate on. To have the same effect on multiple lightstrips, you must create multiple actions.
  • color picker input - allows you to select the color of the lights.
  • speed slider - controls how often the lightning strike occurs.
  • fury slider - controls how furious the lightning is. Play with it!

Flame effect

Flame effect settings

Causes the entire strip to crackle like a fire.

  • “While channel number … is active” - The flame effect persists only while the channel is active, so a continuous input signal is needed.
  • “make fire on lightstrip number …” - Select which lightstrip you wish the flame effect to operate on. To have the same effect on multiple lightstrips, you must create multiple actions.
  • color picker input - allows you to select the color of the lights. Experiment with different colors!

Fade effect

Fade effect settings

The lightstrip will change from one color to another over time, then back to the first.

  • “While channel number … is active” - The fade effect persists only while the channel is active, so a continuous input signal is needed.
  • “fade lightstrip number … back and forth” - Select which lightstrip you wish the fade effect to operate on. To have the same effect on multiple lightstrips, you must create multiple actions.
  • “from color” color picker - This is the initial color that the lightstrip will power up with.
  • “to color” color picker - The other color, which the strip fades to and from periodically.
  • “fade speed” slider - Controls how fast the fading action occurs.

Fill

Fill settings

Fills some number of lights on the light strip with a single color. Blanks the other lights to off.

  • “listen to channel number …” - A momentary signal on this channel is all that is needed to trigger a fill operation, and the fill will persist until another effect starts.
  • “wait for … seconds” - This delay allows for sequencing effects. Most often you’ll probably set it to 0.
  • “clear lightstrip number …” - Select the lightstrip to operate upon.
  • “and fill … pixels” - The number of pixels, from closest to the Light board out, to turn on.

Light pixel

Pixel settings

Turns on one light and blanks the rest of the lights to off.

  • “listen to channel number …” - A momentary signal on this channel is all that is needed to trigger a light pixel operation, and the lit pixel will persist until another effect starts.
  • “wait for … seconds” - This delay allows for sequencing effects. Most often you’ll probably set it to 0.
  • “clear lightstrip number …” - Select the lightstrip to operate upon.
  • “and light pixel number … ” - The number of the pixel, from closest to the Light board out, to turn on.

Example Project

Let’s use the Spectacle Light Board to put together a working project! We’re going to use a “virtual board” to blink a lightstrip attached to the Light Board.

Connect the boards

To follow along with this tutorial, you’ll need the following hardware:

Wall Adapter Power Supply - 5.25V DC 2.4A (USB Micro-B)

TOL-13831
7.95
6
LED RGB Strip - Addressable, Bare (1m)

COM-12025
19.95
7
Spectacle Director Board

DEV-13912
24.95
Spectacle Light Board

DEV-14052
14.95
JST to JST-SM Wire - 1ft

CAB-14165
1.95

Note that you will need two of the TRRS cables!

First, plug one end of one of the TRRS cables into the “Direct” jack on the Director Board.

The direct jack

Next, take the other TRRS cable and plug it into the “Program” jack on the Director Board.

The program jack

Take the other end of this cable and plug it into the audio jack of the phone, tablet, or computer that you’ll be using to program the system.

Into the phone jack

Now, plug the free end of the first cable into the “In” jack on the Light Board. Pay attention to which jack you plug into, as the two jacks are directional.

Light board input jack

Next, you’ll need the JST-SM to JST-PH adapter cable. Plug the white end into connector position 0 on the Light Board.

Adapter into light board

Plug the black end of the adapter into the mating connector on the light strip.

Adapter into light strip

Finally, plug the Micro B end of the power adapter into the Director Board, and the other end into the wall. You should see one solid light and one blinking light on the Light Board. On the Director Board, you’ll see one solid light and one light which blinks one time, then pauses, then repeats. This shows that power is present and the boards are up and running.

Setting up the board configuration

Blank project page

When you first open the Spectacle app webpage, this is what you’ll see. Your project name will differ from mine, as Spectacle assigns a random name to each project.

add a board button

To continue, we must tell the project which boards we wish to use. Start by clicking the “Add a board” button at the bottom of the page.

List of available boards

This will bring up a list of the available boards. Click anywhere in the “Lights” box to add a Light Board to the system.

Light board edit button

Now that you’ve added the Light Board, it’s time to add the actions to the light board. To get a blink effect, we’re going to trigger two events on one signal, and make one delayed slightly. Click the clapboard icon as highlighted in the above picture to bring up the list of actions assigned to that board.

No actions assigned

Naturally, there are no actions in the list, since we haven’t added any yet. Click the “Add an Action” button at the bottom of the screen to bring up a list of available actions.

Actions list for light board

Here’s the list of Light Board actions that will pop up when you hit the “Add an Action” button. We want to add an action of the “Fill Color” type, so click on that entry.

alt text

Here’s the “Fill Color” action list of options. See the previous page of the tutorial for information about the various fields.

Fill with settings in place

Fill in the blanks of the page as seen above. This sets up the strip to turn on to solid white when an event hits channel 0. Now, add another “Fill Color” type action and scroll down so it’s completely visible.

settings for second fill page

Once you’ve added the second “Fill Color” action, set the fields as shown above. This will cause it to trigger on the same action as the first fill, but it won’t activate for two seconds. Then, it will set all the lights on the strip to “black” (off).

Go back button

Click the “Go Back” button to return to the main screen. Clicking this button automatically saves your work, as well.

Now, repeat the steps from above to add a Virtual Board. Click the clapboard icon to edit the list of actions for the Virtual Board.

Virtual Boards provide a number of functions outside of the normal operation of Spectacle boards. In this case, we want "Periodic Input", which generates a signal at a fixed timing rate.

list of Virtual Board actions

Here are the actions we can use with a Virtual Board. We want a “Periodic Input”, to create our blinking action.

Periodic settings

You should set up the periodic action to match the settings above. This will generate a short pulse every 10 seconds. Now click “Go Back” again to return to the main page.

Finished project

Congratulations! You’ve finished the configuration step of the process. Now it’s time to move on to loading the project onto your Director Board.

Uploading

Now that you’ve created your Spectacle program it’s time to upload it to the Director Board. If you followed the instructions above, your uploading device is connected to the board and ready to go, so all you need to do is touch the “Install Script” button at the bottom of the page. That will bring up the page seen below.

Upload page

Make sure the volume on your device is turned all the way up, and that no other audio source (music, video, etc) is playing in the background. Then press and hold the “RST” button on the Director Board, press and hold the “PROG” button, then release the “RST” button.

This will put the Director Board into program mode. You’ll see the light on the board blink three times, pause, then repeat. This is your visual indicator that the board is in program mode. Once you’ve established that the board is in program mode, you can begin programming by touching the “Install” button on the Spectacle app screen. The button will gray out during the programming process, which should only last for a few seconds. Once programming is done, you’ll see the light on the Director Board blink 10 times, pause, then repeat. That’s your cue that the program was uploaded successfully.

Press the “RST” button again to reset the system and begin the program!

If you have any troubles, visit the troubleshooting page for help resolving your issues.

Further reading

For general Spectacle information, please check out the user guide:

New!

Spectacle User's Guide

May 4, 2017

The Spectacle system is designed to help those without electronics or programming experience integrate electronics into projects.
New!

Spectacle Motion Board Hookup Guide

All the information you need to use the Spectacle Motion Kit in one place.
New!

Spectacle Light Board Hookup Guide

All the information you need to use the Spectacle Light Board in one place.
New!

Spectacle User's Guide

The Spectacle system is designed to help those without electronics or programming experience integrate electronics into projects.

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


Spectacle Button Board Hookup Guide

$
0
0

Spectacle Button Board Hookup Guide a learn.sparkfun.com tutorial

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

Spectacle Button Board

The Spectacle Button Board allows you to add input from buttons or switches to your Spectacle projects. It has a total of 9 signal inputs, eight of which can come from external buttons and one button directly on the board.

Spectacle Button Board

DEV-14044
14.95

tl;dr

  1. Buttons or switches can be connected to the board by pushing wires into the “poke home” type connectors on the board.
  2. Up to nine signals are available.
  3. Button signals can be either momentary or continuous.

Meet the Spectacle Button Board

Designed to bring simple signals from the world into your Spectacle projects, the Spectacle Button Board provides input for any of your Spectacle projects.

It has two 1/8" (3.5mm) jacks for connecting to other boards in a Spectacle system. Note that the Spectacle data jacks are directional: the one marked “In” should be plugged into the “upstream” board (i.e., closer to the Director Board than this one) and the one marked “Out” connects to the next downstream board.

Audio jacks

There are 8 “poke home” connectors on the Button Board. Each one can be connected to one (or more) buttons. To add a connection, simply push the stripped end of a wire into the hole on the connector. The connector will automatically grab on and hold the wire in place. If you need to remove the wire later, an small object (bobby pin, ballpoint pen, etc.) can be used to depress the release button, allowing the wire to be extracted without damage.

Poke home connectors

There is an input button on the button board itself which can be used to provide an input signal if no other buttons are available. It functions like any other normal button that might be attached. Be certain you’re pressing the button labeled ‘8’ and not the one labeled ‘Reset’! Pressing the reset button will reset your button board, probably causing your entire system to stop working properly until you reset your Director Board!

Onboard Button 8

Suggested Reading

Before proceeding, you should read through the Spectacle User’s Guide. It will give you the basics you’ll need to know about how Spectacle works to follow the rest of this tutorial.

The Configuration Utility

Spectacle Button Board

Button board action options

For the Button board, there are five options: three which produce a momentary pulse type output and two that produce a continuous switch type output.

Action on press

Action on press options

Trigger an action when a button is first pressed, regardless of how long it is subsequently held down.

  • “When button number … is pressed” - This is the number of the button we wish to assign to this action. The button numbers are printed on the board, and run from 0 through 8.
  • “trigger channel number …” - A single, momentary pulse will be sent out on this channel. It is suitable for starting a sound, initiating a motion, or setting the color of a light strip. It is not suitable for continuous sound playback or for turning on a light strip effect, for instance.
Action on release

action on release options

Trigger an action when a button is released, regardless of how long it has been held down prior to being released.

  • “When button number … is released” - This is the number of the button we wish to assign to this action. The button numbers are printed on the board, and run from 0 through 8.
  • “trigger channel number …” - A single, momentary pulse will be sent out on this channel. It is suitable for starting a sound, initiating a motion, or setting the color of a light strip, but not for continuous sound playback or for turning on a light strip effect, for instance.
Action on press or release

Action on press or release options

Trigger an action when a button is pressed, then trigger the same action again when the button is released.

  • “When button number … is either pressed or released” - This is the number of the button we wish to assign to this action. The button numbers are printed on the board, and run from 0 through 8.
  • “trigger channel number …” - A single, momentary pulse will be sent out on this channel both at the time the button is pressed and at the time it is released. It is suitable for starting a sound, initiating a motion, or setting the color of a light strip, but not for continuous sound playback or for turning on a light strip effect, for instance.
Action while holding

Action while holding options

Trigger an event as soon as a button is pressed, then continue to trigger that event as long as the button is held down.

  • “While button number … is pressed” - This is the number of the button we wish to assign to this action. The button numbers are printed on the board, and run from 0 through 8.
  • “activate channel number …” - A continuous signal will be sent out on this channel. It is suitable for triggering and repeating a sound, or for turning on and keeping on (at least, while the button is held) a lighting effect.
Latch On/Latch Off

Latch On/Off options

This action is like a latching power switch. One press turns the signal on, another later press turns the signal off.

  • “While button number … is pressed” - This is the number of the button we wish to assign to this action. The button numbers are printed on the board, and run from 0 through 8.
  • “activate channel number … until button is pressed again” - A continuous will be sent out on this channel. It is suitable for triggering and repeating a sound, or for turning on and keeping on a lighting effect.

Example Project

Let’s use the Spectacle Button Board to make a project! Obviously, we need to have some kind of output board as well, so we’ll use a Light Board. The project will use the button board to turn the Light Board’s Scanning Effect on and off.

Connect the boards

For this tutorial, you’ll need the following products:

Wall Adapter Power Supply - 5.25V DC 2.4A (USB Micro-B)

TOL-13831
7.95
6
LED RGB Strip - Addressable, Bare (1m)

COM-12025
19.95
7
Spectacle Director Board

DEV-13912
24.95
Spectacle Light Board

DEV-14052
14.95
Audio Cable TRRS - 3ft

CAB-14164
2.5
JST to JST-SM Wire - 1ft

CAB-14165
1.95

You will need three of the TRRS cables!

First, plug one end of one of the TRRS cables into the “Direct” jack on the Director Board.

The direct jack

Next, take the other TRRS cable and plug it into the “Program” jack on the Director Board.

The program jack

Take the other end of this cable and plug it into the audio jack of the phone, tablet, or computer that you’ll be using to program the system.

Into the phone jack

Then take the other end of the first TRRS cable and plug it into the “In” jack on the Button Board.

Cable into button board in jack

Grab another of the TRRS cables and plug it into the “Out” jack on the Button Board.

Cable into out on button board

Plug the other end of that cable into the “In” jack on your Light Board.

Cable into IN jack on light board

Now plug your lightstrip adapter cable into the Light Board…

Light strip adapter into light board

…and plug the lightstrip into the other end of that adapter.

light strip adapter into light strip

Finally, plug the Micro B end of the power adapter into the Director Board, and the other end into the wall. You should see one solid light and one blinking light on the Light board and the Button board. On the Director Board, you’ll see one solid light and one light which blinks eight times, then pauses, then repeats. This shows that power is present and the boards are up and running.

Setting up the board configuration

When you first open the Spectacle app webpage, this is what you’ll see. Your project name will differ from mine, as Spectacle assigns a random name to each project.

Blank project page

To continue, we must tell the project which boards we wish to use. Start by clicking the “Add a Board” button at the bottom of the page.

add a board button

This will bring up a list of the available boards. We’re going to add our Button Board first of all, so click anywhere in the “Button” box to add it.

Now, repeat this process one more time to add a Light Board.

List of available boards

You should now have a list that looks like this. Order is important, so make sure your boards are in the same order as shown above. Names are not important, however, and your boards will have different names than mine do, as Spectacle assigns names randomly.

All boards in list

Each board has a clapboard icon associated with it. To add or edit actions, click this icon. We’re going to start by adding an action to the Button Board.

Edit buttons highlighted

The window that pops up will look like the image below. Click the button highlighted in the image below to add an action to the Button Board.

Add an action button

This list will come up. It represents all the different actions which can be performed by a Button Board.

Click on the list entry which says “Latch On/Latch Off”.

Action list for button board

You’ll then see this screen, which presents the various options for the Latch On/Latch Off action. Every action will have different settings.

latch on latch off options

Here are the settings we need to use for this project. We want button 8 (the button on the Button Board) to activate channel 0 when pressed. Later on, we’ll tell our Light Board to watch channel 0 and do something when it’s active.

Latch mode button options

Now click on the “Go Back” button to return to the main page. Your action changes will be saved automatically.

Go back button

We’re back at the main page, now, and you can see that the action we added appears under the Button Board in the boards list. Now click on the clapboard icon for the Light Board to add an action for the button to trigger.

Main page with both boards

When you click the “Add an Action” button, you’ll be presented with this list of actions that the Light Board can perform. We’re going to choose the “Scanning Effect” action.

Light board action options

This screen will pop up, albeit without any of the entries in the fields. Go ahead and set up the fields as I’ve shown them below, then click the “Go Back” button.

Scan action settings

Congratulations! You’ve finished the configuration step of the process. Now it’s time to move on to loading the project onto your Director Board.

Project, completed

Uploading

Now that you’ve created your Spectacle program it’s time to upload it to the Director Board. If you followed the instructions above, your uploading device is connected to the board and ready to go, so all you need to do is touch the “Install Script” button at the bottom of the page. That will bring up the page seen below.

Upload page

Make sure the volume on your device is turned all the way up, and that no other audio source (music, video, etc) is playing in the background. Then press and hold the “RST” button on the Director Board, press and hold the “PROG” button, then release the “RST” button.

This will put the Director Board into program mode. You’ll see the light on the board blink three times, pause, then repeat. This is your visual indicator that the board is in program mode. Once you’ve established that the board is in program mode, you can begin programming by touching the “Install” button on the Spectacle app screen. The button will gray out during the programming process, which should only last for a few seconds. Once programming is done, you’ll see the light on the Director Board blink 10 times, pause, then repeat. That’s your cue that the program was uploaded successfully.

Press the “RST” button again to reset the system and begin the program!

If you have any troubles, visit the troubleshooting page for help resolving your issues.

Further reading

For general Spectacle information, please check out the user guide:

New!

Spectacle User's Guide

May 4, 2017

The Spectacle system is designed to help those without electronics or programming experience integrate electronics into projects.

For more Spectacle fun, check out the additional tutorials below:

New!

Spectacle Audio Board Hookup Guide

All the information you need to use the Spectacle Audio Board in one place.
New!

Spectacle Sound Kit Hookup Guide

All the information you need to use the Spectacle Sound Kit in one place.
New!

Spectacle User's Guide

The Spectacle system is designed to help those without electronics or programming experience integrate electronics into projects.
New!

Spectacle Light Board Hookup Guide

All the information you need to use the Spectacle Light Board in one place.
New!

Spectacle Example: Super Mario Bros. Diorama

A study in building an animated diorama (with sound!) using Spectacle electronics.
New!

Spectacle Motion Kit Hookup Guide

All the information you need to use the Spectacle Motion Kit in one place.
New!

Spectacle Motion Board Hookup Guide

All the information you need to use the Spectacle Motion Kit in one place.
New!

Spectacle Light and Sound Kit Hookup Guide

All the information you need to use the Spectacle Light and Sound Kit in one place.

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

Spectacle Sound Kit Hookup Guide

$
0
0

Spectacle Sound Kit Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The Spectacle Sound Kit contains everything you need to make a button-triggered sound-playback project.

Spectacle Sound Kit

KIT-14172
99.95

Suggested Reading

Before proceeding, you should read through the Spectacle User’s Guide. It will give you the basics you’ll need to know about how Spectacle works to follow the rest of this tutorial.

Spectacle Audio Board

The Spectacle Audio Board allows you to add sound to your Spectacle projects. It accepts a microSD card with sounds in .ogg format (more on this later), and has a 1/8" (3.5mm) audio jack to connect to external amplifiers.

Spectacle Audio Board

DEV-14034
14.95

tl;dr

  1. Audio files for Spectacle should be formatted as .ogg files.
  2. Audio files should have names 00.ogg, 01.ogg, 02.ogg, etc.
  3. The audio jack on the Audio Board produces output suitable for amplification only. It is not suited to headphones or unpowered speakers.

Meet the Spectacle Audio Board

Designed to be a low-cost and easy to use method of adding sound to projects, the Spectacle Audio Board integrates with the rest of the Spectacle ecosystem to provide sound effects on demand.

It has three 1/8" (3.5mm) jacks: two for Spectacle control signals and one for the audio output. Be certain you are plugging cables into the right jacks! Plugging an audio device into one of the Spectacle jacks could cause damage to the audio device. Note that the Spectacle data jacks are directional: the one marked “In” should be plugged into the “upstream” board (i.e., closer to the Director Board than this one) and the one marked “Out” connects to the next downstream board. The “Out” jack is not for audio signals.

Spectacle IO jacks

The audio output is designed for amplified devices only. This means that any attempt to use the Spectacle Audio Board with headphones or unamplified speakers will fail to produce audible output. SparkFun sells a small, amplified, rechargeable speaker which is specifically intended for use with the Spectacle Audio Board.

Audio jack

The Spectacle Audio Board uses a Micro SD card to store the audio files to be played. The files should be stored as .ogg Vorbis encoded files. This free audio file format can be played and created on any type of computer. Later in the tutorial we’ll show you how to convert from MP3, WAV, or other file formats to the .ogg format.

SD Card Slot

The files must be named by number, which is how they will be referred to from within the configuration application. Filename examples are 00.ogg, 01.ogg, 02.ogg, and so forth.

Spectacle Button Board

The Spectacle Button Board allows you to add input from buttons or switches to your Spectacle projects. It has a total of 9 signal inputs, eight of which can come from external buttons and one button directly on the board.

Spectacle Button Board

DEV-14044
14.95

tl;dr

  1. Buttons or switches can be connected to the board by pushing wires into the “poke home” type connectors on the board.
  2. Up to nine signals are available.
  3. Button signals can be either momentary or continuous.

Meet the Spectacle Button Board

Designed to bring simple signals from the world into your Spectacle projects, the Spectacle Button Board provides input for any of your Spectacle projects.

It has two 1/8" (3.5mm) jacks for connecting to other boards in a Spectacle system. Note that the Spectacle data jacks are directional: the one marked “In” should be plugged into the “upstream” board (i.e., closer to the Director Board than this one) and the one marked “Out” connects to the next downstream board.

Audio jacks

There are 8 “poke home” connectors on the Button Board. Each one can be connected to one (or more) buttons. To add a connection, simply push the stripped end of a wire into the hole on the connector. The connector will automatically grab on and hold the wire in place. If you need to remove the wire later, an small object (bobby pin, ballpoint pen, etc.) can be used to depress the release button, allowing the wire to be extracted without damage.

Poke home connectors

There is an input button on the button board itself which can be used to provide an input signal if no other buttons are available. It functions like any other normal button that might be attached. Be certain you’re pressing the button labeled ‘8’ and not the one labeled ‘Reset’! Pressing the reset button will reset your button board, probably causing your entire system to stop working properly until you reset your Director Board!

Onboard Button 8

The Configuration Utility

Spectacle Sound Board

Sound interface

The Spectacle Audio Board only supports one action: Play Sound. As you can see above, there are a number of settings associated with this action.

  • “Listen to channel number…” - This is the channel number which triggers the audio to start playing. As long as this channel’s value is above the threshold level (see below), the sound will repeat playing at a rate determined by the two time intervals specified lower down.
  • “wait … seconds and play…” - This is the first delay in the system. By delaying when a sound plays, you can sequence events however you see fit.
  • “…and play file number…” - This is where you tell the board which file to play. Remember, when copying the audio files to the Micro SD card, they should be named as 00.ogg, 01.ogg, 02.ogg, etc. The number in this field corresponds to the number in the name of the audio file. If there is no audio file with the corresponding number, no sound will play.
  • “do not allow another sound to interrupt until … seconds” - The number in this field should correspond to the length of the audio file. If this value is less than the length of the sound file, another trigger sent to the audio board will interrupt the sound before it finishes. If it is longer than the sound, there will be a period of silence after playback before another playback can be initiated.
  • “activation threshold” - As it says in the app, most of the time you don’t need to adjust this. By tweaking this, you can set the angle at which the Spectacle Accelerometer Board triggers a sound, or the frequency with which a Random Trigger Virtual Board causes a sound to play.

Spectacle Button Board

Button board action options

For the Button board, there are five options: three which produce a momentary pulse type output and two that produce a continuous switch type output.

Action on press

Action on press options

Trigger an action when a button is first pressed, regardless of how long it is subsequently held down.

  • “When button number … is pressed” - This is the number of the button we wish to assign to this action. The button numbers are printed on the board, and run from 0 through 8.
  • “trigger channel number …” - A single, momentary pulse will be sent out on this channel. It is suitable for starting a sound, initiating a motion, or setting the color of a light strip, but not for continuous sound playback or for turning on a light strip effect, for instance.
Action on release

action on release options

Trigger an action when a button is released, regardless of how long it has been held down prior to being released.

  • “When button number … is released” - This is the number of the button we wish to assign to this action. The button numbers are printed on the board, and run from 0 through 8.
  • “trigger channel number …” - A single, momentary pulse will be sent out on this channel. It is suitable for starting a sound, initiating a motion, or setting the color of a light strip, but not for continuous sound playback or for turning on a light strip effect, for instance.
Action on press or release

Action on press or release options

Trigger an action when a button is pressed, then trigger the same action again when the button is released.

  • “When button number … is either pressed or released” - This is the number of the button we wish to assign to this action. The button numbers are printed on the board, and run from 0 through 8.
  • “trigger channel number …” - A single, momentary pulse will be sent out on this channel both at the time the button is pressed and at the time it is released. It is suitable for starting a sound, initiating a motion, or setting the color of a light strip, but not for continuous sound playback or for turning on a light strip effect, for instance.
Action while holding

Action while holding options

Trigger an event as soon as a button is pressed, then continue to trigger that event as long as the button is held down.

  • “While button number … is pressed” - This is the number of the button we wish to assign to this action. The button numbers are printed on the board, and run from 0 through 8.
  • “activate channel number …” - A continuous will be sent out on this channel. It is suitable for triggering and repeating a sound, or for turning on and keeping on (at least, while the button is held) a lighting effect.
Latch On/Latch Off

Latch On/Off options

This action is like a latching power switch. One press turns the signal on, another later press turns the signal off.

  • “While button number … is pressed” - This is the number of the button we wish to assign to this action. The button numbers are printed on the board, and run from 0 through 8.
  • “activate channel number … until button is pressed again” - A continuous will be sent out on this channel. It is suitable for triggering and repeating a sound, or for turning on and keeping on a lighting effect.

Converting Sounds to OGG Vorbis Format

The files used by the Spectacle Audio Board must be in OGG Vorbis format. This free, lossy codec has a higher compression ratio than MP3, and, more importantly, can be used without paying a licensing fee to any third part organization.

Download and Install Audacity

We’ll be using the free, open source program “Audacity” to convert from whatever your file’s current format is to OGG Vorbis.

Audacity website

Audacity is available across all three major operating systems, so you shouldn’t have any trouble getting it installed.

When you start Audacity, you’ll see this screen, or one very like it. While at first blush it seems extremely complex, none of this crap is important to us, so don’t panic.

Audacity main screen

Load a file

Like most programs, “loading a file” just means selecting “Open” from the File menu and choosing which file you wish to convert. Audacity is capable of editing most types of audio files: WAV, AIFF, FLAC, MP3, and others.

Audacity file menu

By default, Audacity shows all files, not just compatible audio files, when you bring up the open dialog. There’s a dropdown menu that allows you to change that so it shows only compatible audio files along the bottom edge of the window.

Audacity open file dialog

Once you select which file you wish to edit, a rather alarmist message may pop up warning you about editing files without making a copy of them. Just click “OK”.

Audacity edit file warning

You’ll see, then, something like this show up. This is what your audio file looks like, to the computer. Again, don’t panic! Unless you want to edit the sound in some way (which we don’t), none of the settings or pieces of information that have popped up here matter to us.

Audacity with open file

Convert to OGG

Now that you have the file loaded, you need to convert it to OGG Vorbis format. To do so, open the “File” menu and select the “Export Audio…” menu item about halfway down. A familiar looking save window should pop up.

Export command in file menu

Right below the “File name:” field you’ll see a drop-down menus labeled “Save as type:”. Select “Ogg Vorbis Files” in that drop down.

A slider will appear at the bottom of the window. The default value of ‘5’ is probably good enough for most purposes. Click “Save” and another window will pop up.

Export audio frame

This one allows you to set metadata about the file. You can ignore everything and just click “OK” to skip past this.

Congratulations! You’ve successfully converted a file to OGG Vorbis format. You may now copy that file to the Micro SD card (don’t forget to rename it to a number!) for use with the Spectacle Audio Board.

Set metadata window

Extra credit- trimming the fat and making the sound louder

As you can see in my file above, there’s a great deal of room between the extents of the sound and the extents of the window. In the time (horizontal) axis, this manifests as flat lines before and after the content of the sound file. In the “loudness” (vertical) axis, this manifests as space between the top and bottom of the waveform file and the top and bottom of the playback position window.

File open in Audacity

Let’s eliminate some of that dead time before and after the sound plays. To do so, simply click inside the playback position window and drag, as though you are trying to select a section of text. The part you’ve selected will be highlighted, as above. Now, just hit the “Delete” key on your keyboard, and that section will be removed. Repeat the process at the other end of the sound.

Extra dead time highlighted

Now, let’s see what we can do about volume. Under the “Edit” menu, look for the “Select” submenu, and choose “All” to select the entire sound. You can also just use the drag-and-highlight method from above.

Finding the "Select All" menu option

Now that you’ve got the entire sound selected, click on the “Effect” menu and select the “Amplify…” option.

Effects menu

A new window will pop up with a slider, a couple of text boxes, and one checkbox. The slider will be pre-positioned to amplify the sound as much as possible without “clipping” it. “Clipping” occurs when you try to amplify a sound more than the system you’re playing it through can stand, and it results in a sort of grating buzzing noise during playback.

Amplify dialog box

You have a choice, now: you can either accept the system’s suggested level, or you can click on the “Allow Clipping” check box and increase the amplification more with the slider. I’ve chosen to accept the clipping limitation for the image above; comparing it to the image of the file higher up, you can see how I’ve trimmed the dead time at the ends and increased the amplitude vertically.

Why would you want to allow your sound to clip? Well, first of all, the preset amplification only takes into account the peak value of your sound, so if one small section of the audio is allowed to clip, it may allow the vast majority of the sound to be substantially louder. Secondly, if you’re playback device is of relatively poor quality, or the sound file itself is, allowing clipping may increase volume significantly without making the sound quality too much worse than it already is. Thirdly, volume intensity may be far more important than sound quality, and allowing clipping lets you push the volume as high as you can.

Edited sound

Now that you’ve successfully edited the sound, export it to OGG Vorbis as we covered above.

Example Project

Let’s use the contents of the Spectacle Sound Kit to put together a working project!

Connect the boards

All of the required hardware for this tutorial is included in the kit.

Start by connecting up the boards. You’ll need the included TRRS audio cables, the power supply, and the small, rechargeable speaker. Make sure the speaker is charged before the first time you try to use it!

First, plug one end of one of the TRRS cables into the “Direct” jack on the Director Board.

The direct jack

Next, take the other TRRS cable and plug it into the “Program” jack on the Director Board.

The program jack

Take the other end of this cable and plug it into the audio jack of the phone, tablet, or computer that you’ll be using to program the system.

Into the phone jack

Then take the other end of the first TRRS cable (the one connected to the “Direct” jack on the Director Board) and plug it into the “In” jack on the Button board.

Connecting the button board

Grab another of the TRRS cables and plug it into the “Out” jack on the button board.

Connecting to the output of the button board

Plug the other end of that cable into the “In” jack on your Audio board.

Connecting to the input of the Audio board

Now plug the speaker into the “Audio Out” jack on the Audio board.

Connecting the speaker

You can now insert the micro SD card into the slot on the back of the board.

Inserting the sd card

Finally, plug the Micro B end of the power adapter into the Director board, and the other end into the wall. You should see one solid light and one blinking light on both the Audio board and the Button board. On the Director board, you’ll see one solid light and one light which blinks eight times, then pauses, then repeats. This shows that power is present and the boards are up and running.

Setting up the board configuration

We’re going to assume that you followed the instructions on the previous page about converting sounds to OGG Vorbis format, and that there is a sound on the Micro SD card inserted into the Sound board named “00.ogg”. If this is not the case, take a few minutes to go back to that page and prepare a sound.

Here’s a new project in the spectacle app screen. Feel free to rename yours (it will have a different default name than the example does), as the name of the project has no effect on the rest of the process.

Bare new project window

Click the button highlighted below to add a board to our system’s configuration.

Add board button

Click anywhere in the “Button” box in the list that pops up to add a Button Board to your project. Now, repeat the process and click in the “Audio” box to add an Audio Board to your project.

List of available boards

You’ll be back to the main page, then, but there will be a couple of new lines present: one for the Button Board and one for the Audio Board.

Main page, showing boards added

To edit the actions assigned to these boards, click on the clapboard icon in the row of the board you wish to edit. We’ll start by editing the Button Board’s actions.

Board edit highlight buttons

Any time you bring up a new board to add actions, you’ll see the same screen as below. To add an action, click the “Add An Action” button in the center bottom of the frame.

Blank add an action page

This will present you with a list of actions that the current board is capable of implementing. In the case of the button board, there are five different options. Click on the first one, “Action on Press”.

Options for button board actions

You’ll now see the window as above. Put a ‘0’ in the two fields indicated, causing a trigger pulse to be sent out on channel 0 whenever button 0 is pressed. Then click the “Go Back” button at the bottom of the page to save the action and return to the main page.

Setting up the button board action

Back on the main page, you can see that the action you added is visible on the Button Board’s row in the window. Let’s edit the actions for the Sound board next.

Main page with button action in place

There’s only one option for actions for the Audio Board, and that’s “Play Sound”. Once you’ve clicked through to the configuration window for “Play Sound”, you’ll see a page like this. Fill in the blanks as shown above, then click the “Go Back” button again.

Sound board action setup

You’ll be back on the main page, now, and you’ll see the actions you’ve added under each of the lines in the project. It’s time to upload the configuration to your hardware!

Main page with all boards and actions in place

Uploading

Now that you’ve created your Spectacle program it’s time to upload it to the Director Board. If you followed the instructions above, your uploading device is connected to the board and ready to go, so all you need to do is touch the “Install Script” button at the bottom of the page. That will bring up the page seen below.

Upload page

Make sure the volume on your device is turned all the way up, and that no other audio source (music, video, etc) is playing in the background. Then press and hold the “RST” button on the Director Board, press and hold the “PROG” button, then release the “RST” button.

This will put the Director Board into program mode. You’ll see the light on the board blink three times, pause, then repeat. This is your visual indicator that the board is in program mode. Once you’ve established that the board is in program mode, you can begin programming by touching the “Install” button on the Spectacle app screen. The button will gray out during the programming process, which should only last for a few seconds. Once programming is done, you’ll see the light on the Director Board blink 10 times, pause, then repeat. That’s your cue that the program was uploaded successfully.

Press the “RST” button again to reset the system and begin the program!

If you have any troubles, visit the troubleshooting page for help resolving your issues.

Further Reading

For general Spectacle information, please check out the user guide:

New!

Spectacle User's Guide

May 4, 2017

The Spectacle system is designed to help those without electronics or programming experience integrate electronics into projects.

For more Spectacle fun, check out the additional tutorials below:

New!

Spectacle User's Guide

The Spectacle system is designed to help those without electronics or programming experience integrate electronics into projects.
New!

Spectacle Light Board Hookup Guide

All the information you need to use the Spectacle Light Board in one place.
New!

Spectacle Inertia Board Hookup Guide

Everything you need to know about using the Spectacle Inertia Board in one place.
New!

Spectacle Example: Super Mario Bros. Diorama

A study in building an animated diorama (with sound!) using Spectacle electronics.
New!

Spectacle Motion Kit Hookup Guide

All the information you need to use the Spectacle Motion Kit in one place.
New!

Spectacle Motion Board Hookup Guide

All the information you need to use the Spectacle Motion Kit in one place.
New!

Spectacle Button Board Hookup Guide

All the information you need to use the Spectacle Button Board in one place.
New!

Spectacle Light and Sound Kit Hookup Guide

All the information you need to use the Spectacle Light and Sound Kit in one place.

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

Spectacle Light Kit Hookup Guide

$
0
0

Spectacle Light Kit Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The Spectacle Light Kit makes it easy to illuminate your next project at the push of a button!

Spectacle Light Kit

KIT-14170
99.95

Suggested Reading

Before proceeding, you should read through the Spectacle User’s Guide. It will give you the basics you’ll need to know about how Spectacle works to follow the rest of this tutorial.

Spectacle Light Board

The Spectacle Light Board allows you to add some fairly complex lighting effects to your Spectacle projects. It has connections for up to three strands of addressable LEDs and a connector for external power.

Spectacle Light Board

DEV-14052
14.95

tl;dr

  1. If more than approximately 10 pixels will be on at once, we recommend powering the Light Board through the onboard micro B USB port.
  2. For smaller numbers of pixels, it is possible to power them directly over the Spectacle control cable.
  3. Most of the LED effects want a continuous type signal, such as the Button board “Latch On/Latch Off” function.
  4. Only WS2812 (NeoPixel) type addressable LED strips will work with the Spectacle Light Board.

Meet the Spectacle Light Board

Designed to make it easy to add relatively complex lighting effects to your Spectacle projects, the Spectacle Light Board integrates with the rest of the Spectacle ecosystem to allow you to control lighting effects relatively effortlessly.

It has two 1/8" (3.5mm) jacks for Spectacle control signals. Pay attention to the directionality of the jacks! The one labeled “In” should be plugged into a board that is closer to the Director Board than the Light Board is, or into the Director Board itself.

Signal jacks

The Light Board supports up to three strands of addressable LEDs. Each strand can have up to 60 individual pixels. Not all types of addressable LEDs are compatible with the Spectacle Light Board. If you have questions about whether or not a particular type of LED strip is compatible with the Light Board, contact SparkFun technical support.

LED Strand Connectors

The Light Board has a Micro B USB connector to allow it to be directly powered by an external power supply. The relatively slender cables the Spectacle data travels over are not adequate for the large amount of current drawn by more than a few pixels.

USB Power Jack

Spectacle Button Board

The Spectacle Button Board allows you to add input from buttons or switches to your Spectacle projects. It has a total of 9 signal inputs, eight of which can come from external buttons and one button directly on the board.

Spectacle Button Board

DEV-14044
14.95

tl;dr

  1. Buttons or switches can be connected to the board by pushing wires into the “poke home” type connectors on the board.
  2. Up to nine signals are available.
  3. Button signals can be either momentary or continuous.

Meet the Spectacle Button Board

Designed to bring simple signals from the world into your Spectacle projects, the Spectacle Button Board provides input for any of your Spectacle projects.

It has two 1/8" (3.5mm) jacks for connecting to other boards in a Spectacle system. Note that the Spectacle data jacks are directional: the one marked “In” should be plugged into the “upstream” board (i.e., closer to the Director Board than this one) and the one marked “Out” connects to the next downstream board.

Audio jacks

There are 8 “poke home” connectors on the Button Board. Each one can be connected to one (or more) buttons. To add a connection, simply push the stripped end of a wire into the hole on the connector. The connector will automatically grab on and hold the wire in place. If you need to remove the wire later, an small object (bobby pin, ballpoint pen, etc.) can be used to depress the release button, allowing the wire to be extracted without damage.

Poke home connectors

There is an input button on the button board itself which can be used to provide an input signal if no other buttons are available. It functions like any other normal button that might be attached. Be certain you’re pressing the button labeled ‘8’ and not the one labeled ‘Reset’! Pressing the reset button will reset your button board, probably causing your entire system to stop working properly until you reset your Director Board!

Onboard Button 8

The Configuration Utility

Spectacle Button Board

Button board action options

For the Button board, there are five options: three which produce a momentary pulse type output and two that produce a continuous switch type output.

Action on press

Action on press options

Trigger an action when a button is first pressed, regardless of how long it is subsequently held down.

  • “When button number … is pressed” - This is the number of the button we wish to assign to this action. The button numbers are printed on the board, and run from 0 through 8.
  • “trigger channel number …” - A single, momentary pulse will be sent out on this channel. It is suitable for starting a sound, initiating a motion, or setting the color of a light strip, but not for continuous sound playback or for turning on a light strip effect, for instance.
Action on release

action on release options

Trigger an action when a button is released, regardless of how long it has been held down prior to being released.

  • “When button number … is released” - This is the number of the button we wish to assign to this action. The button numbers are printed on the board, and run from 0 through 8.
  • “trigger channel number …” - A single, momentary pulse will be sent out on this channel. It is suitable for starting a sound, initiating a motion, or setting the color of a light strip, but not for continuous sound playback or for turning on a light strip effect, for instance.
Action on press or release

Action on press or release options

Trigger an action when a button is pressed, then trigger the same action again when the button is released.

  • “When button number … is either pressed or released” - This is the number of the button we wish to assign to this action. The button numbers are printed on the board, and run from 0 through 8.
  • “trigger channel number …” - A single, momentary pulse will be sent out on this channel both at the time the button is pressed and at the time it is released. It is suitable for starting a sound, initiating a motion, or setting the color of a light strip, but not for continuous sound playback or for turning on a light strip effect, for instance.
Action while holding

Action while holding options

Trigger an event as soon as a button is pressed, then continue to trigger that event as long as the button is held down.

  • “While button number … is pressed” - This is the number of the button we wish to assign to this action. The button numbers are printed on the board, and run from 0 through 8.
  • “activate channel number …” - A continuous will be sent out on this channel. It is suitable for triggering and repeating a sound, or for turning on and keeping on (at least, while the button is held) a lighting effect.
Latch On/Latch Off

Latch On/Off options

This action is like a latching power switch. One press turns the signal on, another later press turns the signal off.

  • “While button number … is pressed” - This is the number of the button we wish to assign to this action. The button numbers are printed on the board, and run from 0 through 8.
  • “activate channel number … until button is pressed again” - A continuous will be sent out on this channel. It is suitable for triggering and repeating a sound, or for turning on and keeping on a lighting effect.

Spectacle Light Board

Action list for light board

The Light board supports 9 different actions. Most of them want a continuous-type signal input, although a couple of them can be used with momentary input signals. We’ll cover the difference under each action. Each action will have a field for the number of pixels the lightstrip that action is being applied to has, and we won’t mention it again.

Rainbow Effect

Rainbow effect settings

The rainbow effect displays a rainbow of colors across the strip, changing the color of each pixel indvidually to make it appear as though the rainbow is scrolling along the lightstrip.

  • “While channel number … is active” - The rainbow effect persists only while the channel is active, so a continuous input signal is needed.
  • “rainbow scroll lightstrip number …” - Select which lightstrip you wish the rainbow effect to operate on. To have the same effect on multiple lightstrips, you must create multiple actions.
  • scroll speed slider - controls how fast the pattern moves as it scrolls past.
Theater chase

Theater chase settings

Theater chase mode behaves like a marquee light border. The lights will march along making it appear as though the lightstrip is moving in steps.

  • “While channel number … is active” - The theater chase effect persists only while the channel is active, so a continuous input signal is needed.
  • “theater chase lightstrip number …” - Select which lightstrip you wish the theater chase effect to operate on. To have the same effect on multiple lightstrips, you must create multiple actions.
  • chase speed slider - controls how fast the pattern moves as it scrolls past.
  • color picker input - allows you to select the color of the lights.
Scanning effect

Scanning effect settings

Scanning mode sees a small group of lights bouncing back and forth along the length of the lightstrip, reminiscent of Cylons from Battlestar Galactica.

  • “While channel number … is active” - The scanning effect persists only while the channel is active, so a continuous input signal is needed.
  • “scan lightstrip number …” - Select which lightstrip you wish the scanning effect to operate on. To have the same effect on multiple lightstrips, you must create multiple actions.
  • scan speed slider - controls how fast the pattern moves as it scrolls past.
  • color picker input - allows you to select the color of the lights.
Twinkle effect

Twinkle effect settings

Causes individual lights on the selected strip to perform a twinkling action.

  • “While channel number … is active” - The twinkle effect persists only while the channel is active, so a continuous input signal is needed.
  • “twinkle lightstrip number …” - Select which lightstrip you wish the twinkle effect to operate on. To have the same effect on multiple lightstrips, you must create multiple actions.
  • color picker input - allows you to select the color of the lights.
  • speed slider - controls how fast the twinkles are moves as it scrolls past.
  • magic slider - controls how magical the twinkles are. Play with it!
Lightning effect

Lightning effect settings

Causes the entire strip to strobe in a manner that looks a lot like a lightning flash.

  • “While channel number … is active” - The lightning effect persists only while the channel is active, so a continuous input signal is needed.
  • “lightning on lightstrip number …” - Select which lightstrip you wish the lightning effect to operate on. To have the same effect on multiple lightstrips, you must create multiple actions.
  • color picker input - allows you to select the color of the lights.
  • speed slider - controls how often the lightning strike occur moves as it scrolls past.
  • fury slider - controls how furious the lightning is. Play with it!
Flame effect

Flame effect settings

Causes the entire strip to crackle like a fire.

  • “While channel number … is active” - The flame effect persists only while the channel is active, so a continuous input signal is needed.
  • “make fire on lightstrip number …” - Select which lightstrip you wish the flame effect to operate on. To have the same effect on multiple lightstrips, you must create multiple actions.
  • color picker input - allows you to select the color of the lights. Experiment with different colors!
Fade effect

Fade effect settings

The lightstrip will change from one color to another over time, then back to the first.

  • “While channel number … is active” - The fade effect persists only while the channel is active, so a continuous input signal is needed.
  • “fade lightstrip number … back and forth” - Select which lightstrip you wish the fade effect to operate on. To have the same effect on multiple lightstrips, you must create multiple actions.
  • “from color” color picker - This is the initial color that the lightstrip will power up with.
  • “to color” color picker - The other color, which the strip fades to and from periodically.
  • “fade speed” slider - Controls how fast the fading action occurs.
Fill

Fill settings

Fills some number of lights on the light strip with a single color. Blanks the other lights to off.

  • “listen to channel number …” - A momentary signal on this channel is all that is needed to trigger a fill operation, and the fill will persist until another effect starts.
  • “wait for … seconds” - This delay allows for sequencing effects. Most often you’ll probably set it to 0.
  • “clear lightstrip number …” - Select the lightstrip to operate upon.
  • “and fill … pixels” - The number of pixels, from closest to the Light board out, to turn on.
Light pixel

Pixel settings

Turns on one light and blanks the rest of the lights to off.

  • “listen to channel number …” - A momentary signal on this channel is all that is needed to trigger a light pixel operation, and the lit pixel will persist until another effect starts.
  • “wait for … seconds” - This delay allows for sequencing effects. Most often you’ll probably set it to 0.
  • “clear lightstrip number …” - Select the lightstrip to operate upon.
  • “and light pixel number … ” - The number of the pixel, from closest to the Light board out, to turn on.

Example Project

Let’s use the contents of the Spectacle Light Kit to put together a working project! We’re going to use the Button Board to control the Light Board’s “Scanning Effect” action.

Connect the boards

Start by connecting up the boards. All the hardware you’ll need came with the kit.

First, plug one end of one of the TRRS cables into the “Direct” jack on the Director Board.

The direct jack

Next, take the other TRRS cable and plug it into the “Program” jack on the Director Board.

The program jack

Take the other end of this cable and plug it into the audio jack of the phone, tablet, or computer that you’ll be using to program the system.

Into the phone jack

Then take the other end of the first TRRS cable and plug it into the “In” jack on the Button Board.

Cable into button board in jack

Grab another of the TRRS cables and plug it into the “Out” jack on the Button Board.

Cable into out on button board

Plug the other end of that cable into the “In” jack on your Light Board.

Cable into IN jack on light board

Now plug your lightstrip adapter cable into the Light Board…

Light strip adapter into light board

…and plug the lightstrip into the other end of that adapter.

light strip adapter into light strip

Finally, plug the Micro B end of the power adapter into the Director Board, and the other end into the wall. You should see one solid light and one blinking light on the Light board and the Button board. On the Director Board, you’ll see one solid light and one light which blinks eight times, then pauses, then repeats. This shows that power is present and the boards are up and running.

Setting up the board configuration

When you first open the Spectacle app webpage, this is what you’ll see. Your project name will differ from mine, as Spectacle assigns a random name to each project.

Blank project page

To continue, we must tell the project which boards we wish to use. Start by clicking the “Add a board” button at the bottom of the page.

add a board button

This will bring up a list of the available boards. We’re going to add our button board first of all, so click anywhere in the “Button” box to add it.

Now, repeat this process one more time to add a Light Board.

List of available boards

You should now have a list that looks like this. Order is important, so make sure your boards are in the same order as shown above. Names are not important, however, and your boards will have different names than mine do, as Spectacle assigns names randomly.

All boards in list

Each board has a clapboard icon associated with it. To add or edit actions, click this icon. We’re going to start by adding an action to the button board.

Edit buttons highlighted

The window that pops up will look like the above. Click the button highlighted in the image below to add an action to the Button Board.

Add an action button

This list will come up. It represents all the different actions which can be performed by a Button Board.

Click on the list entry which says “Latch On/Latch Off”.

Action list for button board

You’ll then see this screen, which presents the various options for the Latch On/Latch Off action. Every action will have different settings.

latch on latch off options

Here are the settings we need to use for this project. We want button 8 (the button on the Button Board) to activate channel 0 when pressed. Later on, we’ll tell our light board to watch channel 0 and do something when it’s active.

Latch mode button options

Now click on the “Go Back” button to return to the main page. Your action changes will be saved automatically.

Go back button

We’re back at the main page, now, and you can see that the action we added appears under the Button Board in the boards list.

Main page with both boards

Now click on the clapboard icon for the Light Board to add an action for the button to trigger. When you click the “Add an Action” button, you’ll be presented with this list of actions that the Light Board can perform. We’re going to choose the “Scanning Effect” action.

Light board action options

This screen will pop up, albeit without any of the entries in the fields. Go ahead and set up the fields as I’ve shown them above, then click the “Go Back” button.

Scan action settings

Congratulations! You’ve finished the configuration step of the process. Now it’s time to move on to loading the project onto your Director Board.

Project, completed

Uploading

Now that you’ve created your Spectacle program it’s time to upload it to the Director Board. If you followed the instructions above, your uploading device is connected to the board and ready to go, so all you need to do is touch the “Install Script” button at the bottom of the page. That will bring up the page seen below.

Upload page

Make sure the volume on your device is turned all the way up, and that no other audio source (music, video, etc) is playing in the background. Then press and hold the “RST” button on the Director Board, press and hold the “PROG” button, then release the “RST” button.

This will put the Director Board into program mode. You’ll see the light on the board blink three times, pause, then repeat. This is your visual indicator that the board is in program mode. Once you’ve established that the board is in program mode, you can begin programming by touching the “Install” button on the Spectacle app screen. The button will gray out during the programming process, which should only last for a few seconds. Once programming is done, you’ll see the light on the Director Board blink 10 times, pause, then repeat. That’s your cue that the program was uploaded successfully.

Press the “RST” button again to reset the system and begin the program!

If you have any troubles, visit the troubleshooting page for help resolving your issues.

Further reading

For general Spectacle information, please check out the user guide:

New!

Spectacle User's Guide

May 4, 2017

The Spectacle system is designed to help those without electronics or programming experience integrate electronics into projects.

For more Spectacle fun, check out the additional tutorials below:

New!

Spectacle Audio Board Hookup Guide

All the information you need to use the Spectacle Audio Board in one place.
New!

Spectacle Sound Kit Hookup Guide

All the information you need to use the Spectacle Sound Kit in one place.
New!

Spectacle User's Guide

The Spectacle system is designed to help those without electronics or programming experience integrate electronics into projects.
New!

Spectacle Light Board Hookup Guide

All the information you need to use the Spectacle Light Board in one place.
New!

Spectacle Inertia Board Hookup Guide

Everything you need to know about using the Spectacle Inertia Board in one place.
New!

Spectacle Motion Kit Hookup Guide

All the information you need to use the Spectacle Motion Kit in one place.
New!

Spectacle Motion Board Hookup Guide

All the information you need to use the Spectacle Motion Kit in one place.
New!

Spectacle Button Board Hookup Guide

All the information you need to use the Spectacle Button Board in one place.

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

Spectacle Audio Board Hookup Guide

$
0
0

Spectacle Audio Board Hookup Guide a learn.sparkfun.com tutorial

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

Spectacle Audio Board

The Spectacle Audio Board allows you to add sound to your Spectacle projects. It accepts a microSD card with sounds in .ogg format (more on this later), and has a 1/8" (3.5mm) audio jack to connect to external amplifiers.

Spectacle Audio Board

DEV-14034
14.95

tl;dr

  1. Audio files for Spectacle should be formatted as .ogg files.
  2. Audio files should have names 00.ogg, 01.ogg, 02.ogg, etc.
  3. The audio jack on the Audio Board produces output suitable for amplification only. It is not suited to headphones or unpowered speakers.

Meet the Spectacle Audio Board

Designed to be a low-cost and easy to use method of adding sound to projects, the Spectacle Audio Board integrates with the rest of the Spectacle ecosystem to provide sound effects on demand.

It has three 1/8" (3.5mm) jacks: two for Spectacle control signals and one for the audio output. Be certain you are plugging cables into the right jacks! Plugging an audio device into one of the Spectacle jacks could cause damage to the audio device. Note that the Spectacle data jacks are directional: the one marked “In” should be plugged into the “upstream” board (i.e., closer to the Director Board than this one) and the one marked “Out” connects to the next downstream board. The “Out” jack is not for audio signals.

Spectacle IO jacks

The audio output is designed for amplified devices only. This means that any attempt to use the Spectacle Audio Board with headphones or unamplified speakers will fail to produce audible output. SparkFun sells a small, amplified, rechargeable speaker which is specifically intended for use with the Spectacle Audio Board.

Audio jack

The Spectacle Audio Board uses a Micro SD card to store the audio files to be played. The files should be stored as .ogg Vorbis encoded files. This free audio file format can be played and created on any type of computer. Later in the tutorial we’ll show you how to convert from MP3, WAV, or other file formats to the .ogg format.

SD Card Slot

The files must be named by number, which is how they will be referred to from within the configuration application. Filename examples are 00.ogg, 01.ogg, 02.ogg, and so forth.

Suggested Reading

Before proceeding, you should read through the Spectacle User’s Guide. It will give you the basics you’ll need to know about how Spectacle works to follow the rest of this tutorial.

The Configuration Utility

Spectacle Audio Board

Sound interface

The Spectacle Audio Board only supports one action: Play Sound. As you can see above, there are a number of settings associated with this action.

  • “Listen to channel number…” - This is the channel number which triggers the audio to start playing. As long as this channel’s value is above the threshold level (see below), the sound will repeat playing at a rate determined by the two time intervals specified lower down.
  • “wait … seconds and play…” - This is the first delay in the system. By delaying when a sound plays, you can sequence events however you see fit.
  • “…and play file number…” - This is where you tell the board which file to play. Remember, when copying the audio files to the Micro SD card, they should be named as 00.ogg, 01.ogg, 02.ogg, etc. The number in this field corresponds to the number in the name of the audio file. If there is no audio file with the corresponding number, no sound will play.
  • “do not allow another sound to interrupt until … seconds” - The number in this field should correspond to the length of the audio file. If this value is less than the length of the sound file, another trigger sent to the audio board will interrupt the sound before it finishes. If it is longer than the sound, there will be a period of silence after playback before another playback can be initiated.
  • “activation threshold” - As it says in the app, most of the time you don’t need to adjust this. By tweaking this, you can set the angle at which the Spectacle Accelerometer Board triggers a sound, or the frequency with which a Random Trigger Virtual Board causes a sound to play.

Converting Sounds to OGG Vorbis Format

The files used by the Spectacle Audio Board must be in OGG Vorbis format. This free, lossy codec has a higher compression ratio than MP3, and, more importantly, can be used without paying a licensing fee to any third part organization.

Download and Install Audacity

We’ll be using the free, open source program “Audacity” to convert from whatever your file’s current format is to OGG Vorbis.

Audacity website

Audacity is available across all three major operating systems, so you shouldn’t have any trouble getting it installed.

When you start Audacity, you’ll see this screen, or one very like it. While at first blush it seems extremely complex, none of this crap is important to us, so don’t panic.

Audacity main screen

Load a file

Like most programs, “loading a file” just means selecting “Open” from the File menu and choosing which file you wish to convert. Audacity is capable of editing most types of audio files: WAV, AIFF, FLAC, MP3, and others.

Audacity file menu

By default, Audacity shows all files, not just compatible audio files, when you bring up the open dialog. There’s a dropdown menu that allows you to change that so it shows only compatible audio files along the bottom edge of the window.

Audacity open file dialog

Once you select which file you wish to edit, a rather alarmist message may pop up warning you about editing files without making a copy of them. Just click “OK”.

Audacity edit file warning

You’ll see, then, something like this show up. This is what your audio file looks like, to the computer. Again, don’t panic! Unless you want to edit the sound in some way (which we don’t), none of the settings or pieces of information that have popped up here matter to us.

Audacity with open file

Convert to OGG

Now that you have the file loaded, you need to convert it to OGG Vorbis format. To do so, open the “File” menu and select the “Export Audio…” menu item about halfway down. A familiar looking save window should pop up.

Export command in file menu

Right below the “File name:” field you’ll see a drop-down menus labeled “Save as type:”. Select “Ogg Vorbis Files” in that drop down.

A slider will appear at the bottom of the window. The default value of ‘5’ is probably good enough for most purposes. Click “Save” and another window will pop up.

Export audio frame

This one allows you to set metadata about the file. You can ignore everything and just click “OK” to skip past this.

Congratulations! You’ve successfully converted a file to OGG Vorbis format. You may now copy that file to the Micro SD card (don’t forget to rename it to a number!) for use with the Spectacle Audio Board.

Set metadata window

Extra credit- trimming the fat and making the sound louder

As you can see in my file above, there’s a great deal of room between the extents of the sound and the extents of the window. In the time (horizontal) axis, this manifests as flat lines before and after the content of the sound file. In the “loudness” (vertical) axis, this manifests as space between the top and bottom of the waveform file and the top and bottom of the playback position window.

File open in Audacity

Let’s eliminate some of that dead time before and after the sound plays. To do so, simply click inside the playback position window and drag, as though you are trying to select a section of text. The part you’ve selected will be highlighted, as above. Now, just hit the “Delete” key on your keyboard, and that section will be removed. Repeat the process at the other end of the sound.

Extra dead time highlighted

Now, let’s see what we can do about volume. Under the “Edit” menu, look for the “Select” submenu, and choose “All” to select the entire sound. You can also just use the drag-and-highlight method from above.

Finding the "Select All" menu option

Now that you’ve got the entire sound selected, click on the “Effect” menu and select the “Amplify…” option.

Effects menu

A new window will pop up with a slider, a couple of text boxes, and one checkbox. The slider will be pre-positioned to amplify the sound as much as possible without “clipping” it. “Clipping” occurs when you try to amplify a sound more than the system you’re playing it through can stand, and it results in a sort of grating buzzing noise during playback.

Amplify dialog box

You have a choice, now: you can either accept the system’s suggested level, or you can click on the “Allow Clipping” check box and increase the amplification more with the slider. I’ve chosen to accept the clipping limitation for the image above; comparing it to the image of the file higher up, you can see how I’ve trimmed the dead time at the ends and increased the amplitude vertically.

Why would you want to allow your sound to clip? Well, first of all, the preset amplification only takes into account the peak value of your sound, so if one small section of the audio is allowed to clip, it may allow the vast majority of the sound to be substantially louder. Secondly, if you’re playback device is of relatively poor quality, or the sound file itself is, allowing clipping may increase volume significantly without making the sound quality too much worse than it already is. Thirdly, volume intensity may be far more important than sound quality, and allowing clipping lets you push the volume as high as you can.

Edited sound

Now that you’ve successfully edited the sound, export it to OGG Vorbis as we covered above.

Example Project

Let’s use the Spectacle Audio Board to play a single sound at random intervals.

Connect the boards

You’ll need the following hardware for this tutorial:

Wall Adapter Power Supply - 5.25V DC 2.4A (USB Micro-B)

TOL-13831
7.95
6
Hamburger Mini Speaker

COM-14023
4.95
MicroSD Card with Adapter - 8GB

COM-11609
13.95
2
Spectacle Director Board

DEV-13912
24.95
Spectacle Audio Board

DEV-14034
14.95
Audio Cable TRRS - 3ft

CAB-14164
2.5

You will need two of the TRRS cables. Make sure the speaker is charged before the first time you try to use it!

First, plug one end of one of the TRRS cables into the “Direct” jack on the Director Board.

The direct jack

Next, take the other TRRS cable and plug it into the “Program” jack on the Director Board.

The program jack

Take the other end of this cable and plug it into the audio jack of the phone, tablet, or computer that you’ll be using to program the system.

Into the phone jack

You’ll now need to connect the other end of the first TRRS cable (the one connected to the “Direct” jack) to the “In” jack on the Audio Board.

In jack on Audio Board

Connect the speaker to the “Audio Output” port on the Audio Board.

Audio jack to speaker connection

Finally, insert the microSD card with the files you prepared on it into the slot on the back side of the Audio Board.

MicroSD card insertion

Finally, plug the micro-B end of the power adapter into the Director Board, and the other end into the wall. You should see one solid light and one blinking light on the Audio board, and on the director board, you’ll see one solid light and one light which blinks one time, then pauses, then repeats. This shows that power is present and the boards are up and running.

Setting up the board configuration

We’re going to assume that you followed the instructions on the previous page about converting sounds to OGG Vorbis format, and that there is a sound named “00.ogg” on the Micro SD card which is inserted into the Audio Board. If this is not the case, take a few minutes to go back to that page and prepare a sound.

When you first open the Spectacle app webpage, this is what you’ll see. Your project name will differ from mine, as Spectacle assigns a random name to each project.

Blank project page

The very first thing you’ll do is add an Audio Board to the project. To do this, click on the “Add a Board” button, highlighted in the image below.

Add a board button

Clicking on that button will bring up a list of available boards. Click anywhere in the “Audio” box to add an Audio Board to your system.

Board list

We now need to tell the system what we want this board to do.

In the screen that pops up after you click in the “Audio” box, you’ll find this little clapboard icon. Click that icon to add actions to the Audio Board.

Edit button

This will bring up the “Actions” list for this board, which is currently empty. To add an action, click the “Add an Action” button, highlighted below.

Add action button

Clicking on the “Add an Action” button will pull down this short menu, with only two options on it. Click “Play Sound” to add a sound playback action to the board.

Actions list for the audio board

This is the “Play Sound” action settings page. We’ve covered the meaning of these fields elsewhere in this tutorial, so I’m just going to tell you what to enter in these fields.

Play sound action options

Copy the settings from the image below into the fields.

Settings for the play sound action

Now click the “Go Back” button at the bottom of the page. The settings you just put in will be automatically saved, and you’ll return to the main page of the project.

Go Back Button highlighted

Now you’re back to the main page, and you can see that the action set up in the Audio Board configuration we just did shows up in the list of boards as well, as a reminder of what that board is configured to do.

Main page with new actions

Now, click “Add a Board” to bring up the board list again, then click on “Virtual” to add a virtual board to the system. This “board” will generate the signal which randomly triggers the audio playback.

Virtual Boards provide a number of functions outside of the normal operation of Spectacle boards. In this case, we want "Random Input", which generates a signal at a fixed timing rate.

Again, click the clapboard icon on the virtual board list item to bring up the action add and edit page.

Here’s the list of possible actions for the virtual board. Click on “Random Input” to get the randomizing function we want.

Virtual board actions list

Configure the random input settings as shown in the image below, then click the “Go Back” button to return to the main page.

Random function settings

Congratulations! You’ve finished configuring the system. Now it’s time to install the settings onto the Director board.

Final project screen

Uploading

Now that you’ve created your Spectacle program it’s time to upload it to the Director Board. If you followed the instructions above, your uploading device is connected to the board and ready to go, so all you need to do is touch the “Install Script” button at the bottom of the page. That will bring up the page seen below.

Upload page

Make sure the volume on your device is turned all the way up, and that no other audio source (music, video, etc) is playing in the background. Then press and hold the “RST” button on the Director Board, press and hold the “PROG” button, then release the “RST” button.

This will put the Director Board into program mode. You’ll see the light on the board blink three times, pause, then repeat. This is your visual indicator that the board is in program mode. Once you’ve established that the board is in program mode, you can begin programming by touching the “Install” button on the Spectacle app screen. The button will gray out during the programming process, which should only last for a few seconds. Once programming is done, you’ll see the light on the Director Board blink 10 times, pause, then repeat. That’s your cue that the program was uploaded successfully.

Press the “RST” button again to reset the system and begin the program!

If you have any troubles, visit the troubleshooting page for help resolving your issues.

Further Reading

For general Spectacle information, please check out the user guide:

New!

Spectacle User's Guide

May 4, 2017

The Spectacle system is designed to help those without electronics or programming experience integrate electronics into projects.

For more Spectacle fun, check out the additional tutorials below:

New!

Spectacle Sound Kit Hookup Guide

All the information you need to use the Spectacle Sound Kit in one place.
New!

Spectacle User's Guide

The Spectacle system is designed to help those without electronics or programming experience integrate electronics into projects.
New!

Spectacle Light Kit Hookup Guide

All the information you need to use the Spectacle Light Kit in one place.
New!

Spectacle Light Board Hookup Guide

All the information you need to use the Spectacle Light Board in one place.
New!

Spectacle Example: Super Mario Bros. Diorama

A study in building an animated diorama (with sound!) using Spectacle electronics.
New!

Spectacle Motion Board Hookup Guide

All the information you need to use the Spectacle Motion Kit in one place.
New!

Spectacle Button Board Hookup Guide

All the information you need to use the Spectacle Button Board in one place.
New!

Spectacle Light and Sound Kit Hookup Guide

All the information you need to use the Spectacle Light and Sound Kit in one place.

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

Spectacle Inertia Board Hookup Guide

$
0
0

Spectacle Inertia Board Hookup Guide a learn.sparkfun.com tutorial

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

Spectacle Inertia Board

The Spectacle Inertia Board makes it easy to sense motion or orientation with a Spectacle project.

Spectacle Inertia Board

DEV-13992
19.95

tl;dr

  1. The Inertia Board can sense motion, lack of motion, orientation, or acceleration.
  2. It’s capable of either momentary triggers or continuous triggers.

Meet the Spectacle Inertia Board

The Spectacle Inertia Board is designed to allow a Spectacle project to detect its orientation, whether it is moving or stationary, or whether it is under acceleration.

It has two 1/8" (3.5mm) jacks for Spectacle control signals. Pay attention to the directionality of the jacks! The one labeled “In” should be plugged into a board that is closer to the Director Board than the Inertia Board is, or into the Director Board itself.

IO Jacks

Suggested Reading

Before proceeding, you should read through the Spectacle User’s Guide. It will give you the basics you’ll need to know about how Spectacle works to follow the rest of this tutorial.

The Configuration Utility

Inertia board action options

There are three different actions which can be assigned to the inertia board, allowing you to sense several different options of motion and orientation. We’ll explain them one at a time below.

Sense All Motion

Sense all motion options

This action sends out a trigger when the board is either moving or stationary. When the board is moved, the trigger signal will be sent nearly immediately. When the board goes from moving to stationary, however, there is a delay of a couple of seconds before the trigger signal comes out.

  • “if / while” - Determines whether the signal should happen only once, when the board starts or stops moving, or whether it should be constant any time the board is moving or not moving.
  • “moving / stationary” - Should the signal be activated when the board starts moving, or when it stops moving?
  • “activate channel number …” - Which channel do we want the signal to be on?

Sense Orientation

Sense orientation settings

Another sensing application for the Inertia Board is orientation. Each face and edge of the Inertia Board has a name associated with it (A-D, Top, or Bottom). The board can output a signal when any of these sides is up, either only when it initially becomes face up or continually as long as it is face up.

  • “if / while” - Determines whether the signal should happen only once, when the board first attains the orientation, or constantly, so long as the orientation is held.
  • “ a b c d top bottom” - This is the side/face of the board which causes a signal to be sent when it’s on top.
  • “activate channel number …” - Which channel do we want the signal to be on?

Measure Acceleration

Measure acceleration options

The final sensing option is to measure acceleration. The output can be between 0 and 1000, depending on the acceleration of the board. The axis along which the acceleration is being measured is defined by the check boxes, and acceleration in a positive direction will be greater than 500 while a negative acceleration will be less than 500.

We recommend experimentation as the best way to figure out how this mode works.

Example Project

Let’s make a simple project using the Spectacle Audio Board and the Spectacle Inertia Board! We’ll set it up so that a sound is played whenever the Inertia Board is moved.

Connect the boards

To follow this tutorial, you’ll need this hardware:

Wall Adapter Power Supply - 5.25V DC 2.4A (USB Micro-B)

TOL-13831
7.95
6
Hamburger Mini Speaker

COM-14023
4.95
MicroSD Card with Adapter - 8GB

COM-11609
13.95
2
Audio Cable TRRS - 3ft

CAB-14164
2.5
Spectacle Inertia Board

DEV-13992
19.95
Spectacle Director Board

DEV-13912
24.95
Spectacle Audio Board

DEV-14034
14.95

Note that you will need three of the TRRS cables!

First, plug one end of one of the TRRS cables into the “Direct” jack on the Director Board.

The direct jack

Next, take the other TRRS cable and plug it into the “Program” jack on the Director Board.

The program jack

Take the other end of this cable and plug it into the audio jack of the phone, tablet, or computer that you’ll be using to program the system.

Into the phone jack

Plug the other end of that cable into the “In” jack on your Audio Board.

Plugging into the in jack on the audio board

Plug the speaker into the Audio Out port on the Audio Board.

Plugging in the speaker

Take another one of the TRRS cables and plug one end into the “Out” port on the Audio Board…

Plugging into the out jack on the audio board

…and plug the other end of that cable into the “In” port on the Inertia Board.

Plug the other end into the inertia board

Finally, plug the Micro B end of the power adapter into the Director Board and the other end of the adapter into the wall. You should see one solid light and one blinking light on the Inertia Board and the Audio Board. On the Director Board, you’ll see one solid light and one light which blinks one time, then pauses, then repeats. This shows that power is present and the boards are up and running.

Setting up the board configuration

When you first visit the Spectacle configuration website, you’ll be presented with a screen that looks like this. Your project name will differ, however, as Spectacle assigns a new name to each project. To continue, we’re going to have to add our Audio Board to the project.

Blank project

Click on the “Add a Board” button, as highlighted above, to bring up a list of available boards.

Add a board button

In the list, click anywhere in the “Audio” box to add an Audio Board to our project.

Board list

You’ll be returned to the main project page, but this time, an Audio Board will appear in the list on the page. Repeat these two steps to add an Inertia Board to the project.

Main page with audio board

Here you can see both boards in the list in place. Next we’ll need to add actions to the boards.

List with both boards in place

You can see highlighted above the clapboard icons which, when clicked, will take you to the “Actions” page, where you can assign an action to your board. Let’s start by assigning an action to the Audio Board.

Add actions buttons

An empty page will come up. There are no currently assigned actions, so we’ll need to assign some. Click the “Add an Action” button at the bottom of the page.

Empty actions page

As you can see, the Audio Board only has one action. Click on “Play Sound” to add this action to your Audio Board.

There's only one action for the sound board

Here are the various settings for the “Play Sound” action. Copy the settings as I’ve entered them into you project.

Settings for play sound

Click on the “Go Back” button at the bottom of the page to return to the main page, then click on the clapboard icon for the Inertia Board to add an action. When the empty list pops up, click the “Add an Action” button at the bottom to bring up the list of actions for the Inertia Board.

The Go Back button

Here’s the list of actions for the Inertia Board. We want to detect when motion occurs, so click the first option, “Sense All Motion”.

Inertia board actions

Here’s the options page for the sense motion action. Note the choices I’ve made and duplicate them for your project, then click “Go Back”.

Sense motion options

Congratulations! Your project is completed. Now let’s upload it to the Director Board.

Project done

Installing a project on the Director Board

Now that you’ve created your Spectacle program it’s time to upload it to the Director Board. If you followed the instructions above, your uploading device is connected to the board and ready to go, so all you need to do is touch the “Install Script” button at the bottom of the page. That will bring up the page seen below.

Upload page

Make sure the volume on your device is turned all the way up, and that no other audio source (music, video, etc) is playing in the background. Then press and hold the “RST” button on the Director Board, press and hold the “PROG” button, then release the “RST” button.

This will put the Director Board into program mode. You’ll see the light on the board blink three times, pause, then repeat. This is your visual indicator that the board is in program mode. Once you’ve established that the board is in program mode, you can begin programming by touching the “Install” button on the Spectacle app screen. The button will gray out during the programming process, which should only last for a few seconds. Once programming is done, you’ll see the light on the Director Board blink 10 times, pause, then repeat. That’s your cue that the program was uploaded successfully.

Press the “RST” button again to reset the system and begin the program!

If you have any troubles, visit the troubleshooting page for help resolving your issues.

Further reading

For general Spectacle information, please check out the user guide:

New!

Spectacle User's Guide

May 4, 2017

The Spectacle system is designed to help those without electronics or programming experience integrate electronics into projects.

Check out the additional Spectacle guides below:

New!

Spectacle Audio Board Hookup Guide

All the information you need to use the Spectacle Audio Board in one place.
New!

Spectacle Sound Kit Hookup Guide

All the information you need to use the Spectacle Sound Kit in one place.
New!

Spectacle Light Board Hookup Guide

All the information you need to use the Spectacle Light Board in one place.
New!

Spectacle Example: Super Mario Bros. Diorama

A study in building an animated diorama (with sound!) using Spectacle electronics.
New!

Spectacle Motion Kit Hookup Guide

All the information you need to use the Spectacle Motion Kit in one place.
New!

Spectacle Motion Board Hookup Guide

All the information you need to use the Spectacle Motion Kit in one place.
New!

Spectacle Button Board Hookup Guide

All the information you need to use the Spectacle Button Board in one place.
New!

Spectacle Light and Sound Kit Hookup Guide

All the information you need to use the Spectacle Light and Sound Kit in one place.

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>