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

Micro:Climate Kit Experiment Guide

$
0
0

Micro:Climate Kit Experiment Guide a learn.sparkfun.com tutorial

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

Introduction to the Micro:Climate Kit

Introduction

We have seen a huge amount of excitement from hobbyists, students and scientists around building a DIY weather station to track what is going on around us on Planet Earth on a daily basis.

We have seen just as much excitement around the BBC’s newly released micro:bit, which made its debut in the United Kingdom and is now available in the United States through SparkFun.

And then it dawned on us…why not combine the two? So, here it is: a weather station kit that is built on top of the inexpensive, easy-to-use micro:bit and Microsoft MakeCode. We have also written seven experiments that walk you through how to use each and every component of the kit and how to use them with the micro:bit and Microsoft MakeCode.

What’s Included in the Kit?

Below is all the parts included in the SparkFun micro:climate kit.

SparkFun micro:climate kit

KIT-14217
114.95

The kit comes with everything you need to build a fully featured weather station for the micro:bit. All you need to supply is, well, the micro:bit!

micro:bit Board

DEV-14208
14.95

The kit includes the following parts:

  • SparkFun weather:bit— The carrier board for the micro:bit and the central component to building a weather station
  • Weather Meter— Wind speed, direction and rain gauge that connects to the SparkFun weather:bit
  • SparkFun Soil Moisture Sensor— A simple probe for measuring soil moisture
  • Waterproof Temperature Sensor— Waterproof temperature sensor with a long wire
  • SparkFun OpenLog— A small widget that logs any data sent to it over a serial connection to a microSD card
  • 10-Pack of M/M 12" Jumper Wires— Jumper wires for connecting things
  • SparkFun Screwdriver— Great for tightening screws and screw terminals

How to Use This Guide

Please note that this guide is designed to get you started with the weather:bit board and the SparkFun micro:climate kit in a simple, straightforward way. We demonstrate each component’s functionality and the corresponding code to make it work.

While you explore this guide, we urge you to take your time and tinker with the sensors, code and ideas shared to build something tailored to your application. Our goal is to get you enough information and know-how to make you dangerous and then release you into the wild, weather station in hand, to do whatever you do with a weather station.

Be sure to share your projects with us via Twitter or Facebook! We are excited to see you get creative and Start Something!

Suggested Reading

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

What is a Circuit?

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

Getting Started with the micro:bit

The micro:bit is a compact, powerful programming tool that requires no software installation. Read on to learn how to use it YOUR way!

Open Source!

All of our experiments and guides are licensed under the Creative Commons Attribution Share-Alike 4.0 Unported License. Feel free to remix and reuse our work. But please, share the love and give us attribution for our hard work!

To view a copy of this license visit this link, or write: Creative Commons, 171 Second Street, Suite 300, San Francisco, CA 94105, USA.

About the weather:bit

The weather:bit is a carrier board for the micro:bit. Similar to an Arduino shield, it is designed to add functionality to the micro:bit without the hassle of a number of other boards, components and all of those jumper wires.

Product photo

In this case, the weather:bit takes your normal run-of-the-mill micro:bit and turns it into a full-blown weather station with a few extra parts, which you can use to measure the following:

  • Air Temperature
  • Relative Humidity
  • Barometric Pressure
  • Wind Speed
  • Wind Direction
  • Rain Fall
  • Soil Moisture
  • Soil Temperature

Phewwwww! That is a lot of data for such a tiny computer! Let’s take a closer look at this board and check it out for ourselves.

Edge Connector

The weather:bit connects to the micro:bit via an edge pin connector. This makes it handy to swap out micro:bits for programming, but also gives reliable connections to all of the different pins on the micro:bit.

EdgeConnector

BME280 Barometric Pressure Sensor

The weather:bit has a BME280 barometric pressure sensor onboard, which can measure air temperature, humidity, barometric pressure and altitude. It communicates with the micro:bit via I2C, and the data from this sensor is easily accessible using the SparkFun weather:bit package for MakeCode.

BME280

Weather Meter Sockets

There are two RJ11 jacks at the bottom of the weather:bit. These are used to connect our weather meters to the weather:bit.

RJ11 Wind Rain

These meters enable you to measure the wind speed and direction, as well as rain fall.

weather meter hooked u

Again, these are easily accessible in MakeCode via our SparkFun weather:bit package.

Soil Moisture and Temperature

Between the two RJ11 jacks are two sets of screw terminals sets.

Soil Moisture and Temp Screw Terminals

The one on the left is used to hook up a soil moisture sensor. You can use either longer jumper wires or wires cut to whatever length works for your project.

Soil Moisture

The set on the right is the soil temperature sensor. It is set up to use our waterproof temperature sensor. This sensors wire is rather long and is great for monitoring the temperature of the soil in your garden so that you know the exact moment the ground is ready for planting those tomatoes!

Soil Temperature

Serial Port

We have populated the serial port pins with a standard FTDI format to make it easy for you to plug in a serial widget of your choice, such as an OpenLog or Serial LCD display, or to just monitor data through an FTDI breakout and USB cable.

Serial Port

I2C Port

For those of you who are more adventurous and demand a way to hook up other sensors of your choice, we have added an I2C port that can be soldered to directly — or you can add headers for plug-and-play use of your I2C sensors and actuators.

I2C

Installing the weather:bit Package in MakeCode

To make the most out of the weather:bit with the least amount of coding, use the MakeCode package we wrote for the weather:bit board.

Packages?

If you have used Arduino before, you probably know about a thing called a library; which is a collection of code that extends the functionality of the core programming language. MakeCode packages work the same way.

There are some amazing differences between Arduino libraries and MakeCode packages. One of them is that MakeCode packages include JavaScript functions, which you can use when programming in text, as well as all of the blocks you need to program using the block method. This makes learning and using new packages straightforward and shortens the time to awesome when setting out to build the project of your dreams.

Installing a MakeCode Package

To install or add a new package to your MakeCode toolbox (the list of different block groups), click on “Advanced” and then on “Add Package.”

MakeCode Package

From here you can search for “SparkFun weather-bit,” and it should show up as a public package in the list. Go ahead and click on it.

weather-bit Package

This will add all of the blocks to your toolbox. In general, this is a bit tricky as, depending on how the package was written, it may either have its own toolbox or just add blocks to the existing ones. Take a look at your toolbox; for the weather:bit you should see…

Installed Weather-bit Package

Great! You have now installed the weather:bit package and are ready to use the board as well as the components that come in the micro:climate kit. As a side note, for every new MakeCode project that you make, you will have to load packages over again. Not a big deal, but noteworthy! Now, let’s put this package to good use!

Experiment 1: Reading the Temperature, Humidity and Pressure

Introduction

What comes to mind first when you hear the term “Atmospheric Conditions”? Well, other than the weatherman on the news, you probably think about temperature — maybe humidity and even barometric pressure if you are a weather nerd like many of us at SparkFun. In this first experiment we will explore measuring those conditions using a micro:bit and the weather:bit carrier board.

Parts Needed

  • 1x micro:bit board (Not included)
  • 1x weather:bit carrier board
  • 1x micro-B USB cable (Not included)
micro:bit Board

DEV-14208
14.95
SparkFun weather:bit

DEV-14214
14.95
USB Micro-B Cable - 6"

CAB-13244
1.95
3

Suggested Reading

Introduction to the BME280

TempHumidityPressure

The BME280 Atmospheric Sensor is an easy way to measure aspects of the atmosphere around you, including pressure, humidity and air temperature. All of this is combined into a petite package that resides on the weather:bit.

The sensor operates on 3.3V and is super power-efficient, using as little as 5µA (that’s 1/1,000,000 of an amp!) when idling and less than 1mA when it’s taking measurements. This means you can operate the board on a battery, with little thought to major power issues.

In this experiment, you will work with the BME280 to read the temperature, pressure, and humidity of the room as well as your altitude based off of the atmospheric pressure.

Hardware Hookup

Since the BME280 is already on the weather:bit board, this should be pretty straightforward; you have one step in hooking everything up. Insert the micro:bit into the weather:bit carrier board with the LED array facing up as shown in the image below.

Exp1_microBitInsert | microbit plugged into the weather:bit

Note: The edge connector for the micro:bit is not keyed, so there is the potential for the micro:bit to be inserted backward. Be sure to check the orientation of the board and micro:bit before plugging it in!

Running Your Script

We are going to use Microsoft MakeCode to program the micro:bit. Please open a browser window and navigate to https://makecode.microbit.org. This should open the MakeCode environment that you used to install the weather:bit package.

Be sure to add the weather:bit package as instructed in the Installing the weather:bit Package in MakeCode section of this tutorial.

Now, you can either download the following example script and drag and drop it onto your micro:bit, or use it as an example and build it from scratch in MakeCode.

Note: If this is your first time programming a micro:bit, please be sure to see our Getting Started with the micro:bit tutorial on how to get the MakeCode program onto your micro:bit.

Code to Note

Code to Note Exp 1

Start Weather Monitoring

When the script starts, we use this block to start or initiate the BME280 sensor and get it ready to take readings. Anytime you want to use the temperature, humidity, pressure or altitude blocks, you need to have this block in your on start block.

Set Item To

We use a variable called item to keep track of which data are being displayed on the LED array. If item is equal to 0, it shows the temperature; if 1, it shows the humidity; if 2, the pressure. If the variable goes over 2, we reset it to 0. We increment the variable by pressing the A button.

Temperature (°C)

This variable returns a number that you then have to divide by 100 to get the temperature in Celsius.

Humidity

This variable returns a number that you need to divide by 1,024 to get the relative humidity.

Pressure

This variable returns a number that you divide by 25,600 to get the atmospheric pressure in hPa.

Why All of the Math?

This is a good question! It all comes down to accuracy of the data that you receive. MakeCode cannot handle floating point numbers (numbers with decimal points) yet. Which can be troublesome for getting really accurate readings from the BME280 with a single variable block. So, to as accurate of values as possible you have to do some math in the programming environment. We know, not fun! But, hey now you might pay attention in math class a bit more now.

What You Should See

Once your code is loaded, you should start to see numbers scroll across the LED array on your micro:bit, beginning with the temperature in Celsius. If you press the left button on your micro:bit, the number will change to percent humidity; press it again, and it will be pressure. Pretty cool…well, hmmm…maybe warm?

Exp1_Powered

Troubleshooting

  • weather:bit blocks not showing up— Make sure you have a network connection and have added the package to your MakeCode environment.

  • micro:bit not showing up— Try unplugging the USB cable and plugging it back in. Also, be sure that you have the cable inserted all the way into your micro:bit.

  • atmospheric data seems odd— Make sure that the BME280 is free from contact with sources of heat and/or moisture (for example, having your finger over the top of it).

Experiment 2: Reading the Light Level

Introduction

Light conditions are a huge part of the weather. The great thing is that the weather:bit doesn’t have a light sensor. No, we didn’t miss a typo! The weather:bit doesn’t have a light sensor. Why not? Because the micro:bit has one already! In this experiment you will measure the light around you and have the micro:bit “graph” it

Parts Needed

For this experiment you actually don’t need the weather:bit carrier board, so we left it out. But feel free to leave it attached to your micro:bit if you so choose.

  • 1x micro:bit board (Not included)
  • 1x micro-B USB cable (Not included)
micro:bit Board

DEV-14208
14.95
USB Micro-B Cable - 6"

CAB-13244
1.95
3

Suggested Reading

Hardware Hookup

Again, the hardware hookup here is minimal! Plug your micro:bit into your computer with the USB cable, and you are good to go!

micro:bit connected via USB

Running Your Script

Please open a browser window and navigate to makecode.microbit.org. This should open the MakeCode environment that you used to install the weather:bit package.

Code to Note

Code to Note Exp 2

Set lightVal To

We read the light level in the area using the light level block and store it in a variable called lightVal. This is the value that we can compare against the calibration value you captured at the beginning of your script.

Plot Bar Graph Of

This block is fun! It accepts two values: the value of what you want to graph and a maximum value of that variable. In this case we want to graph lightVal, and it has a maximum value of 255. This will create a “bar graph” of the light value on your micro:bit.

What You Should See

You should see the LED array light up as a graph based on how bright it is wherever you are. Turn out the lights or pass your hand over the array, and the graph should react. Pretty sweet! You now have a way to measure the light value as well as another way to display data with the micro:bit.

Exp2 Powered

Troubleshooting

  • odd light readings— Make sure you are not leaning over the micro:bit, your shadow will impact the sensor reading.

  • The arrows threshold is odd— Try resetting the micro:bit while you are not leaning over it or casting a shadow on it.

Experiment 3: Reading the Soil Moisture

Introduction

How wet is the ground? It is actually an important question to ask if you are thinking about growing plants, digging a hole, or even walking across your yard. Enter the soil moisture sensor. In this experiment you will hook up the soil moisture sensor and use it. You will display different images on your micro:bit based on the moisture level of the soil.

Parts Needed

  • 1x micro:bit board (Not included)
  • 1x weather:bit carrier board
  • 1x micro-B USB cable (Not included)
  • 3x 12" M/M jumper wires
  • 1x SparkFun Soil Moisture Sensor
micro:bit Board

DEV-14208
14.95
SparkFun Soil Moisture Sensor

SEN-13322
4.95
9
SparkFun weather:bit

DEV-14214
14.95
USB Micro-B Cable - 6"

CAB-13244
1.95
3
Jumper Wires Premium 12" M/M  Pack of 10

PRT-09387
4.5

Suggested Reading

About the Moisture Sensor

pic of soil sensor

The SparkFun Soil Moisture Sensor is a simple breakout board for measuring the moisture in soil and similar materials. The soil moisture sensor is straightforward to use. The two large, exposed pads function as probes for the sensor, together acting as a variable resistor. The more water that is in the soil, the better the conductivity between the pads will be, which will result in a lower resistance and a higher SIG (output voltage).

To get the SparkFun Soil Moisture Sensor functioning with your weather:bit, all you need to do is connect the VCC, GND and SIG pins to the weather:bits VCC, GND and SIG screw terminals. You will receive a SIG out, which will depend on the amount of water in the soil. Oh, and you’ll also need a bit of dirt in a pot to test it all out!

One commonly known issue with soil moisture sensors is their short life span when exposed to a moist environment. To combat this, we’ve had the PCB coated in gold finishing (ENIG, or Electroless Nickel Immersion Gold).

Hardware Hookup

Hooking the moisture sensor up to the weather:bit is relatively easy. You will need a screwdriver with a small bit, preferably a jeweler’s screwdriver or our pocket screwdriver.

Pocket Screwdriver Set

TOL-12891
3.95
3

Start by using the screwdriver to open the three screw terminals on the moisture sensor enough that you can insert the ends of the jumper wires into them. Next, insert three jumper wires into the screw terminals using Red for VCC, Black for GND and Yellow for SIG. Tighten the screws down so that the wires will not come loose.

mositure sensor wires

Next, do the same thing for the screw terminals for the moisture sensor port on the weather:bit. Open the screws enough that you can insert the jumper wires with Red to VCC, Black to GND and Yellow to SIG. Tighten the screws enough to hold the wires in place.

Exp3_Hookup | soil mositure sensor wires

With that, you are done hooking the moisture sensor up!

Running Your Script

Please open a browser window and navigate to https://makecode.microbit.org. This should open the MakeCode environment that you used to install the weather:bit package.

Code to Note

Code to Note Exp 3

Soil Moisture

The Soil Moisture block returns an analog value range of 0 - 1023 (a 10 bit number). The lower the number is the less moisture the sensor detects. The “dryness” and “wetness” level depends on your climate, humidity, etc. so we cannot give you a concrete range of what is wet and dry, that is something you will have to fiddle with yourself.

If / Else If / Else

We used an if then block to create some logic that changes based on the soil moisture detected by the sensor. If the moisture value is low the LED array shows an angry face, if just right a smiley face and if too wet and frown.

To add more else / else if options to your if statement click on the small gear and build your state tree using the block interface presented.

Show Icon

The Show Icon block is really useful when you want to display a simple image or icon on the LED array. You can select from a number of premade images from the pull down menu in the block.

What You Should See

Based on our extensive testing (me pouring water into a pot of soil with the sensor stuck in it), we defined dry, damp and wet states. The image below shows the experiment powered up to test the plant’s soil.

Exp3_FinalAssembly | moisture sensor and output

When you insert your sensor into a potted plant of your own and run your script, you will see an icon show up on your micro:bit. If you get an angry face, your soil is too dry; a sad face means it is too wet; and finally, a happy face is “moist” and just right. Water as needed to keep your plants “happy.”

Exp3_FinalAssemblyPlant | moisture sensor in a plant and output

You may need to adjust the numbers in your code to match the state of preference for your house plants!

Troubleshooting

  • Odd readings— Make sure your wiring is correct, if you wire the sensor backwards it will give backwards results.

  • I never get a “happy” face— Try playing around with the threshold values in your if statements to find a range that works for your application.

  • It still doesn’t workDrop us a line, we would love to help you figure it out!

Experiment 4: Reading the Soil Temperature

Introduction

When you are looking to put plants in the ground in spring, plant seed, or even track the temperature of your koi pond, you need a temperature sensor. But not just any temperature sensor…a waterproof one! In this experiment you will explore using the waterproof temperature sensor to measure ground temperature in a garden or pot.

Parts Needed

  • 1x micro:bit board (Not included)
  • 1x weather:bit carrier board
  • 1x micro-B USB cable (Not included)
  • 1x Waterproof Temperature Sensor
Temperature Sensor - Waterproof (DS18B20)

SEN-11050
9.95
19
micro:bit Board

DEV-14208
14.95
SparkFun weather:bit

DEV-14214
14.95
USB Micro-B Cable - 6"

CAB-13244
1.95
3

Suggested Reading

Hardware Hookup

The hookup of this sensor is much easier with the weather:bit carrier board than with any other microcontroller. We have done a lot of the leg work for you!

Find the screw terminals for the soil temperature on the weather:bit. Using your screwdriver, open the screw terminals a bit and insert the wires as shown in the photo below with the wires from left to right:

  • Red to VCC
  • White to SIG
  • Black to GND

Exp4_Hookup | hookup of temp sensor

Running Your Script

Please open a browser window and navigate to https://makecode.microbit.org. This should open the MakeCode environment that you used to install the weather:bit package.

Code to Note

Code To Note Exp 4

Soil Temperature

The Soil Temperature block returns the soil a value that you need to divide by 100 to get the temperature in Celcius. Like the data from the BME280 sensor in Experiment 1, this is to get you the most accurate temperature possible.

Set Item To

In this Set Item To block we use a boolean variable of true. You can then flip flop that variables to false when needed

Not

We use the not block to flip flop a boolean variable when needed. In this case when a button is pressed.

Show String

The Show String Block enables you to display a scrolling string of character across the LED array.

Show Number

As in previous experiments we use the show number block to display the temperature data from the soil temperature sensor.

What You Should See

As soon as you power up your micro:bit, you should see the ground temperature from the temperature sensor scrolling across the LED array in Celcius. If you press the A button, it will change what is scrolling to a “Plant” or “Don’t Plant” depending on the temperature of the ground making it a useful tool for when to figure out when it is time to plant your tomato crop.

Exp4_FinalAssembly | Temperature setup

Note: The actual temperature sensor is at the end of the long wire. Make sure that is in place where you want to take temperature readings; otherwise you may get odd values.

Troubleshooting

  • Odd temperature— Make sure you are measuring with the end of the temperature sensor, that is where the actual sensor is.

  • Really odd temperature— Double check your wiring and hookup!

  • Numbers still seem odd— Check your math blocks! You may be missing an order of operation.

Experiment 5: Reading the Wind Direction and Speed

Introduction

The winds are a-blowin'! The question is, which direction and how hard? In this experiment you will assemble, hook up and program your weather:bit to read the weather meters — more specifically, the wind anemometer (wind speed) and directional vane. We will again use the micro:bit’s LED array to display the wind speed or the direction.

Parts Needed

  • 1x micro:bit board (Not included)
  • 1x weather:bit carrier board
  • 1x micro-B USB cable (Not included)
  • 1x Weather Meter
Weather Meters

SEN-08942
76.95
20
micro:bit Board

DEV-14208
14.95
SparkFun weather:bit

DEV-14214
14.95
USB Micro-B Cable - 6"

CAB-13244
1.95
3

Suggested Reading

Introducing the Weather Meter (Anemometer and Vane)

The anemometer on the weather meter is the propeller-looking thing that got lost in a ping-pong ball factory.

Anemometer

It has three cups that catch the wind, which then cause it to spin. As the head spins, a magnet at the center of the hub travels over a reed switch that closes the circuit to the pin that the sensor is connected to for a brief moment. The faster the wind is, the faster the anemometer spins and the faster and more often the reed switch is triggered.

We count the number of times that the reed switch is triggered every second, and we can calculate the wind speed from that (1 click per second is roughly 1.5mph).

We did the hard work on this one in terms of simplifying all of this for you. All you need to know is that an anemometer is a wind-speed sensor.

The wind vane is the arrow-looking thing that spins.

Wind Vane

When the wind blows, it catches the vane, which points in the direction that the wind is coming from. As the vane moves around, it closes a series of switches inside, which produce a different resistance at 16 different locations around the hub. Each direction has a specific value that we have mapped to the cardinal directions once you have it set in the location you want it. In the makeCode package the Wind Direction block will return N,NE,E,SE,S,SW,W,NE directions as a string.

Hardware Hookup

To help you out in the assembly of your weather meter we have created this step by step assembly guide.

New!

Weather Meter Hookup Guide

July 20, 2017

How to assemble your very own weather meter!
Note: Once you have assembled your weather meter we highly recommend labeling the two cables for the wind and rain sensors. This will make your life much easier in the long run!

Once you have completed the assembly of the weather meter, find the cable for the wind sensors and plug it into the RJ-11 connector on the weather:bit labeled “wind”.

wind

With that you are ready to roll!

Running Your Script

Please open a browser window and navigate to https://makecode.microbit.org/. This should open the MakeCode environment that you used to install the weather:bit package in.

Code to Note

Code to Note Exp 5

Start Wind Monitoring

The Start Wind Monitoring block starts all of the necessary processes to use the wind sensors that plug into the weather:bit. This block show be placed in the On Start block as it only needs to be called once at the very beginning of the program.

Show Number

The Show Number block displays/scrolls whatever number is placed inside of it across the LED array. We use it to display the wind speed in this example.

Wind Speed

The Wind Speed block is a variable block that returns the calculated wind speed from the anemometer. It is updated every 2 seconds!

Show String

The Show String block is similar to the Show Number block in that it displays/scrolls whatever string that it is passed. In this case we use it to display the wind direction.

Wind Direction

Last but not least, the Wind Direction block is a variable block that returns a string value of a cardinal direction that the wind vane is pointing.

What You Should See

Once you power up the micro:bit, spin the anemometer with your hand or place it in front of a fan. The speed in miles per hour should start to scroll across the LED array. If you press the A button on your micro:bit, it will change the readout to print the direction the vane is pointing as the direction the wind is coming from.

Note: Be sure to set your vane so that N on the micro:bit reading is true north for this reading to be accurate.

Exp5_FinalAssembly

Troubleshooting

  • odd readings— Make sure your wiring is correct, make sure the correct sensors are plugged into the correct RJ11 jack.

  • What is north?— The directions produced by the weather:bit are based off of readings from the vane, you have to personally line up the orientation of your vane to north.

  • It still doesn’t workDrop us a line, we would love to help you figure it out!

Experiment 6: Reading the Rain Gauge

Introduction

Rain, rain, go away; come again another day! In this experiment you will add the rain gauge to your weather meter and use it to track the amount of rain that falls. In the end you will use the micro:bit to keep track of the amount of rain, print it out over the LED array when a button is pressed and then use another button press to reset that value to 0. Ready to get wet? Us too…

Parts Needed

  • 1x micro:bit board (Not included)
  • 1x weather:bit carrier board
  • 1x micro-B USB cable (Not included)
  • 1x Weather Meter
Weather Meters

SEN-08942
76.95
20
micro:bit Board

DEV-14208
14.95
SparkFun weather:bit

DEV-14214
14.95
USB Micro-B Cable - 6"

CAB-13244
1.95
3

Suggested Reading

Introducing the Weather Meter (Rain Gauge)

In the previous experiment you met the wind sensors on the weather meter. Here you meet the rain gauge!

Rain Gauge

The rain gauge is actually quite an ingenious design. Inside of the box is a tiny bucket. When that bucket is full (0.011" of rain) it tips over, both triggering a switch and dumping out the water that is in the bucket, which then allows the bucket to come back to upright. So, for every switch press there is 0.011" of rain. In software we count these triggers and increment the rainfall value.

Hardware Hookup

If you didn’t assembly your weather meter in the previous experiment we created this step by step assembly guide for you to follow!

New!

Weather Meter Hookup Guide

July 20, 2017

How to assemble your very own weather meter!
Note: Once you have assembled your weather meter we highly recommend labeling the two cables for the wind and rain sensors. This will make your life much easier in the long run!

Once you have completed the assembly of the weather meter, find the cable for the rain gauge and plug it into the RJ-11 connector on the weather:bit labeled “rain”.

rain

Hope you have an umbrella!

Running Your Script

Please open a browser window and navigate tohttps://makecode.microbit.org. This should open the MakeCode environment that you used to install the weather:bit package.

Code to Note

Code to Note Exp 6

Start Rain Monitoring

To use the rain gauge you need to add the Start Rain Monitoring block to your On Start Block for it to be able to function correctly. It sets up the micro:bit hardware correctly to be able to read the rain gauge correctly.

Rain

The rain block returns the number of inches of rain that the gauge has measured as a whole number. This variable block stores that value until your micro:bit is reset or power cycled (turned off and on again).

Show LEDs

We used the Show LEDs block to draw an image of the sun. If MakeCode doesn’t have just the right icon for you pre-drawn you can make your own using this method.

Reset

The reset block resets the code that you have on your micro:bit. This is the same as pressing the reset button on the back of the micro:bit, but at times it is useful to be able to do this in software. A great example would be that you couldn’t reach the back of the micro:bit for some reason.

What You Should See

Once you power up your micro:bit, you should see a sun show up on the LED array. Once the amount of rain fallen goes over 1" the LED array will display an umbrella and every 10 seconds the number of inches of rain fall since you started your program.

Exp 6 Final Assembly

To restart the counter, press the A button or, if you can reach it, the reset button on the back of the micro:bit.

Troubleshooting

  • I am getting a lot or rain?— Every time the bucket tip, it is measured as rainfall. If you bump into the sensor or if it is vibrated it may trigger the sensor and you get a false reading.

  • Getting an Odd reading?!— Make sure the rain gauge is plugged into the proper RJ11 jack and there is a “click” when you insert it all the way.

  • It still doesn’t workDrop us a line, we would love to help you figure it out!

Experiment 7: Logging to the MicroSD Card

Introduction

We are almost done with our whirlwind series of weather experiments. In this final experiment we will look at how to log all of this amazing weather data to a microSD card using the OpenLog.

Parts Needed

  • 1x micro:bit board (Not included)
  • 1x weather:bit carrier board
  • 1x micro-B USB cable (Not included)
  • 1x OpenLog (with headers)
  • 1x microSD card (NOT INCLUDED WITH THIS KIT)
SparkFun OpenLog

DEV-13712
14.95
17
micro:bit Board

DEV-14208
14.95
SparkFun weather:bit

DEV-14214
14.95
USB Micro-B Cable - 6"

CAB-13244
1.95
3
MicroSD Card with Adapter - 8GB

COM-11609
13.95
2

Suggested Reading

Introducing the SparkFun OpenLog

OpenLog

The OpenLog Data Logger is a simple-to-use open source solution for logging serial data from your projects. The OpenLog provides a simple serial interface to log data from a project to a microSD card.

The primary interface with the OpenLog is the FTDI header on the board edge. This header is designed to plug directly into the weather:bit carrier board’s serial port, which allows the micro:bit to send data over a serial connection to the OpenLog.

Header

There are two status LEDs on the OpenLog to help you with troubleshooting.

  • STAT1— This blue indicator LED toggles on/off when a new character is received. This LED blinks when serial communication is functioning.
  • STAT2— This green LED is connected to Arduino D13 (SPI Serial Clock Line/ATmega328 PB5). This LED only blinks when the SPI interface is active. You will see it flash when the OpenLog records 512 bytes to the microSD card.

Stat LEDs

Hardware Hookup

You are going to love this! First thing is that you need to insert a microSD card into the OpenLog with the text side “up” as shown in the image below.

Exp7_HookUp1 | Adding a microSD card

Make sure the card “clicks” into place and stays in place.

Exp7_HookUp2 | microSD card inserted OpenLog

Next insert the OpenLog’s pins into the serial port on the weather:bit carrier board as shown below. Make sure that all of the pins are aligned and inserted correctly. Offsetting these pins could end in damaging your OpenLog or micro:bit. Finally, if you haven’t already, plug your micro:bit into the weather:bit. With that you should be good to go!

Exp7_HookUp3

Running Your Script

Please open a browser window and navigate tohttps://makecode.microbit.org. This should open the MakeCode environment that you used to install the weather:bit package.

Code to Note

Code to Note Exp 7

Serial Redirect To

We use the Serial Port on the weather:bit board to write data to the SparkFun OpenLog. To do this we need to do some setup for the micro:bit to use it correctly. We do this through the Serial Redirect To block placed in our On Start block.

In the Serial Redirect To block we set the transmit (TX) and receive (RX) pins. In this case we use pins 15 and 14. We also set the baud rate which is the rate at which two devices “agree” to communicate at. The OpenLog is preprogrammed to communicate at 9600 baud, so that is what we will set it at.

Join

The join block is one of the most useful blocks out there. You use it to join pieces of data together to build a long string that you then store in a variable. For example for our header we stored comma separated names as a single variable called header. The join blocks standard size is 2 slots. To add more slots click on the gear button and drag more slots in place as you have with the if / else if statements in previous experiments.

Serial Write Line

To send data to the OpenLog we use the Serial Write Line block. This command sends whatever data you attach to it over the serial lines you have specified in your Serial Redirect to block with a carriage return at the end of it.

Running Time(ms)

The running time block returns the number of milliseconds that the micro:bit has been powered up and running the current program. We are using it as a timestamp for data logging since there is no access to a realtime clock.

What You Should See

When you power your micro:bit, you will eventually see an “X” on the LED array. Press the A button to start logging data every 30 seconds. A check mark will be displayed on your LED array. Let the program run for a couple of minutes and press the A button again. You will see an “X” again. It is now safe to remove the microSD card from the OpenLog.

Exp 7 Powered without X

Now, using the microSD card slot on your computer or an adapter, open up the microSD card on your computer. You should see two files. One is a config file, which you can ignore. The other, which has a file name of “LOGXXXXX.txt,” is what you are looking for; go ahead and open it.

openlog files

The data in this text file is a Comma Separated Value (CSV) set of the data you sent it. The format is that the first line is the “header,” which is the name of each “column.” You see that our header is the following:

time,temperature,humidity,pressure,altitude

The header is followed by lines of values associated with each reading.

In fact, if you are a user of Google Sheets you can import this text file as a CSV and then graph these values pretty easily. We recommend this quick guide from Google on how to import a .txt file as a CSV into sheets.

Troubleshooting

  • Doesn’t seem to be logging— Make sure your openLog is oriented correctly in the Serial port

  • The log has weird characters—Make sure you have the serial baud rate set to 9600!

  • It still doesn’t workDrop us a line, we would love to help you figure it out!

Resources and Going Further

We produce a number of other kits and carrier boards that you can hook up to your micro:bit to help take your projects to the next level. Here is some further reading that may help you along in learning more about the world of electronics.

For more information on our micro:bit ecosystem, check out these tutorials:

New!

SparkFun Inventor's Kit for micro:bit Experiment Guide

The SparkFun Inventor’s Kit for micro:bit Experiment Guide is your map for navigating the waters of beginning embedded electronics, robotics and citizen science using the micro:bit. This guide contains all the information you will need to explore the 12 circuits of the SparkFun Inventors Kit for micro:bit.
New!

Micro:Arcade Kit Experiment Guide

We love games! We love writing games, building games and yes, even building game consoles. So we want to introduce to you the micro:arcade kit for the micro:bit!

micro:bit Breakout Board Hookup Guide

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

For more Internet-connected weather fun, check out our these other weather data tutorials.

Weather Station Wirelessly Connected to Wunderground

Build your own open-source, official Wunderground weather station that connects over WiFi via an Electric Imp.

Photon Weather Shield Hookup Guide V11

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

Arduino Weather Shield Hookup Guide V12

Read humidity, pressure and luminosity quickly and easily. Add wind speed, direction and rain gauge for full weather station capabilities.
New!

ESP32 Environment Sensor Shield Hookup Guide

SparkFun's ESP32 Environment Sensor Shield provides sensors and hookups for monitoring environmental conditions. This tutorial will show you how to connect your sensor suite to the Internet and post weather data online.

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


Micro:Arcade Kit Experiment Guide

$
0
0

Micro:Arcade Kit Experiment Guide a learn.sparkfun.com tutorial

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

Introduction to the micro:arcade Kit

We love games! We love writing games, building games and yes, even building game consoles. So we want to introduce to you the micro:arcade kit for the micro:bit!

The kit includes our gamer:bit carrier board for the micro:bit, which gives you access to a number of pins through the form of buttons in a classic game controller layout. But, that isn’t all!

It’s one thing to design a “game controller,” but what about building a console? A joystick, buttons to mash…the things that make us hard-core arcade fans drool and daydream. This kit is designed for you! The kit includes all of the parts you need to take this lowly controller breakout to a pinball wizard’s dream!

Included Materials

Below is all the parts included in the SparkFun micro:arcade kit.

SparkFun micro:arcade kit

KIT-14218
49.95

The kit includes the following parts:

  • SparkFun gamer:bit— The carrier board for the micro:bit that turns it into a handheld controller, game or other tool.
  • Arcade Joystick— Old-school arcade joystick that uses digital switched for directions.
  • Red Concave Button— Mash away!
  • Blue Concave Button— Jump!
  • Yellow Concave Button— Game over!
  • Green Concave Button— For firin' the laser!
  • micro:bit Battery Holder— Unique 2XAA battery holder built specifically for the BBC micro:bit
  • Spade Connector Wires (Qty: 16)— 24 AWG 3 ft wires with a female insulated spade connector at one end and a braided wire lead at the other to connect the arcade buttons and joystick to the gamer:bit
Note: The kit comes with everything you need to build a game or controller console. But you will need to supply your own micro:bit and USB cable.
micro:bit Board

DEV-14208
14.95
USB Micro-B Cable - 6"

CAB-13244
1.95
3

How to Use This Guide

We wanted to note that this guide is designed to get you started with the gamer:bit board and the SparkFun micro:arcade kit in a straightforward and simple way. We demonstrate each component’s functionality and the corresponding code to make it work.

While you explore this guide, we urge you to take your time and tinker with the sensors, code and the ideas shared to build something tailored to your application and creativity. Our goal is to get you enough information and know-how to make you dangerous and then release you into the wild.

Be sure to share your projects with us over Twitter or Facebook! We are excited to see you Start Something!

Suggested Reading

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

What is a Circuit?

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

Getting Started with the micro:bit

The micro:bit is a compact, powerful programming tool that requires no software installation. Read on to learn how to use it YOUR way!

Open Source!

All of our experiments and guides are licensed under the Creative Commons Attribution Share-Alike 4.0 Unported License. Feel free to remix and reuse our work. But please, share the love and give us attribution for our hard work!

To view a copy of this license visit this link, or write: Creative Commons, 171 Second Street, Suite 300, San Francisco, CA 94105, USA.

Hardware Overview

The gamer:bit is a carrier board for the micro:bit. It is similar to an Arduino shield by adding functionality to the micro:bit without the hastle of a number of other boards, components, and all of those jumper wires connected to a breadboard.

Product Photo

In this case, the gamer:bit takes your normal run of the mill micro:bit and turns it into a fully functional game system with a few extra parts to take your game experience to the next level. Let’s take a closer look at the gamer:bit!

Edge Connector

The gamer:bit connects to the micro:bit via an edge pin connector in the center of the board. This makes it handy to swap out micro:bits for programming, but also gives reliable connections to all of the different pins on the micro:bit. Make sure that you insert the micro:bit correctly with the LED array facing up!

Edge Connector

Direction Buttons

The gamer:bit is designed around a classic game controller which means ther is a familiar “D Pad” style button layout on the left hand side of the board. The pins that each button controls are labeled on the board.

Direction Buttons

  • UP => P0
  • RIGHT => P1
  • DOWN => P8
  • LEFT => P2

Action Buttons

There are two action buttons.

Action Buttons

Let’s name them X and Y buttons. Sorry to those used to the classic style naming, but A and B are already referenced with the buttons on the micro:bit. These buttons have no specific use other than what you program them to be. They are connected to the following pins:

  • X (LEFT FUNCTION) => P12
  • Y (RIGHT FUNCTION) => P16

Poke-Home Connectors

On the back of the gamer:bit you will notice some odd plastic connectors. These are called poke home connectors. Each one corresponds to a button on the back of the board and are labeled as such. You will end up using these to connect your external components to gamer:bits buttons. Each button has two pins to it, one for each wire to connect to the button and component.

Poke Home Connectors

With that, you are ready to start! Are you a user? We hope you have your chips, energy drink and eye drops because this is going to be a marathon!

Installing the gamer:bit Package for Microsoft MakeCode

To make the most out of the gamer:bit with the least amount of coding, use the MakeCode package we wrote for the gamer:bit board.

Packages?

If you have used Arduino before, you probably know about a thing called a library; which is a collection of code that extends the functionality of the core programming language. MakeCode packages work the same way.

There are some amazing differences between Arduino libraries and MakeCode packages. One of them is that MakeCode packages include JavaScript functions, which you can use when programming in text, as well as all of the blocks you need to program using the block method. This makes learning and using new packages straightforward and shortens the time to awesome when setting out to build the project of your dreams.

Installing a MakeCode Package

To install or add a new package to your MakeCode toolbox (the list of different block groups), click on “Advanced” and then on “Add Package.”

Screenshot Installing MakeCode Package

From here you can search for “SparkFun gamer-bit,” and it should show up as a public package in the list. Go ahead and click on it.

Screenshot Makecode gamer:bit

This will add all of the blocks to your toolbox. In general, this is a bit tricky as, depending on how the package was written, it may either have its own toolbox or just add blocks to the existing ones. Take a look at your toolbox; for the gamer:bit you should see…

Screenshot gamer:bit installed

Great! You have now installed the gamer:bit package and are ready to use the board as well as the components that come in the micro:arcade kit. As a side note, for every new MakeCode project that you make, you will have to load packages over again. Not a big deal, but noteworthy! Now, let’s put your package to good use and get your game on!!!

Experiment 1: Basic Use of The Gamer:bit

Introduction

We take buttons for granted! We press the keyboard in front us all day long, we use game controllers until they ware out and we never really think about what goes on behind the scenes in terms of programming or even in the hardware circuit. In this initial experiment, you will hookup your micro:bit to the gamer:bit and test the buttons to make sure everything is up and running and your first introduction to the game command blocks in Microsoft MakeCode.

Parts Needed

  • 1x micro:bit*
  • 1x micro-B USB Cable*
  • 1x gamer:bit carrier board

*Not included in the micro:arcade kit

Didn’t Get the micro:arcarde Kit?

If you are conducting this experiment and didn’t get the micro:arcade Kit, we suggest using these parts:

micro:bit Board

DEV-14208
14.95
USB Micro-B Cable - 6"

CAB-13244
1.95
3
SparkFun gamer:bit

DEV-14215
9.95

Suggested Reading

Introduction to the button

Buttons are part of our everyday lives! They are an actuator that closes, or completes a circuit when you press it and sometimes release it.

The buttons on the gamer:bit are called momentary push buttons, meaning that they are only actuated or complete the circuit when you are physically pressing them. These types of buttons are great for things that you want to happen quickly, for example trigger a character to jump or chime in during a game show. The image below highlights one of the buttons that we will be using in this experiment.

UpP0

Behind the button itself you also need to realize that a button is read by a pin on your micro:bit. That pin reads whether it is HIGH or LOW, ON or OFF, 1 or 0. A pin being pulled HIGH is 3.3 volts being applied to it, while LOW is 0 volts, or grounded. A button actuation can either pull the pin HIGH or LOW depending on how it is wired as well as the program running on your micro:bit.

Hardware Hookup

The only hardware hookup at this point is inserting your micro:bit into the gamer:bit correctly! Insert your micro:bit with the LED array facing up (the same direction as all of the buttons).

micro:bit insertion

Note: The edge connector for the micro:bit is not keyed, so there is the potential for the micro:bit to be inserted backwards. Be sure to check the orientation of the board and micro:bit before plugging it in!

Running Your Script

We are going to use Microsoft MakeCode to program the micro:bit. Please open a browser window and navigate to makecode.microbit.org. This should open the makeCode environment that you used to install the gamer:bit package in.

MakeCode Program

Be sure to add the gamer:bit package as instructed in the Installing the gamer:bit Package in MakeCode section of this tutorial.

Now, you can either download the following example script below and drag and drop it onto your micro:bit, or use it as an example and build it from scratch in Microsoft MakeCode.

Note: If this is your first time programming a micro:bit please be sure to see our Getting Started with the micro:bit tutorial on how to get your MakeCode program onto your micro:bit.

Code to Note

Let’s take a look at the code blocks in this experiment.

Code to Note

If you are having a hard time viewing this code, click on the image above to get a better look!

Create Sprite at

The “players” or “objects” in a video game are called sprites. On the micro:bit, sprites are a single LED in the LED array that you can control. You create a sprite by creating a variable in MakeCode.

You can create a variable under the Variables drawer and use the “Make a Variable” option and name it. We named our variable player. To initially create our sprite in the On Start block, we set the variable to Create Sprite at block and pass it an x and y value.

The coordinate system of the micro:bit’s LED array starts at the top left of the array. The variable for x increases as you move from left to right (from 0 to 4). The variable fory increase from the top to the bottom (from 0 to 4). We set our sprite to the location 2,2 which is the center of the LED array.

Gamer:bit On

To move our sprite around the tiny screen, we read if the D-Pad (direction buttons) are being clicked (i.e. pressed and then released) or not. We track these button clicks using an event block from the gamer:bit toobox drawer that is only triggered when you interact with a specific button on the gamer:bit,. This block is called the Gamer:bit On block. You can track any of the buttons / pins on the gamer:bit as well as using following event types:

  • DOWN - If the specified button is UP or being held down
  • UP - If the specified button is UP or when it is released
  • CLICKED - If the specified button has been pressed AND released.

[SPRITE] Change by

Under the game:bit toobox drawer, there are a number of blocks to help you manipulate or change your sprite. A basic one to start out with is the [SPRITE] Change by block. This block allows you to change x, y, direction, brightness, or blink of a sprite by a number. We use this block to change the X and Y coordinates and move the sprite around.

If we change the Y coordinate of the sprite by -1 it will move up one spot. A positive 1 will move the sprite down. For the X coordinate, positive 1 is moving to the right and -1 is to the left.

What You Should See

Once your code is loaded, you should press the direction buttons on the D-pad. As a result, your sprite should move around the screen. Pretty sweet! You have built something that is a pretty good start to a possible game.

Final Assembly | pressing a button

Troubleshooting

  • gamer:Bit blocks not showing up - Make sure you have a network connection and you have added the package to your MakeCode environment.

  • micro:bit not showing up on my machine - Try unplugging the USB cable and plugging it back in. Also, be sure that you have the cable inserted all the way into your micro:bit

  • Button events don’t seem right?! - Make sure that you have specified the correct direction to the correct direction of the X and Y coordinates.

Experiment 2: Button Reaction Timer

Introduction

You learned about reading button presses in Experiment 1 and event blocks. But, there is a bit of a problem with reading buttons that way… Events cannot be used as a variable in a simple way (similar to just reading a pin on its own). If for some reason you want to be able to read a combination of blocks at one time, or in this case use the state of a button with some other type of logic you actually need to use the Button variables that come with the gamer:bit package. You will be building a reaction timer to test how sharp your wits really are!

We will also be adding an external button to gamer:bit to give it a bit of an arcade feel!

Parts Needed

  • 1x micro:bit*
  • 1x micro-B USB Cable*
  • 1x gamer:bit carrier board
  • 1x Arcade Button
  • 2x Spade Wire Connectors

*Not included in the micro:arcade kit

Didn’t Get the micro:arcarde Kit?

If you are conducting this experiment and didn’t get the micro:arcade Kit, we suggest using these parts:

micro:bit Board

DEV-14208
14.95
USB Micro-B Cable - 6"

CAB-13244
1.95
3
Concave Button - Red

COM-09336
1.95
1
Spade Connector Wire - 3ft, Female (2 Pack)

CAB-14166
1.95
SparkFun gamer:bit

DEV-14215
9.95

Suggested Tools

  • Ball point pen
  • Hobby knife or scissors

Suggested Reading

Introduction to the Arcade Buttons

The classic arcade button! Oh how we love them.

Red Arcade Button

The arcade buttons work two ways as either a normally closed (NC) switch or as a normally open (NO) switch. That is to say that you can pick whether pressing the button completes, or closes the circuit. Or, breaks the circuit from a closed, or “on” state.

Micro Switch

The back of each button has a the actual switch with 3 tabs. One is common or “COM” which you will always use and then either “NO” or “NC”. In this case, we will be using Normally Open, but there are times where you could use Normal Closed as well.

Hardware Hookup

You will be hooking up one of the arcade buttons to the UP direction pad. You can then mount the button in a cardboard box or any other panel you like. The cardboard box that the kit came in is a good stand in for now!!

Exp2_Step1Hookup | parts laid out

We will start out by adding the disconnect wires to the button. Start by connecting one wire to the Common (COM) pin on the button. The disconnects should slide over the tabs on the buttons snugly.

Exp2_Step2Hookup | closeup of adding a disconnect to COM

Next, for each button add another wire to the “NO” tab, on the button, you should have two wires connected to it at this point.

Exp2_Step3Hookup | closeup of adding a disconnect to NO

The image below shows the quick disconnects added to the terminals of the microswitch.

Exp2_Step4Hookup | closeup of a button wired up

Finally, connect each set of wires to its corresponding poke-home connector by pressing down on the tab of the connector with a ballpoint pen and inserting the bare wire end. It doesn’t matter what wire goes where in this wiring configuration as long as each wire is connected to pin P0 and P1.

Exp2_Step5aHookup | closeup of a poke home being wired up

As the poke-home connector is being pressed down, insert the wire into the connector as shown below.

Exp2_Step5bHookup | closeup of a poke home being wired up

Once the wire has been inserted sufficiently into the poke-home connector, pressure from the ballpoint pen on the tab may be removed. The connector will actually hold it tight until you want to remove it. Below shows an image of the wires connected to P0 and P1.

Exp2_Step5dHookup | closeup of a poke home wired up

Note: To disconnect a wire from a pokehome connector use a ball point pen or pencil to press down on the small tab of the connector and gently tug on the wire. The wire should come out easily.

The buttons themselves are designed to be mounted to a panel made of plywood, plastic, or even through a piece of cardboard. For this project we used the box that the kit came in as a great cabinet for your reaction timer.

To start, we need to remove the microswitch from the bottom of the button by carefully prying it out of the mounting bracket. This isn’t held in place with any hardware, just molded plastic, so be careful not to break anything. With the green side of the microswitch facing toward you, you will need to push the one of the plastic pins holding it in place. Gently twist the microswitch counterclockwise with your left hand while holding the concave button with your right hand.

Exp2_Step7aHookup | removing the mech. from switch

Once the plastic pins is out of one of the holes, rotate the microswitch away from the pin as shown in the image below.

Exp2_Step7bHookup | removing the mech. from switch

Finally, slide the microswitch out by moving it out of the second molded pin.

Exp2_Step7cHookup | removing the mech. from switch

To mount the concave button, we will also need to cut a hole the cardboard box. You will need to unscrew the black ring from the concave button. In this experiment, we will be mounting the button on the top right side of the box. We can use the black ring that is attached to the concave button as a guide to cut the 1 1/8" hole. Using a pen, draw the mounting hole.

Exp2_Step6aHookup | Draw Hole with ring

Using a craft knife or pair of scissors, cut a hole inside of the lines. Make sure to not cut too much of the cardboard box.

Exp2_Step6bHookup | Hole cut in the box

Additionally, draw about a 1" square hole on the front of the box for the wires. The square was placed in the middle for the purpose of this experiment.

Exp2_Step6cHookup | Draw hole for wires

Cut the square out using the craft knife or pair of scissors.

Exp2_Step6dHookup | Cut hole for wires

Insert the microswitch with wires through the square hole.

Exp2_Step8Hookup | Place microswitch through the square hole

At this point, we can insert the concave button through the hole and thread the nut back onto the button from the bottom. The cardboard will be sandwiched between the concave button and the threaded nut. Finally, reattach the microswitch to the bottom of the concave button.

Exp2 Final Assembly

Now, give it a good mash to test it and make sure it will hold up!

Running Your Script

Now, you can either download the following example script below and drag and drop it onto your micro:bit, or use it as an example and build it from scratch in MakeCode.

Note: If this is your first time programming a micro:bit please be sure to see our Getting Started with the micro:bit tutorial on how to get your MakeCode program onto your micro:bit.

Code to Note

Let’s take a look at the code blocks in this experiment.

Code to Note

If you are having a hard time viewing this code, click on the image above to get a better look!

RandomTime

We create a variable called randomTime and store a value that produces a random number between 1 and 5 seconds. This will be the random time it takes that a person needs to wait before the LED will turn on so it is harder to “game” the system or cheat their reaction time.

We produce that random number using the random number to block which produces a random number between 0 and a give value, we set it to 4. To make the range between 1 and 5 seconds we added 1 and multiplied that value by 1000.

While Not Gamer:bit Pressed

Once the program starts we need it to wait until the button is pressed by the person playing. To put the program in “limbo” we use a while block that reads the opposite of the gamer:bit pressed block. In other words… while the button is NOT being pressed, the program will do nothing. We use this twice; once at the beginning to start the game and a second time to capture the reaction timing.

Toggle X Y

To turn the LED in the center of the LED array on we use the Toggle X Y block. This will toggle the LED at a given X/Y coordinate. In terms of the the LED, a “toggle” changes its state from the one that it currently is in. So toggling from OFF is to turn something ON.

ZeroTime

To keep track of a reaction time we need two values to compare; a starting point and a stopping point. We capture the staring point by creating a variable called zeroTime and setting it to running time. The running time block returns the number of milliseconds that the micro:bit has been powered up and running.

StopTime

Once the button is pressed we need to capture that current time. When the button is pressed it releases the program from the while block and captures the current time again and stores it to the stopTime variable. This is done the same way as the zeroTime variable.

ReactionTime

When we have the two different variables zeroTime and stopTime, we can calculate the player’s reaction time. The reaction time is the difference between the two.

Show String / Number

We display the readout of the player’s reaction time to the player once they have finally reacted. The show string block allows you to display text across the LED array. The show number block does the same thing, but for a number.

Game Over

The game over block is an animation block found under the game:bit toobox drawer of MakeCode. It does a little animation, prints out “Game Over”, and then a score if you are using it.

What You Should See

Once your code is loaded to the micro:bit, you should see text scroll by that says “Push Me!”. Press the button and the screen will go blank. Once the single LED lights up, press the button again as quickly as possible. Your reaction time will then be displayed followed by a game over sequence.

Exp2Powered

Troubleshooting

  • Game doesn’t start right away - You have to wait for the text to finish scrolling by before the game starts.

  • Doesn’t read my button press - Make sure that you are hooked up to the correct button on the gamer:bit and that all wires are securely fastened to both the button and the board.

  • Reads a constant button press - You have the button wired to NC (Normally closed) and so it is constantly being pressed, change the connections on the back of the button to NO (Normally Open).

Experiment 3: Fun with the Joystick

Introduction

So far we have been building and programming games that either don’t have a score or require you to keep track. It is now time to pass that job off to the micro:bit. You are now going to build a simple collection game where “coins” are falling down the screen and you will control your sprite with the joystick to collect them. You will also only have 10 second before the game ends. At the end of the 10 seconds the game will be over and your score will be displayed.

Parts Needed

  • 1x micro:bit*
  • 1x micro-B USB Cable*
  • 1x gamer:bit Carrier Board
  • 1x Arcade Joystick
  • 4x Spade Wire Connectors

*Not included in the micro:arcade kit

Didn’t Get the micro:arcarde Kit?

If you are conducting this experiment and didn’t get the micro:arcade Kit, we suggest using these parts:

micro:bit Board

DEV-14208
14.95
USB Micro-B Cable - 6"

CAB-13244
1.95
3
Arcade Joystick - Short Handle

COM-09182
14.95
2
Spade Connector Wire - 3ft, Female (2 Pack)

CAB-14166
1.95
SparkFun gamer:bit

DEV-14215
9.95

Suggested Tools

  • Ball point pen
  • Hobby knife or scissors
  • 12" ruler

Suggested Reading

Meet the Joystick

The arcade joystick is the heavy duty short handled joystick that we are all familiar with from our favorite game cabinet of our childhoods (or for most of us… yesterday).

Joystick

This joystick operates as four momentary push switch, one for each direction. Each switch is opposite from the directions that it controls. For example is you press the joystick “UP” the switch on the “DOWN” side of the joystick is pressed, so you have to wire it backwards to the direction the joystick is pressed.

Bottom of Joystick

The wiring for this experiment will use the common (COM) and the Normally Open (NO) terminals on the switches.

Hardware Hookup

The hardware hookup should be pretty familiar to you in a way. The Arcade joystick uses the same type of switches as the arcade buttons with the same spade connects. Hookup a spade connector wire to each switches COM and NO terminals as shown below. For this specific game you will only need the two switches that control left and right movement.

Exp3_4xQuickDisconnects

When using the joystick or the arcade buttons, it is always a great idea to mount them to a piece of cardboard or in shoe box (the box the kit comes in is the perfect size). You can mount the joystick by cutting out mounting holes for the joystick’s frame.

To begin, remove the knob of the joystick by unscrewing it from the shaft. This also allows you to remove the black cover ring of the joystick as well.

Removing Knob

Using a Phillips head, we can remove the four screws that are holding down the frame. The SparkFun mini screwdriver was used in this experiment to remove the screws.

Knob and Ring Removed

Once the frame has been removed, we can use it to draw the mounting holes. Place the other parts in a safe location as while cutting the cardboard box.

Joystick Parts Laid Out

On the top left hand side of the box, draw the four mounting holes for the screws. Additionally, draw a hole for the shaft.

Drawing Mounting Holes

Using the mini screwdriver, carefully poke holes through the four mounting holes. A craft knife or pair of scissors can be used cut the hole for the shaft.

Cut Mounting Holes

Note: To prevent damage to the wires and concave button, you may remove the concave button, wires, and microswitch as the hole is being cut out.

Now that the mounting holes are cut, we can attach the joystick to the cardboard box. Hold the frame against the top of the cardboard box. Attach one screw through the mounting hole using one hand. Next, pass the shaft of the joystick up through the bottom of the box until one mounting hole lines up with the screw. Twist the screw in with your hand just enough to sandwich the cardboard between the joystick and the frame. Continue adding the rest of the screws to the joystick and tighten up the scerws using the mini screwdriver.

A great idea to be able to keep things straight is to label each pair of wires at the stripped ends so that when you hook it up to your gamer:bit carrier board, you don’t have to constantly tracing the wires back to the correct switch.

Exp3_Labeled1 | labeled wires for the micro:bit and joystick

Using some sticky notes, label each wire twice for the poke-home connectors labeled P1 and P2. You can slide one label close to the joystick and the other for the gamer:bit.

Exp3_Labeled2| labeled wires for the micro:bit and joystick

Hookup the stripped ends into the poke-home connectors as explained in the previous experiment by pressing down on the connector tab with a ballpoint pen, inserting the bare end of the wire into the connector, and releasing the tab. The connector will hold tight onto the wire with a snug connection. While we are at it, feel free to reconnect the concave button and label those wires.

Wires Inserted into Poke-Home Connector

Finally, you can return the black cover ring and knob to the top of the joystick. The concave button was not used in this experiment but feel free to reattach it back to the box.

Reattached Nut and Ring

Give a quick test to make sure everything works… you should feel a nice click from the switches inside the box.

Exp3_FinalAssembly

Running Your Script

You can either download the following example script below and drag and drop it onto your micro:bit, or use it as an example and build it from scratch in MakeCode.

Note: If this is your first time programming a micro:bit please be sure to see our Getting Started with the micro:bit tutorial on how to get your MakeCode program onto your micro:bit.

Code to Note

Let’s take a look at the code blocks in this experiment.

alt text

If you are having a hard time viewing this code, click on the image above to get a better look!

Create Sprite

As in the previous experiments we use the Create Sprite block. This time though we use it multiple times in the program. We create our player sprite, but also a sprite for the “gold coins” that are falling that you want to capture before they go by.

Start Countdown (ms)

The start countdown block starts a timer for the length of milliseconds. At the end of that countdown, it runs a game over animation and displays the score. This simplifies this program a lot. We would have had to program that all by ourselves.

Set Score

To make sure that you are starting with a fresh game we set the score to 0 by using the Set Score block in On Start and pass it the number 0.

Change Y by

In the forever loop, we change the y value of the gold spite by 1. This creates a falling animation after the “gold” has been created in a random place along the top of the LED array.

Touching

As the “gold” falls down, we check if the “gold” sprite is touching the “player” sprite. If it is, then the player scores and the following happens.

  1. The player scores a point.
  2. The “gold” sprite is destroyed.
  3. A new “gold” sprite is created at the top of the LED array.

If the player misses the “gold” then it passes by the player. If the Y coordinate of the “gold” is equal to 4, then it is destroyed and and a new one is created without the player gaining a point.

Score + 1

To add to a players score, we use the set score block again, but this time in a different way. We set the score to the score variable plus 1.If you wanted to hack this project and have this subtract a point, you would change the math block from addition to subtraction.

Delete

To remove a sprite from the screen, you use the delete block that will destroy the variable storing the sprite and its information.

What You Should See

When the game starts, your sprite will show up one row above the bottom of the LED array. You control your sprite with the joystick to move left and right. “Gold” will start to fall from the top of the screen and you need to move to catch it. This will go on for 15 seconds. At the end of the 15 seconds, the game will end with the “game over” sequence and display your score. Wahoo, let’s play again.

Exp3_Powered

Note: The concave button from experiment 2 was wired in the setup. However, we are not using the button because the example code is only using the joystick.

Troubleshooting

  • The direction of the joystick is opposite - It gets us all the time! Flip the wires around to the opposite side of the joystick from where they are are. Or, change the wires at the gamer:bit.

  • Nothing reacts! - Double check that your gamer:bit events are monitoring the correct pins that your joystick is wired to!

  • I can’t unhook the poke-home connector - Make sure you are using a ball point pen and pressing down on the tab. Don’t just pull on the wire!

Resources and Going Further

Here is some further reading that may help you along in learning more about the world of electronics.

Check out these other great micro:bit ecosystem tutorials from SparkFun:

New!

SparkFun Inventor's Kit for micro:bit Experiment Guide

The SparkFun Inventor’s Kit for micro:bit Experiment Guide is your map for navigating the waters of beginning embedded electronics, robotics and citizen science using the micro:bit. This guide contains all the information you will need to explore the 12 circuits of the SparkFun Inventors Kit for micro:bit.

Getting Started with the micro:bit

The micro:bit is a compact, powerful programming tool that requires no software installation. Read on to learn how to use it YOUR way!
New!

Micro:Climate Kit Experiment Guide

A weather station kit that is built on top of the inexpensive, easy-to-use micro:bit and Microsoft MakeCode. We have also written seven experiments that walk you through how to use each and every component of the kit and how to use them with the micro:bit and Microsoft MakeCode.

micro:bit Breakout Board Hookup Guide

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

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

Driving Motors with Arduino

$
0
0

Driving Motors with Arduino a learn.sparkfun.com tutorial

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

Introduction

There are 20 GPIO (General Purpose Input \ Output) pins on the standard Arduino Uno and the SparkFun Redboard. These pins are limited to driving no more than about 40 mA of current. For controlling things like motors, 40 mA is just not enough. A small hobby motor requires at least 100 - 200 mA to spin up. To do this, we need to use a circuit called a transistor amplifier.

This project has been adapted from the Circuit #12 in the SparkFun Inventor’s Kit (SIK) v3.3. We’ve updated the Fritzing diagrams and the code examples to make the connections easier to follow. The SparkFun Inventor’s Kit is a great beginners kit to introduce you to the world of physical computing and Arduino.

SparkFun Inventor's Kit - V3.3

KIT-13969
99.95
2

Required Materials

We suggest that you start with a full SparkFun Inventor’s Kit, but for this tutorial, we are going to be using the SparkFun RedBoard, but you can use any microcontroller development board you like including: Arduino, RedBoard, Photon or Teensy. The concepts covered here are universal to nearly all systems.

Hardware used in this tutorial:

SparkFun RedBoard - Programmed with Arduino

DEV-13975
19.95
5
Breadboard - Self-Adhesive (White)

PRT-12002
4.95
31
Hobby Motor - Gear

ROB-11696
1.95
4
Jumper Wires Premium 6" M/M Pack of 10

PRT-08431
3.95
2
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

COM-11507
0.95
2
Transistor - NPN (BC337)

COM-13689
0.5
Diode Small Signal - 1N4148

COM-08588
0.15

These parts are all included in the standard SparkFun Inventor’s Kit.

Suggested Reading

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

Voltage, Current, Resistance, and Ohm's Law

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

How to Use a Breadboard

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

What is an Arduino?

What is this 'Arduino' thing anyway?

Transistors

A crash course in bi-polar junction transistors. Learn how transistors work and in which circuits we use them.

Introducing the transistor

Before we jump in, let’s take a look at the transistor. We will only briefly show how the transistor works in this application. If you’re interested in learning more, we have a full tutorial on transistors here.

There are many different types of transistors; the one that we will be looking at is called an NPN BJT (Bi-Junction Transistor) transistor. The NPN describes the material properties of the device and how this devices behaves. (Note: There is also a PNP type transistor which works similarly but with different directions of current flow). A typical drawing or diagram of an NPN transistor looks like the image below.

alt text

Pin Labeling

The three legs of the transistor are labeled Collector (C ), Base (B), and Emitter (E). Depending on the manufacturer and the package type, the order of these pins may differ. It’s important to always double check the datasheets if you’re not sure. There are two very common NPN transistors used with electronics. These are the 2N2222 and the BC337.

Transistor - NPN (BC337)

COM-13689
0.5

The pin labeling and orientation is the same for both the 2N2222 and the BC337. If you look at the top of a transistor, you’ll notice that it has a shape of a capital letter D. There is one side that is curved and one side that is flat. Hold the transistor so that the pins are facing down and the flat edge faces to the left, the pins are in the same order as in the diagram above: Collector (top), Base (middle), and Emitter (bottom).

When looking at the schematic diagram for a transistor, the base is always in the middle; the emitter has an arrow pointing away (NPN transistors only), and the collector is the final un-marked pin.

How it works

Without going into too much depth on the nuances of semiconductors and quantum physics, here is a brief overview of how the NPN transistor functions. The transistor works like a switch. Imagine that there is a switch between the collector and the emitter. When the transistor is “off”, the switch is open and current is not allowed to flow from the collector to the emitter. When the transistor is turned “on”, the switch is closed and current flows from the collector to the emitter.

The base pin is used to control the transistor. When a voltage is applied to the base, the transistor turns on and current flows. The advantage of this configuration is that a low current signal from the Arduino can be used to turn the transistor on and off. The transistor works like a switch that can be used to close the circuit for a motor that is connected directly to the power supply.

Now, let’s wire this up to our Arduino.

Wiring up the circuit

Here is the schematic diagram for the circuit that we are going to wire up:

alt text

The transistor (switch) works in this circuit to close the circuit for the motor. One side of the motor is connected to 5V, the other is connected to the collector pin of the transistor, and the emitter is connected to ground. When a voltage is sensed at the base of the transistor, the transistor turns on, the switch is closed, closing the circuit for the motor circuit. Notice that the voltage for the motor comes directly from the 5V power supply.

Fly-back Diode

In this circuit, we also have a diode placed in parallel with the motor. Diodes only allow current to flow in one direction - as indicated by the arrow. This diode is often called a “fly-back” diode, and it helps to prevent damage to the transistor. As the motor starts and stops, the coils inside the motor can give create current spikes that may damage the transistor. This diode prevents that from happening.

Most diodes have a line or a bar that marks one end of the device. This line corresponds the the line or bar on the end of the arrow in the diagram. In our circuit, this is connected to 5V.

alt text

Final circuit

Here is the completed circuit as it should look like on your breadboard. Pay close attention to the direction of the diode. If it’s plugged in backwards, you’ll end up with unpredictable behavior. Notice that we are connecting one of the PWM pins (pin 9) on the Arduino to the base of the transistor. This will be our control signal for the motor.

alt text

Now you have your circuit, let’s try out some sample code.

Example Code

With your transistor and motor connected up, let’s try a few simple examples.

Motor Blink

This is the easiest example to try. This is essentially the blink example code. But, instead of blinking an LED on pin 13, we are setting pin 9 HIGH and LOW. We increased the delay to 5 seconds so that the motor isn’t starting and stopping every second. Copy this code into Arduino and upload it to your board. You should see that the motor turns on for 5 seconds and then stops for 5 seconds. If it doesn’t work, go back and double-check your wiring.

language:c
//Simple Motor Blink
//Turns pin 9 on and off repeatedly

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

void loop()
{
  digitalWrite(9, HIGH);
  delay(5000);  //wait for 5 seconds
  digitalWrite(9, LOW);
  delay(5000);  //wait for 5 seconds
}

Serial Motor Speed Control

On and off are fun, but what about controlling the speed of the motor. We connected the transistor to pin 9 (a PWM pin) so that we can also use analogWrite() to control the speed of the motor. This is a little example sketch that allows you to type in values into the Serial Monitor to pass values to your program.

Copy this code into Arduino and upload it to your board. After the upload is complete, open up the Serial Monitor. Type in a value from 0 to 255 and hit enter. You should see the motor spin up. What’s the slowest speed you can set this to? What happens when you put a load on the end of the motor? This is a great application for creating kinetic sculptures and moving things.

language:c
//Serial control of motor speed
//Upload this sketch and then open up the Serial Monitor. Type in a value (0 - 255) and hit enter.

int motorSpeed;

void setup()
{
  Serial.begin(9600);  //initiate Serial communication
  Serial.println("Type in a vale from 0 - 255 and hit enter.");
  pinMode(9, OUTPUT);
}

void loop()
{
  if (Serial.available() > 0)
  {
    motorSpeed = Serial.parseInt();
    Serial.print("Setting motor speed to: ");
    Serial.println(motorSpeed);
    analogWrite(9, motorSpeed);
  }
}

Can I change the direction?

The next thing you probably want to do is change or control the direction that the motor spins. Unfortunately, you can’t do this with a single transistor. If you want to change the direction the motor spins, you can manually reverse the wires on the circuit, but there is no way to do this in code without introducing a new piece of hardware. To control speed and direction, you need 5 transistors arranged in a configuration called an H-Bridge.

In the diagram below, we have shown the transistors as simple switches. If we closed switch A and D, current flows through the motor from left to right. If we close switch B and C, current flows through the motor in the opposite direction from right to left.

alt text

Check out the tutorial on getting started with the H-Bridge Robot.

Robot Quickstart!

This is a quick startup guide for building simple robots with the TB6612 driver board and some simple motors.

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

micro:arcade Kit Experiment Guide

$
0
0

micro:arcade Kit Experiment Guide a learn.sparkfun.com tutorial

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

Introduction to the micro:arcade Kit

We love games! We love writing games, building games and yes, even building game consoles. So we want to introduce to you the micro:arcade kit for the micro:bit!

The kit includes our gamer:bit carrier board for the micro:bit, which gives you access to a number of pins through the form of buttons in a classic game controller layout. But, that isn’t all!

It’s one thing to design a “game controller,” but what about building a console? A joystick, buttons to mash…the things that make us hard-core arcade fans drool and daydream. This kit is designed for you! The kit includes all of the parts you need to take this lowly controller breakout to a pinball wizard’s dream!

Included Materials

Below is all the parts included in the SparkFun micro:arcade kit.

SparkFun micro:arcade kit

KIT-14218
49.95

The kit includes the following parts:

  • SparkFun gamer:bit— The carrier board for the micro:bit that turns it into a handheld controller, game or other tool.
  • Arcade Joystick— Old-school arcade joystick that uses digital switched for directions.
  • Red Concave Button— Mash away!
  • Blue Concave Button— Jump!
  • Yellow Concave Button— Game over!
  • Green Concave Button— For firin' the laser!
  • micro:bit Battery Holder— Unique 2XAA battery holder built specifically for the BBC micro:bit
  • Spade Connector Wires (Qty: 16)— 24 AWG 3 ft wires with a female insulated spade connector at one end and a braided wire lead at the other to connect the arcade buttons and joystick to the gamer:bit
Note: The kit comes with everything you need to build a game or controller console. But you will need to supply your own micro:bit and USB cable.
micro:bit Board

DEV-14208
14.95
USB Micro-B Cable - 6"

CAB-13244
1.95
3

How to Use This Guide

We wanted to note that this guide is designed to get you started with the gamer:bit board and the SparkFun micro:arcade kit in a straightforward and simple way. We demonstrate each component’s functionality and the corresponding code to make it work.

While you explore this guide, we urge you to take your time and tinker with the sensors, code and the ideas shared to build something tailored to your application and creativity. Our goal is to get you enough information and know-how to make you dangerous and then release you into the wild.

Be sure to share your projects with us over Twitter or Facebook! We are excited to see you Start Something!

Suggested Reading

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

What is a Circuit?

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

Getting Started with the micro:bit

The micro:bit is a compact, powerful programming tool that requires no software installation. Read on to learn how to use it YOUR way!

Open Source!

All of our experiments and guides are licensed under the Creative Commons Attribution Share-Alike 4.0 Unported License. Feel free to remix and reuse our work. But please, share the love and give us attribution for our hard work!

To view a copy of this license visit this link, or write: Creative Commons, 171 Second Street, Suite 300, San Francisco, CA 94105, USA.

Hardware Overview

The gamer:bit is a carrier board for the micro:bit. It is similar to an Arduino shield by adding functionality to the micro:bit without the hastle of a number of other boards, components, and all of those jumper wires connected to a breadboard.

SparkFun gamer:bit

DEV-14215
9.95

In this case, the gamer:bit takes your normal run of the mill micro:bit and turns it into a fully functional game system with a few extra parts to take your game experience to the next level. Let’s take a closer look at the gamer:bit!

Edge Connector

The gamer:bit connects to the micro:bit via an edge pin connector in the center of the board. This makes it handy to swap out micro:bits for programming, but also gives reliable connections to all of the different pins on the micro:bit. Make sure that you insert the micro:bit correctly with the LED array facing up!

Edge Connector

Direction Buttons

The gamer:bit is designed around a classic game controller which means ther is a familiar “D Pad” style button layout on the left hand side of the board. The pins that each button controls are labeled on the board.

Direction Buttons

  • UP => P0
  • RIGHT => P1
  • DOWN => P8
  • LEFT => P2

Action Buttons

There are two action buttons.

Action Buttons

Let’s name them X and Y buttons. Sorry to those used to the classic style naming, but A and B are already referenced with the buttons on the micro:bit. These buttons have no specific use other than what you program them to be. They are connected to the following pins:

  • X (LEFT FUNCTION) => P12
  • Y (RIGHT FUNCTION) => P16

Poke-Home Connectors

On the back of the gamer:bit you will notice some odd plastic connectors. These are called poke home connectors. Each one corresponds to a button on the back of the board and are labeled as such. You will end up using these to connect your external components to gamer:bits buttons. Each button has two pins to it, one for each wire to connect to the button and component.

Poke Home Connectors

With that, you are ready to start! Are you a user? We hope you have your chips, energy drink and eye drops because this is going to be a marathon!

Installing the gamer:bit Package for Microsoft MakeCode

To make the most out of the gamer:bit with the least amount of coding, use the MakeCode package we wrote for the gamer:bit board.

Packages?

If you have used Arduino before, you probably know about a thing called a library; which is a collection of code that extends the functionality of the core programming language. MakeCode packages work the same way.

There are some amazing differences between Arduino libraries and MakeCode packages. One of them is that MakeCode packages include JavaScript functions, which you can use when programming in text, as well as all of the blocks you need to program using the block method. This makes learning and using new packages straightforward and shortens the time to awesome when setting out to build the project of your dreams.

Installing a MakeCode Package

To install or add a new package to your MakeCode toolbox (the list of different block groups), click on “Advanced” and then on “Add Package.”

Screenshot Installing MakeCode Package

From here you can search for “SparkFun gamer-bit,” and it should show up as a public package in the list. Go ahead and click on it.

Screenshot Makecode gamer:bit

This will add all of the blocks to your toolbox. In general, this is a bit tricky as, depending on how the package was written, it may either have its own toolbox or just add blocks to the existing ones. Take a look at your toolbox; for the gamer:bit you should see…

Screenshot gamer:bit installed

Great! You have now installed the gamer:bit package and are ready to use the board as well as the components that come in the micro:arcade kit. As a side note, for every new MakeCode project that you make, you will have to load packages over again. Not a big deal, but noteworthy! Now, let’s put your package to good use and get your game on!!!

Experiment 1: Basic Use of The Gamer:bit

Introduction

We take buttons for granted! We press the keyboard in front us all day long, we use game controllers until they ware out and we never really think about what goes on behind the scenes in terms of programming or even in the hardware circuit. In this initial experiment, you will hookup your micro:bit to the gamer:bit and test the buttons to make sure everything is up and running and your first introduction to the game command blocks in Microsoft MakeCode.

Parts Needed

  • 1x micro:bit*
  • 1x micro-B USB Cable*
  • 1x gamer:bit carrier board

*Not included in the micro:arcade kit

Didn’t Get the micro:arcarde Kit?

If you are conducting this experiment and didn’t get the micro:arcade Kit, we suggest using these parts:

micro:bit Board

DEV-14208
14.95
USB Micro-B Cable - 6"

CAB-13244
1.95
3
SparkFun gamer:bit

DEV-14215
9.95

Suggested Reading

Introduction to the button

Buttons are part of our everyday lives! They are an actuator that closes, or completes a circuit when you press it and sometimes release it.

The buttons on the gamer:bit are called momentary push buttons, meaning that they are only actuated or complete the circuit when you are physically pressing them. These types of buttons are great for things that you want to happen quickly, for example trigger a character to jump or chime in during a game show. The image below highlights one of the buttons that we will be using in this experiment.

UpP0

Behind the button itself you also need to realize that a button is read by a pin on your micro:bit. That pin reads whether it is HIGH or LOW, ON or OFF, 1 or 0. A pin being pulled HIGH is 3.3 volts being applied to it, while LOW is 0 volts, or grounded. A button actuation can either pull the pin HIGH or LOW depending on how it is wired as well as the program running on your micro:bit.

Hardware Hookup

The only hardware hookup at this point is inserting your micro:bit into the gamer:bit correctly! Insert your micro:bit with the LED array facing up (the same direction as all of the buttons).

micro:bit insertion

Note: The edge connector for the micro:bit is not keyed, so there is the potential for the micro:bit to be inserted backwards. Be sure to check the orientation of the board and micro:bit before plugging it in!

Running Your Script

We are going to use Microsoft MakeCode to program the micro:bit. Please open a browser window and navigate to makecode.microbit.org. This should open the makeCode environment that you used to install the gamer:bit package in.

MakeCode Program

Be sure to add the gamer:bit package as instructed in the Installing the gamer:bit Package in MakeCode section of this tutorial.

Now, you can either download the following example script below and drag and drop it onto your micro:bit, or use it as an example and build it from scratch in Microsoft MakeCode.

Note: If this is your first time programming a micro:bit please be sure to see our Getting Started with the micro:bit tutorial on how to get your MakeCode program onto your micro:bit.

Code to Note

Let’s take a look at the code blocks in this experiment.

Code to Note

If you are having a hard time viewing this code, click on the image above to get a better look!

Create Sprite at

The “players” or “objects” in a video game are called sprites. On the micro:bit, sprites are a single LED in the LED array that you can control. You create a sprite by creating a variable in MakeCode.

You can create a variable under the Variables drawer and use the “Make a Variable” option and name it. We named our variable player. To initially create our sprite in the On Start block, we set the variable to Create Sprite at block and pass it an x and y value.

The coordinate system of the micro:bit’s LED array starts at the top left of the array. The variable for x increases as you move from left to right (from 0 to 4). The variable fory increase from the top to the bottom (from 0 to 4). We set our sprite to the location 2,2 which is the center of the LED array.

Gamer:bit On

To move our sprite around the tiny screen, we read if the D-Pad (direction buttons) are being clicked (i.e. pressed and then released) or not. We track these button clicks using an event block from the gamer:bit toobox drawer that is only triggered when you interact with a specific button on the gamer:bit,. This block is called the Gamer:bit On block. You can track any of the buttons / pins on the gamer:bit as well as using following event types:

  • DOWN - If the specified button is UP or being held down
  • UP - If the specified button is UP or when it is released
  • CLICKED - If the specified button has been pressed AND released.

[SPRITE] Change by

Under the game:bit toobox drawer, there are a number of blocks to help you manipulate or change your sprite. A basic one to start out with is the [SPRITE] Change by block. This block allows you to change x, y, direction, brightness, or blink of a sprite by a number. We use this block to change the X and Y coordinates and move the sprite around.

If we change the Y coordinate of the sprite by -1 it will move up one spot. A positive 1 will move the sprite down. For the X coordinate, positive 1 is moving to the right and -1 is to the left.

What You Should See

Once your code is loaded, you should press the direction buttons on the D-pad. As a result, your sprite should move around the screen. Pretty sweet! You have built something that is a pretty good start to a possible game.

Final Assembly | pressing a button

Troubleshooting

  • gamer:Bit blocks not showing up - Make sure you have a network connection and you have added the package to your MakeCode environment.

  • micro:bit not showing up on my machine - Try unplugging the USB cable and plugging it back in. Also, be sure that you have the cable inserted all the way into your micro:bit

  • Button events don’t seem right?! - Make sure that you have specified the correct direction to the correct direction of the X and Y coordinates.

Experiment 2: Button Reaction Timer

Introduction

You learned about reading button presses in Experiment 1 and event blocks. But, there is a bit of a problem with reading buttons that way… Events cannot be used as a variable in a simple way (similar to just reading a pin on its own). If for some reason you want to be able to read a combination of blocks at one time, or in this case use the state of a button with some other type of logic you actually need to use the Button variables that come with the gamer:bit package. You will be building a reaction timer to test how sharp your wits really are!

We will also be adding an external button to gamer:bit to give it a bit of an arcade feel!

Parts Needed

  • 1x micro:bit*
  • 1x micro-B USB Cable*
  • 1x gamer:bit carrier board
  • 1x Arcade Button
  • 2x Spade Wire Connectors

*Not included in the micro:arcade kit

Didn’t Get the micro:arcarde Kit?

If you are conducting this experiment and didn’t get the micro:arcade Kit, we suggest using these parts:

micro:bit Board

DEV-14208
14.95
USB Micro-B Cable - 6"

CAB-13244
1.95
3
Concave Button - Red

COM-09336
1.95
1
Spade Connector Wire - 3ft, Female (2 Pack)

CAB-14166
1.95
SparkFun gamer:bit

DEV-14215
9.95

Suggested Tools

  • Ball point pen
  • Hobby knife or scissors

Suggested Reading

Introduction to the Arcade Buttons

The classic arcade button! Oh how we love them.

Red Arcade Button

The arcade buttons work two ways as either a normally closed (NC) switch or as a normally open (NO) switch. That is to say that you can pick whether pressing the button completes, or closes the circuit. Or, breaks the circuit from a closed, or “on” state.

Micro Switch

The back of each button has a the actual switch with 3 tabs. One is common or “COM” which you will always use and then either “NO” or “NC”. In this case, we will be using Normally Open, but there are times where you could use Normal Closed as well.

Hardware Hookup

You will be hooking up one of the arcade buttons to the UP direction pad. You can then mount the button in a cardboard box or any other panel you like. The cardboard box that the kit came in is a good stand in for now!!

Exp2_Step1Hookup | parts laid out

We will start out by adding the disconnect wires to the button. Start by connecting one wire to the Common (COM) pin on the button. The disconnects should slide over the tabs on the buttons snugly.

Exp2_Step2Hookup | closeup of adding a disconnect to COM

Next, for each button add another wire to the “NO” tab, on the button, you should have two wires connected to it at this point.

Exp2_Step3Hookup | closeup of adding a disconnect to NO

The image below shows the quick disconnects added to the terminals of the microswitch.

Exp2_Step4Hookup | closeup of a button wired up

Finally, connect each set of wires to its corresponding poke-home connector by pressing down on the tab of the connector with a ballpoint pen and inserting the bare wire end. It doesn’t matter what wire goes where in this wiring configuration as long as each wire is connected to pin P0 and P1.

Exp2_Step5aHookup | closeup of a poke home being wired up

As the poke-home connector is being pressed down, insert the wire into the connector as shown below.

Exp2_Step5bHookup | closeup of a poke home being wired up

Once the wire has been inserted sufficiently into the poke-home connector, pressure from the ballpoint pen on the tab may be removed. The connector will actually hold it tight until you want to remove it. Below shows an image of the wires connected to P0 and P1.

Exp2_Step5dHookup | closeup of a poke home wired up

Note: To disconnect a wire from a pokehome connector use a ball point pen or pencil to press down on the small tab of the connector and gently tug on the wire. The wire should come out easily.

The buttons themselves are designed to be mounted to a panel made of plywood, plastic, or even through a piece of cardboard. For this project we used the box that the kit came in as a great cabinet for your reaction timer.

To start, we need to remove the microswitch from the bottom of the button by carefully prying it out of the mounting bracket. This isn’t held in place with any hardware, just molded plastic, so be careful not to break anything. With the green side of the microswitch facing toward you, you will need to push the one of the plastic pins holding it in place. Gently twist the microswitch counterclockwise with your left hand while holding the concave button with your right hand.

Exp2_Step7aHookup | removing the mech. from switch

Once the plastic pins is out of one of the holes, rotate the microswitch away from the pin as shown in the image below.

Exp2_Step7bHookup | removing the mech. from switch

Finally, slide the microswitch out by moving it out of the second molded pin.

Exp2_Step7cHookup | removing the mech. from switch

To mount the concave button, we will also need to cut a hole the cardboard box. You will need to unscrew the black ring from the concave button. In this experiment, we will be mounting the button on the top right side of the box. We can use the black ring that is attached to the concave button as a guide to cut the 1 1/8" hole. Using a pen, draw the mounting hole.

Exp2_Step6aHookup | Draw Hole with ring

Using a craft knife or pair of scissors, cut a hole inside of the lines. Make sure to not cut too much of the cardboard box.

Exp2_Step6bHookup | Hole cut in the box

Additionally, draw about a 1" square hole on the front of the box for the wires. The square was placed in the middle for the purpose of this experiment.

Exp2_Step6cHookup | Draw hole for wires

Cut the square out using the craft knife or pair of scissors.

Exp2_Step6dHookup | Cut hole for wires

Insert the microswitch with wires through the square hole.

Exp2_Step8Hookup | Place microswitch through the square hole

At this point, we can insert the concave button through the hole and thread the nut back onto the button from the bottom. The cardboard will be sandwiched between the concave button and the threaded nut. Finally, reattach the microswitch to the bottom of the concave button.

Exp2 Final Assembly

Now, give it a good mash to test it and make sure it will hold up!

Running Your Script

Now, you can either download the following example script below and drag and drop it onto your micro:bit, or use it as an example and build it from scratch in MakeCode.

Note: If this is your first time programming a micro:bit please be sure to see our Getting Started with the micro:bit tutorial on how to get your MakeCode program onto your micro:bit.

Code to Note

Let’s take a look at the code blocks in this experiment.

Code to Note

If you are having a hard time viewing this code, click on the image above to get a better look!

RandomTime

We create a variable called randomTime and store a value that produces a random number between 1 and 5 seconds. This will be the random time it takes that a person needs to wait before the LED will turn on so it is harder to “game” the system or cheat their reaction time.

We produce that random number using the random number to block which produces a random number between 0 and a give value, we set it to 4. To make the range between 1 and 5 seconds we added 1 and multiplied that value by 1000.

While Not Gamer:bit Pressed

Once the program starts we need it to wait until the button is pressed by the person playing. To put the program in “limbo” we use a while block that reads the opposite of the gamer:bit pressed block. In other words… while the button is NOT being pressed, the program will do nothing. We use this twice; once at the beginning to start the game and a second time to capture the reaction timing.

Toggle X Y

To turn the LED in the center of the LED array on we use the Toggle X Y block. This will toggle the LED at a given X/Y coordinate. In terms of the the LED, a “toggle” changes its state from the one that it currently is in. So toggling from OFF is to turn something ON.

ZeroTime

To keep track of a reaction time we need two values to compare; a starting point and a stopping point. We capture the staring point by creating a variable called zeroTime and setting it to running time. The running time block returns the number of milliseconds that the micro:bit has been powered up and running.

StopTime

Once the button is pressed we need to capture that current time. When the button is pressed it releases the program from the while block and captures the current time again and stores it to the stopTime variable. This is done the same way as the zeroTime variable.

ReactionTime

When we have the two different variables zeroTime and stopTime, we can calculate the player’s reaction time. The reaction time is the difference between the two.

Show String / Number

We display the readout of the player’s reaction time to the player once they have finally reacted. The show string block allows you to display text across the LED array. The show number block does the same thing, but for a number.

Game Over

The game over block is an animation block found under the game:bit toobox drawer of MakeCode. It does a little animation, prints out “Game Over”, and then a score if you are using it.

What You Should See

Once your code is loaded to the micro:bit, you should see text scroll by that says “Push Me!”. Press the button and the screen will go blank. Once the single LED lights up, press the button again as quickly as possible. Your reaction time will then be displayed followed by a game over sequence.

Exp2Powered

Troubleshooting

  • Game doesn’t start right away - You have to wait for the text to finish scrolling by before the game starts.

  • Doesn’t read my button press - Make sure that you are hooked up to the correct button on the gamer:bit and that all wires are securely fastened to both the button and the board.

  • Reads a constant button press - You have the button wired to NC (Normally closed) and so it is constantly being pressed, change the connections on the back of the button to NO (Normally Open).

Experiment 3: Fun with the Joystick

Introduction

So far we have been building and programming games that either don’t have a score or require you to keep track. It is now time to pass that job off to the micro:bit. You are now going to build a simple collection game where “coins” are falling down the screen and you will control your sprite with the joystick to collect them. You will also only have 10 second before the game ends. At the end of the 10 seconds the game will be over and your score will be displayed.

Parts Needed

  • 1x micro:bit*
  • 1x micro-B USB Cable*
  • 1x gamer:bit Carrier Board
  • 1x Arcade Joystick
  • 4x Spade Wire Connectors

*Not included in the micro:arcade kit

Didn’t Get the micro:arcarde Kit?

If you are conducting this experiment and didn’t get the micro:arcade Kit, we suggest using these parts:

micro:bit Board

DEV-14208
14.95
USB Micro-B Cable - 6"

CAB-13244
1.95
3
Arcade Joystick - Short Handle

COM-09182
14.95
2
Spade Connector Wire - 3ft, Female (2 Pack)

CAB-14166
1.95
SparkFun gamer:bit

DEV-14215
9.95

Suggested Tools

  • Ball point pen
  • Hobby knife or scissors
  • 12" ruler

Suggested Reading

Meet the Joystick

The arcade joystick is the heavy duty short handled joystick that we are all familiar with from our favorite game cabinet of our childhoods (or for most of us… yesterday).

Joystick

This joystick operates as four momentary push switch, one for each direction. Each switch is opposite from the directions that it controls. For example is you press the joystick “UP” the switch on the “DOWN” side of the joystick is pressed, so you have to wire it backwards to the direction the joystick is pressed.

Bottom of Joystick

The wiring for this experiment will use the common (COM) and the Normally Open (NO) terminals on the switches.

Hardware Hookup

The hardware hookup should be pretty familiar to you in a way. The Arcade joystick uses the same type of switches as the arcade buttons with the same spade connects. Hookup a spade connector wire to each switches COM and NO terminals as shown below. For this specific game you will only need the two switches that control left and right movement.

Exp3_4xQuickDisconnects

When using the joystick or the arcade buttons, it is always a great idea to mount them to a piece of cardboard or in shoe box (the box the kit comes in is the perfect size). You can mount the joystick by cutting out mounting holes for the joystick’s frame.

To begin, remove the knob of the joystick by unscrewing it from the shaft. This also allows you to remove the black cover ring of the joystick as well.

Removing Knob

Using a Phillips head, we can remove the four screws that are holding down the frame. The SparkFun mini screwdriver was used in this experiment to remove the screws.

Knob and Ring Removed

Once the frame has been removed, we can use it to draw the mounting holes. Place the other parts in a safe location as while cutting the cardboard box.

Joystick Parts Laid Out

On the top left hand side of the box, draw the four mounting holes for the screws. Additionally, draw a hole for the shaft.

Drawing Mounting Holes

Using the mini screwdriver, carefully poke holes through the four mounting holes. A craft knife or pair of scissors can be used cut the hole for the shaft.

Cut Mounting Holes

Note: To prevent damage to the wires and concave button, you may remove the concave button, wires, and microswitch as the hole is being cut out.

Now that the mounting holes are cut, we can attach the joystick to the cardboard box. Hold the frame against the top of the cardboard box. Attach one screw through the mounting hole using one hand. Next, pass the shaft of the joystick up through the bottom of the box until one mounting hole lines up with the screw. Twist the screw in with your hand just enough to sandwich the cardboard between the joystick and the frame. Continue adding the rest of the screws to the joystick and tighten up the scerws using the mini screwdriver.

A great idea to be able to keep things straight is to label each pair of wires at the stripped ends so that when you hook it up to your gamer:bit carrier board, you don’t have to constantly tracing the wires back to the correct switch.

Exp3_Labeled1 | labeled wires for the micro:bit and joystick

Using some sticky notes, label each wire twice for the poke-home connectors labeled P1 and P2. You can slide one label close to the joystick and the other for the gamer:bit.

Exp3_Labeled2| labeled wires for the micro:bit and joystick

Hookup the stripped ends into the poke-home connectors as explained in the previous experiment by pressing down on the connector tab with a ballpoint pen, inserting the bare end of the wire into the connector, and releasing the tab. The connector will hold tight onto the wire with a snug connection. While we are at it, feel free to reconnect the concave button and label those wires.

Wires Inserted into Poke-Home Connector

Finally, you can return the black cover ring and knob to the top of the joystick. The concave button was not used in this experiment but feel free to reattach it back to the box.

Reattached Nut and Ring

Give a quick test to make sure everything works… you should feel a nice click from the switches inside the box.

Exp3_FinalAssembly

Running Your Script

You can either download the following example script below and drag and drop it onto your micro:bit, or use it as an example and build it from scratch in MakeCode.

Note: If this is your first time programming a micro:bit please be sure to see our Getting Started with the micro:bit tutorial on how to get your MakeCode program onto your micro:bit.

Code to Note

Let’s take a look at the code blocks in this experiment.

alt text

If you are having a hard time viewing this code, click on the image above to get a better look!

Create Sprite

As in the previous experiments we use the Create Sprite block. This time though we use it multiple times in the program. We create our player sprite, but also a sprite for the “gold coins” that are falling that you want to capture before they go by.

Start Countdown (ms)

The start countdown block starts a timer for the length of milliseconds. At the end of that countdown, it runs a game over animation and displays the score. This simplifies this program a lot. We would have had to program that all by ourselves.

Set Score

To make sure that you are starting with a fresh game we set the score to 0 by using the Set Score block in On Start and pass it the number 0.

Change Y by

In the forever loop, we change the y value of the gold spite by 1. This creates a falling animation after the “gold” has been created in a random place along the top of the LED array.

Touching

As the “gold” falls down, we check if the “gold” sprite is touching the “player” sprite. If it is, then the player scores and the following happens.

  1. The player scores a point.
  2. The “gold” sprite is destroyed.
  3. A new “gold” sprite is created at the top of the LED array.

If the player misses the “gold” then it passes by the player. If the Y coordinate of the “gold” is equal to 4, then it is destroyed and and a new one is created without the player gaining a point.

Score + 1

To add to a players score, we use the set score block again, but this time in a different way. We set the score to the score variable plus 1.If you wanted to hack this project and have this subtract a point, you would change the math block from addition to subtraction.

Delete

To remove a sprite from the screen, you use the delete block that will destroy the variable storing the sprite and its information.

What You Should See

When the game starts, your sprite will show up one row above the bottom of the LED array. You control your sprite with the joystick to move left and right. “Gold” will start to fall from the top of the screen and you need to move to catch it. This will go on for 15 seconds. At the end of the 15 seconds, the game will end with the “game over” sequence and display your score. Wahoo, let’s play again.

Exp3_Powered

Note: The concave button from experiment 2 was wired in the setup. However, we are not using the button because the example code is only using the joystick.

Troubleshooting

  • The direction of the joystick is opposite - It gets us all the time! Flip the wires around to the opposite side of the joystick from where they are are. Or, change the wires at the gamer:bit.

  • Nothing reacts! - Double check that your gamer:bit events are monitoring the correct pins that your joystick is wired to!

  • I can’t unhook the poke-home connector - Make sure you are using a ball point pen and pressing down on the tab. Don’t just pull on the wire!

Resources and Going Further

Here is some further reading that may help you along in learning more about the world of electronics.

Check out these other great micro:bit ecosystem tutorials from SparkFun:

New!

SparkFun Inventor's Kit for micro:bit Experiment Guide

The SparkFun Inventor’s Kit for micro:bit Experiment Guide is your map for navigating the waters of beginning embedded electronics, robotics and citizen science using the micro:bit. This guide contains all the information you will need to explore the 12 circuits of the SparkFun Inventors Kit for micro:bit.

Getting Started with the micro:bit

The micro:bit is a compact, powerful programming tool that requires no software installation. Read on to learn how to use it YOUR way!
New!

micro:climate Kit Experiment Guide

A weather station kit that is built on top of the inexpensive, easy-to-use micro:bit and Microsoft MakeCode. We have also written seven experiments that walk you through how to use each and every component of the kit and how to use them with the micro:bit and Microsoft MakeCode.

micro:bit Breakout Board Hookup Guide

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

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

micro:climate Kit Experiment Guide

$
0
0

micro:climate Kit Experiment Guide a learn.sparkfun.com tutorial

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

Introduction to the Micro:Climate Kit

Introduction

We have seen a huge amount of excitement from hobbyists, students and scientists around building a DIY weather station to track what is going on around us on Planet Earth on a daily basis.

We have seen just as much excitement around the BBC’s newly released micro:bit, which made its debut in the United Kingdom and is now available in the United States through SparkFun.

And then it dawned on us…why not combine the two? So, here it is: a weather station kit that is built on top of the inexpensive, easy-to-use micro:bit and Microsoft MakeCode. We have also written seven experiments that walk you through how to use each and every component of the kit and how to use them with the micro:bit and Microsoft MakeCode.

What’s Included in the Kit?

Below is all the parts included in the SparkFun micro:climate kit.

SparkFun micro:climate kit

KIT-14217
114.95

The kit comes with everything you need to build a fully featured weather station for the micro:bit. All you need to supply is, well, the micro:bit!

micro:bit Board

DEV-14208
14.95

The kit includes the following parts:

  • SparkFun weather:bit— The carrier board for the micro:bit and the central component to building a weather station
  • Weather Meter— Wind speed, direction and rain gauge that connects to the SparkFun weather:bit
  • SparkFun Soil Moisture Sensor— A simple probe for measuring soil moisture
  • Waterproof Temperature Sensor— Waterproof temperature sensor with a long wire
  • SparkFun OpenLog— A small widget that logs any data sent to it over a serial connection to a microSD card
  • 10-Pack of M/M 12" Jumper Wires— Jumper wires for connecting things
  • SparkFun Screwdriver— Great for tightening screws and screw terminals

How to Use This Guide

Please note that this guide is designed to get you started with the weather:bit board and the SparkFun micro:climate kit in a simple, straightforward way. We demonstrate each component’s functionality and the corresponding code to make it work.

While you explore this guide, we urge you to take your time and tinker with the sensors, code and ideas shared to build something tailored to your application. Our goal is to get you enough information and know-how to make you dangerous and then release you into the wild, weather station in hand, to do whatever you do with a weather station.

Be sure to share your projects with us via Twitter or Facebook! We are excited to see you get creative and Start Something!

Suggested Reading

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

What is a Circuit?

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

Getting Started with the micro:bit

The micro:bit is a compact, powerful programming tool that requires no software installation. Read on to learn how to use it YOUR way!

Open Source!

All of our experiments and guides are licensed under the Creative Commons Attribution Share-Alike 4.0 Unported License. Feel free to remix and reuse our work. But please, share the love and give us attribution for our hard work!

To view a copy of this license visit this link, or write: Creative Commons, 171 Second Street, Suite 300, San Francisco, CA 94105, USA.

About the weather:bit

The weather:bit is a carrier board for the micro:bit. Similar to an Arduino shield, it is designed to add functionality to the micro:bit without the hassle of a number of other boards, components and all of those jumper wires.

SparkFun weather:bit

DEV-14214
14.95

In this case, the weather:bit takes your normal run-of-the-mill micro:bit and turns it into a full-blown weather station with a few extra parts, which you can use to measure the following:

  • Air Temperature
  • Relative Humidity
  • Barometric Pressure
  • Wind Speed
  • Wind Direction
  • Rain Fall
  • Soil Moisture
  • Soil Temperature

Phewwwww! That is a lot of data for such a tiny computer! Let’s take a closer look at this board and check it out for ourselves.

Edge Connector

The weather:bit connects to the micro:bit via an edge pin connector. This makes it handy to swap out micro:bits for programming, but also gives reliable connections to all of the different pins on the micro:bit.

EdgeConnector

BME280 Barometric Pressure Sensor

The weather:bit has a BME280 barometric pressure sensor onboard, which can measure air temperature, humidity, barometric pressure and altitude. It communicates with the micro:bit via I2C, and the data from this sensor is easily accessible using the SparkFun weather:bit package for MakeCode.

BME280

Weather Meter Sockets

There are two RJ11 jacks at the bottom of the weather:bit. These are used to connect our weather meters to the weather:bit.

RJ11 Wind Rain

These meters enable you to measure the wind speed and direction, as well as rain fall.

weather meter hooked u

Again, these are easily accessible in MakeCode via our SparkFun weather:bit package.

Soil Moisture and Temperature

Between the two RJ11 jacks are two sets of screw terminals sets.

Soil Moisture and Temp Screw Terminals

The one on the left is used to hook up a soil moisture sensor. You can use either longer jumper wires or wires cut to whatever length works for your project.

Soil Moisture

The set on the right is the soil temperature sensor. It is set up to use our waterproof temperature sensor. This sensors wire is rather long and is great for monitoring the temperature of the soil in your garden so that you know the exact moment the ground is ready for planting those tomatoes!

Soil Temperature

Serial Port

We have populated the serial port pins with a standard FTDI format to make it easy for you to plug in a serial widget of your choice, such as an OpenLog or Serial LCD display, or to just monitor data through an FTDI breakout and USB cable.

Serial Port

I2C Port

For those of you who are more adventurous and demand a way to hook up other sensors of your choice, we have added an I2C port that can be soldered to directly — or you can add headers for plug-and-play use of your I2C sensors and actuators.

I2C

Installing the weather:bit Package in MakeCode

To make the most out of the weather:bit with the least amount of coding, use the MakeCode package we wrote for the weather:bit board.

Packages?

If you have used Arduino before, you probably know about a thing called a library; which is a collection of code that extends the functionality of the core programming language. MakeCode packages work the same way.

There are some amazing differences between Arduino libraries and MakeCode packages. One of them is that MakeCode packages include JavaScript functions, which you can use when programming in text, as well as all of the blocks you need to program using the block method. This makes learning and using new packages straightforward and shortens the time to awesome when setting out to build the project of your dreams.

Installing a MakeCode Package

To install or add a new package to your MakeCode toolbox (the list of different block groups), click on “Advanced” and then on “Add Package.”

MakeCode Package

From here you can search for “SparkFun weather-bit,” and it should show up as a public package in the list. Go ahead and click on it.

weather-bit Package

This will add all of the blocks to your toolbox. In general, this is a bit tricky as, depending on how the package was written, it may either have its own toolbox or just add blocks to the existing ones. Take a look at your toolbox; for the weather:bit you should see…

Installed Weather-bit Package

Great! You have now installed the weather:bit package and are ready to use the board as well as the components that come in the micro:climate kit. As a side note, for every new MakeCode project that you make, you will have to load packages over again. Not a big deal, but noteworthy! Now, let’s put this package to good use!

Experiment 1: Reading the Temperature, Humidity and Pressure

Introduction

What comes to mind first when you hear the term “Atmospheric Conditions”? Well, other than the weatherman on the news, you probably think about temperature — maybe humidity and even barometric pressure if you are a weather nerd like many of us at SparkFun. In this first experiment we will explore measuring those conditions using a micro:bit and the weather:bit carrier board.

Parts Needed

  • 1x micro:bit board (Not included)
  • 1x weather:bit carrier board
  • 1x micro-B USB cable (Not included)
micro:bit Board

DEV-14208
14.95
SparkFun weather:bit

DEV-14214
14.95
USB Micro-B Cable - 6"

CAB-13244
1.95
3

Suggested Reading

Introduction to the BME280

TempHumidityPressure

The BME280 Atmospheric Sensor is an easy way to measure aspects of the atmosphere around you, including pressure, humidity and air temperature. All of this is combined into a petite package that resides on the weather:bit.

The sensor operates on 3.3V and is super power-efficient, using as little as 5µA (that’s 1/1,000,000 of an amp!) when idling and less than 1mA when it’s taking measurements. This means you can operate the board on a battery, with little thought to major power issues.

In this experiment, you will work with the BME280 to read the temperature, pressure, and humidity of the room as well as your altitude based off of the atmospheric pressure.

Hardware Hookup

Since the BME280 is already on the weather:bit board, this should be pretty straightforward; you have one step in hooking everything up. Insert the micro:bit into the weather:bit carrier board with the LED array facing up as shown in the image below.

Exp1_microBitInsert | microbit plugged into the weather:bit

Note: The edge connector for the micro:bit is not keyed, so there is the potential for the micro:bit to be inserted backward. Be sure to check the orientation of the board and micro:bit before plugging it in!

Running Your Script

We are going to use Microsoft MakeCode to program the micro:bit. Please open a browser window and navigate to https://makecode.microbit.org. This should open the MakeCode environment that you used to install the weather:bit package.

Be sure to add the weather:bit package as instructed in the Installing the weather:bit Package in MakeCode section of this tutorial.

Now, you can either download the following example script and drag and drop it onto your micro:bit, or use it as an example and build it from scratch in MakeCode.

Note: If this is your first time programming a micro:bit, please be sure to see our Getting Started with the micro:bit tutorial on how to get the MakeCode program onto your micro:bit.

Code to Note

Code to Note Exp 1

Start Weather Monitoring

When the script starts, we use this block to start or initiate the BME280 sensor and get it ready to take readings. Anytime you want to use the temperature, humidity, pressure or altitude blocks, you need to have this block in your on start block.

Set Item To

We use a variable called item to keep track of which data are being displayed on the LED array. If item is equal to 0, it shows the temperature; if 1, it shows the humidity; if 2, the pressure. If the variable goes over 2, we reset it to 0. We increment the variable by pressing the A button.

Temperature (°C)

This variable returns a number that you then have to divide by 100 to get the temperature in Celsius.

Humidity

This variable returns a number that you need to divide by 1,024 to get the relative humidity.

Pressure

This variable returns a number that you divide by 25,600 to get the atmospheric pressure in hPa.

Why All of the Math?

This is a good question! It all comes down to accuracy of the data that you receive. MakeCode cannot handle floating point numbers (numbers with decimal points) yet. Which can be troublesome for getting really accurate readings from the BME280 with a single variable block. So, to as accurate of values as possible you have to do some math in the programming environment. We know, not fun! But, hey now you might pay attention in math class a bit more now.

What You Should See

Once your code is loaded, you should start to see numbers scroll across the LED array on your micro:bit, beginning with the temperature in Celsius. If you press the left button on your micro:bit, the number will change to percent humidity; press it again, and it will be pressure. Pretty cool…well, hmmm…maybe warm?

Exp1_Powered

Troubleshooting

  • weather:bit blocks not showing up— Make sure you have a network connection and have added the package to your MakeCode environment.

  • micro:bit not showing up— Try unplugging the USB cable and plugging it back in. Also, be sure that you have the cable inserted all the way into your micro:bit.

  • atmospheric data seems odd— Make sure that the BME280 is free from contact with sources of heat and/or moisture (for example, having your finger over the top of it).

Experiment 2: Reading the Light Level

Introduction

Light conditions are a huge part of the weather. The great thing is that the weather:bit doesn’t have a light sensor. No, we didn’t miss a typo! The weather:bit doesn’t have a light sensor. Why not? Because the micro:bit has one already! In this experiment you will measure the light around you and have the micro:bit “graph” it

Parts Needed

For this experiment you actually don’t need the weather:bit carrier board, so we left it out. But feel free to leave it attached to your micro:bit if you so choose.

  • 1x micro:bit board (Not included)
  • 1x micro-B USB cable (Not included)
micro:bit Board

DEV-14208
14.95
USB Micro-B Cable - 6"

CAB-13244
1.95
3

Suggested Reading

Hardware Hookup

Again, the hardware hookup here is minimal! Plug your micro:bit into your computer with the USB cable, and you are good to go!

micro:bit connected via USB

Running Your Script

Please open a browser window and navigate to makecode.microbit.org. This should open the MakeCode environment that you used to install the weather:bit package.

Code to Note

Code to Note Exp 2

Set lightVal To

We read the light level in the area using the light level block and store it in a variable called lightVal. This is the value that we can compare against the calibration value you captured at the beginning of your script.

Plot Bar Graph Of

This block is fun! It accepts two values: the value of what you want to graph and a maximum value of that variable. In this case we want to graph lightVal, and it has a maximum value of 255. This will create a “bar graph” of the light value on your micro:bit.

What You Should See

You should see the LED array light up as a graph based on how bright it is wherever you are. Turn out the lights or pass your hand over the array, and the graph should react. Pretty sweet! You now have a way to measure the light value as well as another way to display data with the micro:bit.

Exp2 Powered

Troubleshooting

  • odd light readings— Make sure you are not leaning over the micro:bit, your shadow will impact the sensor reading.

  • The arrows threshold is odd— Try resetting the micro:bit while you are not leaning over it or casting a shadow on it.

Experiment 3: Reading the Soil Moisture

Introduction

How wet is the ground? It is actually an important question to ask if you are thinking about growing plants, digging a hole, or even walking across your yard. Enter the soil moisture sensor. In this experiment you will hook up the soil moisture sensor and use it. You will display different images on your micro:bit based on the moisture level of the soil.

Parts Needed

  • 1x micro:bit board (Not included)
  • 1x weather:bit carrier board
  • 1x micro-B USB cable (Not included)
  • 3x 12" M/M jumper wires
  • 1x SparkFun Soil Moisture Sensor
micro:bit Board

DEV-14208
14.95
SparkFun weather:bit

DEV-14214
14.95
SparkFun Soil Moisture Sensor

SEN-13322
4.95
9
USB Micro-B Cable - 6"

CAB-13244
1.95
3
Jumper Wires Premium 12" M/M  Pack of 10

PRT-09387
4.5

Suggested Reading

About the Moisture Sensor

pic of soil sensor

The SparkFun Soil Moisture Sensor is a simple breakout board for measuring the moisture in soil and similar materials. The soil moisture sensor is straightforward to use. The two large, exposed pads function as probes for the sensor, together acting as a variable resistor. The more water that is in the soil, the better the conductivity between the pads will be, which will result in a lower resistance and a higher SIG (output voltage).

To get the SparkFun Soil Moisture Sensor functioning with your weather:bit, all you need to do is connect the VCC, GND and SIG pins to the weather:bits VCC, GND and SIG screw terminals. You will receive a SIG out, which will depend on the amount of water in the soil. Oh, and you’ll also need a bit of dirt in a pot to test it all out!

One commonly known issue with soil moisture sensors is their short life span when exposed to a moist environment. To combat this, we’ve had the PCB coated in gold finishing (ENIG, or Electroless Nickel Immersion Gold).

Hardware Hookup

Hooking the moisture sensor up to the weather:bit is relatively easy. You will need a screwdriver with a small bit, preferably a jeweler’s screwdriver or our pocket screwdriver.

Pocket Screwdriver Set

TOL-12891
3.95
3

Start by using the screwdriver to open the three screw terminals on the moisture sensor enough that you can insert the ends of the jumper wires into them. Next, insert three jumper wires into the screw terminals using Red for VCC, Black for GND and Yellow for SIG. Tighten the screws down so that the wires will not come loose.

mositure sensor wires

Next, do the same thing for the screw terminals for the moisture sensor port on the weather:bit. Open the screws enough that you can insert the jumper wires with Red to VCC, Black to GND and Yellow to SIG. Tighten the screws enough to hold the wires in place.

Exp3_Hookup | soil mositure sensor wires

With that, you are done hooking the moisture sensor up!

Running Your Script

Please open a browser window and navigate to https://makecode.microbit.org. This should open the MakeCode environment that you used to install the weather:bit package.

Code to Note

Code to Note Exp 3

Soil Moisture

The Soil Moisture block returns an analog value range of 0 - 1023 (a 10 bit number). The lower the number is the less moisture the sensor detects. The “dryness” and “wetness” level depends on your climate, humidity, etc. so we cannot give you a concrete range of what is wet and dry, that is something you will have to fiddle with yourself.

If / Else If / Else

We used an if then block to create some logic that changes based on the soil moisture detected by the sensor. If the moisture value is low the LED array shows an angry face, if just right a smiley face and if too wet and frown.

To add more else / else if options to your if statement click on the small gear and build your state tree using the block interface presented.

Show Icon

The Show Icon block is really useful when you want to display a simple image or icon on the LED array. You can select from a number of premade images from the pull down menu in the block.

What You Should See

Based on our extensive testing (me pouring water into a pot of soil with the sensor stuck in it), we defined dry, damp and wet states. The image below shows the experiment powered up to test the plant’s soil.

Exp3_FinalAssembly | moisture sensor and output

When you insert your sensor into a potted plant of your own and run your script, you will see an icon show up on your micro:bit. If you get an angry face, your soil is too dry; a sad face means it is too wet; and finally, a happy face is “moist” and just right. Water as needed to keep your plants “happy.”

Exp3_FinalAssemblyPlant | moisture sensor in a plant and output

You may need to adjust the numbers in your code to match the state of preference for your house plants!

Troubleshooting

  • Odd readings— Make sure your wiring is correct, if you wire the sensor backwards it will give backwards results.

  • I never get a “happy” face— Try playing around with the threshold values in your if statements to find a range that works for your application.

  • It still doesn’t workDrop us a line, we would love to help you figure it out!

Experiment 4: Reading the Soil Temperature

Introduction

When you are looking to put plants in the ground in spring, plant seed, or even track the temperature of your koi pond, you need a temperature sensor. But not just any temperature sensor…a waterproof one! In this experiment you will explore using the waterproof temperature sensor to measure ground temperature in a garden or pot.

Parts Needed

  • 1x micro:bit board (Not included)
  • 1x weather:bit carrier board
  • 1x micro-B USB cable (Not included)
  • 1x Waterproof Temperature Sensor
Temperature Sensor - Waterproof (DS18B20)

SEN-11050
9.95
19
micro:bit Board

DEV-14208
14.95
SparkFun weather:bit

DEV-14214
14.95
USB Micro-B Cable - 6"

CAB-13244
1.95
3

Suggested Reading

Hardware Hookup

The hookup of this sensor is much easier with the weather:bit carrier board than with any other microcontroller. We have done a lot of the leg work for you!

Find the screw terminals for the soil temperature on the weather:bit. Using your screwdriver, open the screw terminals a bit and insert the wires as shown in the photo below with the wires from left to right:

  • Red to VCC
  • White to SIG
  • Black to GND

Exp4_Hookup | hookup of temp sensor

Running Your Script

Please open a browser window and navigate to https://makecode.microbit.org. This should open the MakeCode environment that you used to install the weather:bit package.

Code to Note

Code To Note Exp 4

Soil Temperature

The Soil Temperature block returns the soil a value that you need to divide by 100 to get the temperature in Celcius. Like the data from the BME280 sensor in Experiment 1, this is to get you the most accurate temperature possible.

Set Item To

In this Set Item To block we use a boolean variable of true. You can then flip flop that variables to false when needed

Not

We use the not block to flip flop a boolean variable when needed. In this case when a button is pressed.

Show String

The Show String Block enables you to display a scrolling string of character across the LED array.

Show Number

As in previous experiments we use the show number block to display the temperature data from the soil temperature sensor.

What You Should See

As soon as you power up your micro:bit, you should see the ground temperature from the temperature sensor scrolling across the LED array in Celcius. If you press the A button, it will change what is scrolling to a “Plant” or “Don’t Plant” depending on the temperature of the ground making it a useful tool for when to figure out when it is time to plant your tomato crop.

Exp4_FinalAssembly | Temperature setup

Note: The actual temperature sensor is at the end of the long wire. Make sure that is in place where you want to take temperature readings; otherwise you may get odd values.

Troubleshooting

  • Odd temperature— Make sure you are measuring with the end of the temperature sensor, that is where the actual sensor is.

  • Really odd temperature— Double check your wiring and hookup!

  • Numbers still seem odd— Check your math blocks! You may be missing an order of operation.

Experiment 5: Reading the Wind Direction and Speed

Introduction

The winds are a-blowin'! The question is, which direction and how hard? In this experiment you will assemble, hook up and program your weather:bit to read the weather meters — more specifically, the wind anemometer (wind speed) and directional vane. We will again use the micro:bit’s LED array to display the wind speed or the direction.

Parts Needed

  • 1x micro:bit board (Not included)
  • 1x weather:bit carrier board
  • 1x micro-B USB cable (Not included)
  • 1x Weather Meter
Weather Meters

SEN-08942
76.95
20
micro:bit Board

DEV-14208
14.95
SparkFun weather:bit

DEV-14214
14.95
USB Micro-B Cable - 6"

CAB-13244
1.95
3

Suggested Reading

Introducing the Weather Meter (Anemometer and Vane)

The anemometer on the weather meter is the propeller-looking thing that got lost in a ping-pong ball factory.

Anemometer

It has three cups that catch the wind, which then cause it to spin. As the head spins, a magnet at the center of the hub travels over a reed switch that closes the circuit to the pin that the sensor is connected to for a brief moment. The faster the wind is, the faster the anemometer spins and the faster and more often the reed switch is triggered.

We count the number of times that the reed switch is triggered every second, and we can calculate the wind speed from that (1 click per second is roughly 1.5mph).

We did the hard work on this one in terms of simplifying all of this for you. All you need to know is that an anemometer is a wind-speed sensor.

The wind vane is the arrow-looking thing that spins.

Wind Vane

When the wind blows, it catches the vane, which points in the direction that the wind is coming from. As the vane moves around, it closes a series of switches inside, which produce a different resistance at 16 different locations around the hub. Each direction has a specific value that we have mapped to the cardinal directions once you have it set in the location you want it. In the makeCode package the Wind Direction block will return N,NE,E,SE,S,SW,W,NE directions as a string.

Hardware Hookup

To help you out in the assembly of your weather meter we have created this step by step assembly guide.

New!

Weather Meter Hookup Guide

July 20, 2017

How to assemble your very own weather meter!
Note: Once you have assembled your weather meter we highly recommend labeling the two cables for the wind and rain sensors. This will make your life much easier in the long run!

Once you have completed the assembly of the weather meter, find the cable for the wind sensors and plug it into the RJ-11 connector on the weather:bit labeled “wind”.

wind

With that you are ready to roll!

Running Your Script

Please open a browser window and navigate to https://makecode.microbit.org/. This should open the MakeCode environment that you used to install the weather:bit package in.

Code to Note

Code to Note Exp 5

Start Wind Monitoring

The Start Wind Monitoring block starts all of the necessary processes to use the wind sensors that plug into the weather:bit. This block show be placed in the On Start block as it only needs to be called once at the very beginning of the program.

Show Number

The Show Number block displays/scrolls whatever number is placed inside of it across the LED array. We use it to display the wind speed in this example.

Wind Speed

The Wind Speed block is a variable block that returns the calculated wind speed from the anemometer. It is updated every 2 seconds!

Show String

The Show String block is similar to the Show Number block in that it displays/scrolls whatever string that it is passed. In this case we use it to display the wind direction.

Wind Direction

Last but not least, the Wind Direction block is a variable block that returns a string value of a cardinal direction that the wind vane is pointing.

What You Should See

Once you power up the micro:bit, spin the anemometer with your hand or place it in front of a fan. The speed in miles per hour should start to scroll across the LED array. If you press the A button on your micro:bit, it will change the readout to print the direction the vane is pointing as the direction the wind is coming from.

Note: Be sure to set your vane so that N on the micro:bit reading is true north for this reading to be accurate.

Exp5_FinalAssembly

Troubleshooting

  • odd readings— Make sure your wiring is correct, make sure the correct sensors are plugged into the correct RJ11 jack.

  • What is north?— The directions produced by the weather:bit are based off of readings from the vane, you have to personally line up the orientation of your vane to north.

  • It still doesn’t workDrop us a line, we would love to help you figure it out!

Experiment 6: Reading the Rain Gauge

Introduction

Rain, rain, go away; come again another day! In this experiment you will add the rain gauge to your weather meter and use it to track the amount of rain that falls. In the end you will use the micro:bit to keep track of the amount of rain, print it out over the LED array when a button is pressed and then use another button press to reset that value to 0. Ready to get wet? Us too…

Parts Needed

  • 1x micro:bit board (Not included)
  • 1x weather:bit carrier board
  • 1x micro-B USB cable (Not included)
  • 1x Weather Meter
Weather Meters

SEN-08942
76.95
20
micro:bit Board

DEV-14208
14.95
SparkFun weather:bit

DEV-14214
14.95
USB Micro-B Cable - 6"

CAB-13244
1.95
3

Suggested Reading

Introducing the Weather Meter (Rain Gauge)

In the previous experiment you met the wind sensors on the weather meter. Here you meet the rain gauge!

Rain Gauge

The rain gauge is actually quite an ingenious design. Inside of the box is a tiny bucket. When that bucket is full (0.011" of rain) it tips over, both triggering a switch and dumping out the water that is in the bucket, which then allows the bucket to come back to upright. So, for every switch press there is 0.011" of rain. In software we count these triggers and increment the rainfall value.

Hardware Hookup

If you didn’t assembly your weather meter in the previous experiment we created this step by step assembly guide for you to follow!

New!

Weather Meter Hookup Guide

July 20, 2017

How to assemble your very own weather meter!
Note: Once you have assembled your weather meter we highly recommend labeling the two cables for the wind and rain sensors. This will make your life much easier in the long run!

Once you have completed the assembly of the weather meter, find the cable for the rain gauge and plug it into the RJ-11 connector on the weather:bit labeled “rain”.

rain

Hope you have an umbrella!

Running Your Script

Please open a browser window and navigate tohttps://makecode.microbit.org. This should open the MakeCode environment that you used to install the weather:bit package.

Code to Note

Code to Note Exp 6

Start Rain Monitoring

To use the rain gauge you need to add the Start Rain Monitoring block to your On Start Block for it to be able to function correctly. It sets up the micro:bit hardware correctly to be able to read the rain gauge correctly.

Rain

The rain block returns the number of inches of rain that the gauge has measured as a whole number. This variable block stores that value until your micro:bit is reset or power cycled (turned off and on again).

Show LEDs

We used the Show LEDs block to draw an image of the sun. If MakeCode doesn’t have just the right icon for you pre-drawn you can make your own using this method.

Reset

The reset block resets the code that you have on your micro:bit. This is the same as pressing the reset button on the back of the micro:bit, but at times it is useful to be able to do this in software. A great example would be that you couldn’t reach the back of the micro:bit for some reason.

What You Should See

Once you power up your micro:bit, you should see a sun show up on the LED array. Once the amount of rain fallen goes over 1" the LED array will display an umbrella and every 10 seconds the number of inches of rain fall since you started your program.

Exp 6 Final Assembly

To restart the counter, press the A button or, if you can reach it, the reset button on the back of the micro:bit.

Troubleshooting

  • I am getting a lot or rain?— Every time the bucket tip, it is measured as rainfall. If you bump into the sensor or if it is vibrated it may trigger the sensor and you get a false reading.

  • Getting an Odd reading?!— Make sure the rain gauge is plugged into the proper RJ11 jack and there is a “click” when you insert it all the way.

  • It still doesn’t workDrop us a line, we would love to help you figure it out!

Experiment 7: Logging to the MicroSD Card

Introduction

We are almost done with our whirlwind series of weather experiments. In this final experiment we will look at how to log all of this amazing weather data to a microSD card using the OpenLog.

Parts Needed

  • 1x micro:bit board (Not included)
  • 1x weather:bit carrier board
  • 1x micro-B USB cable (Not included)
  • 1x OpenLog (with headers)
  • 1x microSD card (NOT INCLUDED WITH THIS KIT)
SparkFun OpenLog

DEV-13712
14.95
17
micro:bit Board

DEV-14208
14.95
SparkFun weather:bit

DEV-14214
14.95
USB Micro-B Cable - 6"

CAB-13244
1.95
3
MicroSD Card with Adapter - 8GB

COM-11609
13.95
2

Suggested Reading

Introducing the SparkFun OpenLog

OpenLog

The OpenLog Data Logger is a simple-to-use open source solution for logging serial data from your projects. The OpenLog provides a simple serial interface to log data from a project to a microSD card.

The primary interface with the OpenLog is the FTDI header on the board edge. This header is designed to plug directly into the weather:bit carrier board’s serial port, which allows the micro:bit to send data over a serial connection to the OpenLog.

Header

There are two status LEDs on the OpenLog to help you with troubleshooting.

  • STAT1— This blue indicator LED toggles on/off when a new character is received. This LED blinks when serial communication is functioning.
  • STAT2— This green LED is connected to Arduino D13 (SPI Serial Clock Line/ATmega328 PB5). This LED only blinks when the SPI interface is active. You will see it flash when the OpenLog records 512 bytes to the microSD card.

Stat LEDs

Hardware Hookup

You are going to love this! First thing is that you need to insert a microSD card into the OpenLog with the text side “up” as shown in the image below.

Exp7_HookUp1 | Adding a microSD card

Make sure the card “clicks” into place and stays in place.

Exp7_HookUp2 | microSD card inserted OpenLog

Next insert the OpenLog’s pins into the serial port on the weather:bit carrier board as shown below. Make sure that all of the pins are aligned and inserted correctly. Offsetting these pins could end in damaging your OpenLog or micro:bit. Finally, if you haven’t already, plug your micro:bit into the weather:bit. With that you should be good to go!

Exp7_HookUp3

Running Your Script

Please open a browser window and navigate tohttps://makecode.microbit.org. This should open the MakeCode environment that you used to install the weather:bit package.

Code to Note

Code to Note Exp 7

Serial Redirect To

We use the Serial Port on the weather:bit board to write data to the SparkFun OpenLog. To do this we need to do some setup for the micro:bit to use it correctly. We do this through the Serial Redirect To block placed in our On Start block.

In the Serial Redirect To block we set the transmit (TX) and receive (RX) pins. In this case we use pins 15 and 14. We also set the baud rate which is the rate at which two devices “agree” to communicate at. The OpenLog is preprogrammed to communicate at 9600 baud, so that is what we will set it at.

Join

The join block is one of the most useful blocks out there. You use it to join pieces of data together to build a long string that you then store in a variable. For example for our header we stored comma separated names as a single variable called header. The join blocks standard size is 2 slots. To add more slots click on the gear button and drag more slots in place as you have with the if / else if statements in previous experiments.

Serial Write Line

To send data to the OpenLog we use the Serial Write Line block. This command sends whatever data you attach to it over the serial lines you have specified in your Serial Redirect to block with a carriage return at the end of it.

Running Time(ms)

The running time block returns the number of milliseconds that the micro:bit has been powered up and running the current program. We are using it as a timestamp for data logging since there is no access to a realtime clock.

What You Should See

When you power your micro:bit, you will eventually see an “X” on the LED array. Press the A button to start logging data every 30 seconds. A check mark will be displayed on your LED array. Let the program run for a couple of minutes and press the A button again. You will see an “X” again. It is now safe to remove the microSD card from the OpenLog.

Exp 7 Powered without X

Now, using the microSD card slot on your computer or an adapter, open up the microSD card on your computer. You should see two files. One is a config file, which you can ignore. The other, which has a file name of “LOGXXXXX.txt,” is what you are looking for; go ahead and open it.

openlog files

The data in this text file is a Comma Separated Value (CSV) set of the data you sent it. The format is that the first line is the “header,” which is the name of each “column.” You see that our header is the following:

time,temperature,humidity,pressure,altitude

The header is followed by lines of values associated with each reading.

In fact, if you are a user of Google Sheets you can import this text file as a CSV and then graph these values pretty easily. We recommend this quick guide from Google on how to import a .txt file as a CSV into sheets.

Troubleshooting

  • Doesn’t seem to be logging— Make sure your openLog is oriented correctly in the Serial port

  • The log has weird characters—Make sure you have the serial baud rate set to 9600!

  • It still doesn’t workDrop us a line, we would love to help you figure it out!

Resources and Going Further

We produce a number of other kits and carrier boards that you can hook up to your micro:bit to help take your projects to the next level. Here is some further reading that may help you along in learning more about the world of electronics.

For more information on our micro:bit ecosystem, check out these tutorials:

New!

SparkFun Inventor's Kit for micro:bit Experiment Guide

The SparkFun Inventor’s Kit for micro:bit Experiment Guide is your map for navigating the waters of beginning embedded electronics, robotics and citizen science using the micro:bit. This guide contains all the information you will need to explore the 12 circuits of the SparkFun Inventors Kit for micro:bit.
New!

micro:arcade Kit Experiment Guide

We love games! We love writing games, building games and yes, even building game consoles. So we want to introduce to you the micro:arcade kit for the micro:bit!

micro:bit Breakout Board Hookup Guide

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

For more Internet-connected weather fun, check out our these other weather data tutorials.

Weather Station Wirelessly Connected to Wunderground

Build your own open-source, official Wunderground weather station that connects over WiFi via an Electric Imp.

Photon Weather Shield Hookup Guide V11

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

Arduino Weather Shield Hookup Guide V12

Read humidity, pressure and luminosity quickly and easily. Add wind speed, direction and rain gauge for full weather station capabilities.
New!

ESP32 Environment Sensor Shield Hookup Guide

SparkFun's ESP32 Environment Sensor Shield provides sensors and hookups for monitoring environmental conditions. This tutorial will show you how to connect your sensor suite to the Internet and post weather data online.

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

micro:bot Kit Experiment Guide

$
0
0

micro:bot Kit Experiment Guide a learn.sparkfun.com tutorial

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

Introducing the micro:bot Kit

The micro:bit is a great platform for learning how to build and program robots! Combining the micro:bit with the SparkFun moto:bit carrier board creates a flexible, low-cost robotics platform for anyone from students getting started with the micro:bit to the engineer looking to quickly prototype or build a proof of concept.

The micro:bot kit is the extension of that idea: build simple robots quickly that leverage the capabilities of the micro:bit while implementing peripheral sensors and motor functions with simple programming in the Microsoft MakeCode environment as a gateway into robotics.

What’s Included in the Kit?

SparkFun micro:bot kit

KIT-14216
59.95

The kit includes the following parts:

Note: The kit does not include 4xAA batteries or a micro:bit. You will need to purchase one separately.

micro:bit Board

DEV-14208
14.95

How to Use This Guide?

This guide is designed to get you started with the moto:bit board and the SparkFun micro:bot kit in a straight forward and simple way. We demonstrate each component’s functionality and the corresponding code to make it work.

While you explore this guide, we urge you to take your time and tinker with the sensors, code, and the ideas shared to build something tailored to your application and creativity. Our goal is to get you enough information and know-how to make you dangerous and then release you into the wild to do whatever you do with your robot.

Be sure to share your projects with us over Twitter or Facebook! We are excited to see you Start Something!

Suggested Reading

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

Accelerometer Basics

A quick introduction to accelerometers, how they work, and why they're used.

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.

Hobby Servo Tutorial

Servos are motors that allow you to accurately control the rotation of the output shaft, opening up all kinds of possibilities for robotics and other projects.

Getting Started with the micro:bit

The micro:bit is a compact, powerful programming tool that requires no software installation. Read on to learn how to use it YOUR way!

Open Source

All of our experiments and guides are licensed under the Creative Commons Attribution Share-Alike 4.0 Unported License. Feel free to remix and reuse our work. But please, share the love and give us attribution for our hard work!

To view a copy of this license visit this link, or write: Creative Commons, 171 Second Street, Suite 300, San Francisco, CA 94105, USA.

About the moto:bit Board

The moto:bit is a carrier board for the micro:bit. Similar to an Arudino shield, it is designed to add functionality to the micro:bit without the hassle of a number of other boards, soldering, and all of those jumper wires.

SparkFun moto:bit

DEV-14213
14.95

In this case, the moto:bit takes a micro:bit and turns it into a full blown robotics platform. Wondering what you can do with it? Well here are a few things…

  • Control motors through an onboard H-Bridge
  • Read digital sensors such as line and bump sensors
  • Read analog sensors like light sensors, temperature sensors, etc
  • Control servo motors
  • I2C port for extending functionality

That is a lot of options in terms of bells and whistles! Let’s take a closer look at the board and go over each section.

Edge Connector

The moto:bit connects to the micro:bit via an edge pin connector. This makes it handy to swap out micro:bits for programming, and it creates reliable connections to all of the different pins on the micro:bit.

Edge Connector

H-Bridge and Motor Pins

An H-Bridge is a chip that is the heart of a robot when it comes to driving motors and more specifically driving motors in both directions. Depending on the electrical state of specific pins on the H-Bridge, a motor drives forwards, backwards, and at different speeds. The good thing about this board is that if you are using Microsoft MakeCode, you actually don’t really need to know a whole lot about the H-Bridge itself.

Hbridge

To connect the hobby motors that are included in the kit, you can insert them into the 2-pin female connectors just above the motor pins. The connectors are highlighted in the image below. Keep in mind that direction the hobby motors will move depends on the code to control the H-bridge motor driver, how the motors are attached to a chassis, and the way the motors are wired to the input pins.

MotorInputPins

Motor Control Switch

The moto:bit has a switch that controls the power supply to the motors. That way you can have the robot powered while working on it or programming it and know that the robot is not going to start moving and drive off of the table. Believe us… that happens all the time!

Motor Control Switch

Input and Output Pins

The male pins on the moto:bit are for hooking up various inputs and outputs on your robot without using a breadboard to build elaborate circuits.

I/O Pins

We have a number of sensors and actuators that are built in this pin formation and will work with this board.

SparkFun Line Follower Array

SEN-13582
29.95
6
Wheel Encoder Kit

ROB-12629
12.95
4
SparkFun RedBot Sensor - Mechanical Bumper

SEN-11999
4.95
2
SparkFun RedBot Buzzer

ROB-12567
5.95
SparkFun RedBot Sensor - Accelerometer

SEN-12589
9.95
SparkFun RedBot Sensor - Wheel Encoder

SEN-12617
9.95

Servo Ports

No robot is complete without an arm, a swiveling “head,” or some other type of movement other than wheels. Notice that a couple of the pin groups are designated as “Servo”. You can connect servo motors directly to these pins and use them right out of the box with Microsoft MakeCode.

Male Servo Pins

I2C Port

We broke out the I2C port of the micro:bit to an external port so that you can add any I2C capable sensor or actuator you can think of. It is standard pin arrangement to many of our I2C sensor breakout boards.

I<sup>2</sup>c

Power

A standard barrel jack connector is used for easily powering your robot. We find that a 4xAA battery pack works great, but it will accept between 3 and 17 volts at the barrel jack. That’s a whole lot of robo-power!

Barrel Jack

Assembling Your Robot

This section will cover how to assemble your robot chassis.Assembly time: 30-60 minutes

The robot chassis requires the following pieces to build. You’ll find most of them in your SparkFun micro:bot kit.

Note: Several of the parts need to be snapped out of the main chassis panels.

micro:bot chassis parts

Click on the image for a closer look.

LetterPartQty
ABottom Chassis Plate1
BTop Chassis Plate1
CFront Motor Mount2
DRear Motor Mount2
ESide Strut4
FEncoder Mount (Not Used in this Guide)2
Gmoto:bit Mount2
HBattery Pack Clip1
ILine Follower Mount1
JLine Follower Mount Plate1
KJumper Wire — 3-pin, 6"3
LWheels2
MNub Caster1
NDC Motors2
OLine Follower Boards3
P4xAA Battery Holder1
Q4xAA Batteries (Not Included)3
micro:bitNot Included in Kit1
moto:bitIncluded in Kit1

No Tools Necessary

The robot chassis does not require any additional tools.

WARNING: Do not attempt to remove chassis parts by squeezing them with pliers. If you try to muscle it too much you risk breaking them and compromising the structure of your robot. Handle with care. ;)

No Pliers

A Note About Orientation

When we talk about the “front,” “left,” “right,” and “back” of the Shadow Chassis, we are referring to specific sides of the robot when viewed from above.

micro:bot Orientation

Notice that we consider the SparkFun moto:bit to be on the “back” of the bot and the Bumper Whiskers and Line Follower Boards to be in the “front.”

Assembly

Installing Motors

Let’s begin by installing the motors that will control the wheels. Locate the following:

Installing Motors Parts

Attach Rear Motor Mounts

Hold the wires near the middle of the Motor (N), and carefully slide a Rear Motor Mount (D) in from the side and over the two motor wires. Be careful not to snag the wires, the cable tie, or the clear plastic strap.

Attaching Rear Motor Mounts

Holding the motor wires, gently twist the Rear Motor Mount counter clockwise so that it snaps in place on the motor and the wires are centered in the gap of the motor mount. Again, be sure not to snag the wires under the motor mount.

Adjusting Rear Motor Mount

Repeat the process for the second motor, ensuring that it is a mirror image of the first.

Both Rear Motor Mounts

Attach the Front Motor Mounts

Slide a Front Motor Mount (C) onto the protruding eyelet on the front of a Motor (N). Ensure the rounded sides of the motor mounts are facing the same way.

Attaching Front Motor Mounts

Repeat the process for the second motor.

Both Front Motor Mounts

Attach the Motor Assemblies to the Chassis

Snap one of the motor assemblies into the left two horizontal slots of the Bottom Chassis Plate (A). Make sure that the rounded edges of the motor mounts and the wires are facing toward the center of the chassis. Repeat for the opposite motor.

Attaching Motor Assemblies to Chassis

Attach the Wheels

Slide one Wheel (L) onto the plastic shaft of a Motor (N). Look at the motor shaft. Notice it has two flat edges. Make sure to line up the flat edges of the motor shaft with the flat edges of the wheel.

Attaching Wheel

Repeat with the other wheel.

Two Wheels Ready to Roll

Installing the Line Sensors

This section will cover the Line Following Sensors array assembly. You’ll first build the Line Following array and then attach it to the chassis. Locate the following:

Line Sensor Parts

Construct the Line Follower Assembly

Attach the three Line Follower Boards (O) to the Line Follower Mount (I) such that the rectangular pegs in the Line Follower Mount poke through the mounting holes in the Line Follower Boards. Make sure the sensors are facing away/down from the clip of the mount.

Line Follower Boards on Mount

Place the Line Follower Mount Plate (J) on top of the Line Follower Mount (I) so that the center clip of the mount is poking through the center slot of the plate.

Mount Plate on Top of Line Follower Boards

Attach the Cables

You will need to connect a 3-Wire Jumper Cable (K) to each of the Line Follower Boards (O). Note the color of the wire attached to each pin.

Line Follower Connections:

Jumper Wire ColorRedBot Sensor - Line Follower
RedGND
OrangeVCC
YellowOUT

Attach all 3 cables to the 3 Line Follower Boards. Notice that the yellow wire should be on the right (out) and the red wire should be on the left (ground).

Attach Cables to Line Follower Boards

Attach the Line Follower Assembly to the Chassis

Locate the wide, rectangular slot near the front of the chassis and snap the line follower assembly in from the bottom side of the chassis. Route the cables through the large hole in the bottom plate.

Attach Line Follower Assembly to Chassis

The bottom of your chassis should look like the following image allowing the line sensors to be facing down.

Line Followers Mounted Bottom View

Final Assembly

With the motors and a few sensors attached, we can assemble the main body of the robot. Locate the following:

Side Strut and Nub Caster Assembly

You will also need the Top Chassis Plate and Bottom Chassis Plate assemblies, which have any additional parts and sensors you attached in previous steps.

Attach the Nub Caster

Snap the Nub Caster (M) into the slot on the back of the Bottom Chassis Plate assembly. Make sure the Nub Caster is on the side opposite the motors (the bottom side).

Attach Nub Caster

Add the Side Struts

Snap the four Side Struts (E) into the diagonal slots on the four corners of the Bottom Chassis Plate assembly.

Attach Side Struts

Pull the cables through the cutouts on the chassis.

Cables through Cutouts

Route the Cables

Position the Top Chassis Plate over the Bottom Chassis Plate – but do not snap the two plates together yet. Make sure that the front sides of each plate line up.

Route the wires and cables through the left and right oval slots in the Top Chassis Plate assembly as shown. For the center line follower sensor, route this cable through the right oval slot. Note that SIK-only cables are listed with an asterisk (*).

NOTE: It might be a good idea to use some pieces of masking tape to mark which cables go to which component. It’s not necessary, but it might help keep things organized.

Cable Routing:

Cable ConnectionOval Side
Left Line FollowerCenter
Center Line FollowerCenter
Right Line FollowerCenter
Left Motor wires (red and black)Left
Right Motor wires (red and black)Right

Pull Wires Through and Prepare Top Plate

Attach Top Chassis Plate Assembly

Line up the Top Chassis Plate on top of all the struts, and carefully snap the Top Chassis Plate assembly onto the side struts and motor mounts. Press gently above each side strut individually until they each snap into place. If you have the Bumpers installed, make sure the boards are between the top and bottom plates.

Snap Top Plate On

If you need to remove the plate to change anything, gently pull upward on each side strut individually. Do not attempt to use pliers or hand tools, or you may end up snapping the plastic clip.

Attaching the moto:bit

In this section, you will add brains of the robot: the SparkFun moto:bit. Locate the following:

Attaching moto:bit

You will also need the full chassis assembly, which contains any additional parts and sensors you attached in previous steps.

Attach the moto:bit Mounts

Snap the two moto:bit mounts (G) into the vertical slots in the back of the top chassis plate near the large rectangular opening.

Add Controller Board Mounts

Both of these mounts will enable your moto:bit board to be mounted to the chassis.

Both moto:bit Moutns

Add the moto:bit

Before you snap in the moto:bit board, insert your micro:bit into the moto:bit as shown here.

Inserting micro:bit into moto:bit

The moto:bit snaps into the lowest of the notches on the moto:bit Mounts (G). Make sure the power jack is facing the left side of the robot. Push gently and evenly until it snaps into place.

Snap In Main Board

NOTE:The other slots in the moto:bit mounts can be used to hold the Arduino UNO or the Sparkfun RedBoard.

Connecting the Cables

It is time to connect the jumper wires; it is really important that these connections are right.

Loose Wires

You can follow along with the pin out tables or scroll down for a diagram. Trace each cable poking through the top chassis plate to make sure you know what it is connected to.

Please Note: When you have the micro:bot upright and the front of the chassis facing away from you, "left" sensors/motors will be on the left side and "right" sensors/motors will be on the right side. Also, the motor wires are intentionally switched for the right motor -- see notes below.

micro:bot Annotated

Line Followers


Left Line Follower:

SparkFun moto:bit PinsJumper WiresLeft Line Follower Board
P03-Wire Jumper Cable - YellowOUT
3.3V3-Wire Jumper Cable - OrangeVCC
GND3-Wire Jumper Cable - RedGND

Center Line Follower:

SparkFun moto:bit PinsJumper WiresMiddle Line Follower Board
P13-Wire Jumper Cable - YellowOUT
3.3V3-Wire Jumper Cable - OrangeVCC
GND3-Wire Jumper Cable - RedGND

Right Line Follower:

SparkFun moto:bit PinsJumper WiresRight Line Follower Board
P23-Wire Jumper Cable - YellowOUT
3.3V3-Wire Jumper Cable - OrangeVCC
GND3-Wire Jumper Cable - RedGND

Line Follower Connection


Motors


Left Motor:

SparkFun moto:bit PinsLeft Motor Jumper Wires
LEFT MOTOR - REDSoldered on Motor Jumper Wire - RED
LEFT MOTOR - BLACKSoldered on Motor Jumper Wire - BLACK

Right Motor:

moto:bit PinsRight Motor Jumper Wires
RIGHT MOTOR - REDSoldered on Motor Jumper Wire - BLACK
RIGHT MOTOR - BLACKSoldered on Motor Jumper Wire - RED

Black Wire Motor

Red Wire Motor

Once all wires are connected it should look like the following image.

All Wire Connections Made

Batteries

The last step is to provide a power source for the micro:bot. You will need to provide your own AA batteries (Q). Locate the following:

Batteries and Clip Parts

Insert Batteries

Insert the AA batteries into the Battery Holder (P). Makes sure the batteries are facing the correct direction, as per the markings inside of the Battery Holder.

Insert AA Batteries into Pack

Attach Battery Pack

Insert the Battery Holder (P) with batteries into the back cavity of the chassis. Position the Battery Holder so that the barrel jack cable comes out on the left side of the robot.

Insert Battery Pack

Insert the Battery Pack Clip (H) on top of the battery pack.

Insert Battery Pack Clip

Twist and position the clip so that it rests on top of the battery pack.

Attach Battery Pack Clip

Push the clip down into the vertical slots in the Bottom Chassis Plate so it snaps in place.

Snapping Battery Clip into Chassis

Route the barrel jack cable out of the left side of the chassis and up to the moto:bit.

Route Barrel Jack Cable

Plug the barrel jack cable into the barrel connector on the side of the moto:bit carrier board.

Plug into Barrel Connector

Changing the Batteries

If you find that you need to replace the batteries in the micro:bot, the process is simple. Unplug the battery pack from the moto:bit.

Unplug the Batteries

Turn the micro:bot over and push on the Battery Holder through the hole in the Bottom Chassis Plate. This will cause the Battery Pack Clip to unsnap from the Bottom Chassis Plate.

Push on battery pack to unsnap it

Slide the Battery Pack and Clip out from the back of the micro:bot.

Remove Battery Clip

Remove Battery Pack

Change the batteries, and follow the steps in Attach Battery Pack section above to put the Battery Pack back in the micro:bot.

Installing the moto:bit Package in MakeCode

To make the most out of the moto:bit with the least amount of coding, use the Microsoft MakeCode package we wrote for the moto:bit board.

Packages

If you have used Arduino before, you probably know about a thing called a library; which is a collection of code that extends the functionality of the core programming language. MakeCode packages work the same way.

There are some amazing differences between Arduino libraries and MakeCode packages. One of them is that MakeCode packages include JavaScript functions, which you can use when programming in text, as well as all of the blocks you need to program using the block method. This makes learning and using new packages straightforward and shortens the time to awesome when setting out to build the project of your dreams.

Installing a MakeCode Package

To install or add a new package to your MakeCode toolbox (the list of different block groups), click on “Advanced” and then on “Add Package.”

alt text

From here you can search for “SparkFun moto-bit,” and it should show up as a public package in the list. Go ahead and click on it.

alt text

This will add all of the blocks to your toolbox. In general, this is a bit tricky as, depending on how the package was written, it may either have its own toolbox or just add blocks to the existing ones. Take a look at your toolbox; for the moto:bit you should see…

alt text

Great! You have now installed the moto:bit package and are ready to use the board as well as the components that come in the micro:bot kit. As a side note, for every new MakeCode project that you make, you will have to load packages over again. Not a big deal, but noteworthy! Now, let’s put your package to good use and get your robot moving!!!

Experiment 1: Driving and Turning

Introduction

The “Hello World” for the robotics world is getting your robot moving! Driving forwards, backwards and steering is goal #1 when you are dealing with wheeled / moving robots. This experiment will cover just that: getting your robot moving using our moto:bit software package for Microsoft MakeCode. Once you get through this first experiment you will be golden!

Parts Needed

  • 1x micro:bit board (Not Included)
  • 1x Micro B USB Cable (Not Included)
  • 1x moto:bit carrier board
  • 2x Wheels
  • 1x Assembled shadow chassis
  • 2x Hobby Gear Motors
  • 1x 4xAA Battery Holder
  • 4x AA Batteries (Not Included)

Didn’t get the kit? Have no fear! Here are the parts you will need to complete this experiment…

micro:bit Board

DEV-14208
14.95
SparkFun moto:bit

DEV-14213
14.95
Hobby Gearmotor - 200 RPM (Pair)

ROB-13302
3.95
Wheel - 65mm (Rubber Tire, Pair)

ROB-13259
2.95
1
Shadow Chassis

ROB-13301
12.95
7
Battery Holder - 4xAA to Barrel Jack Connector

PRT-09835
2.49
1500 mAh Alkaline Battery - AA

PRT-09100
0.5

Suggested Reading

Motors and Selecting the Right One

Learn all about different kinds of motors and how they operate.

Getting Started with the micro:bit

The micro:bit is a compact, powerful programming tool that requires no software installation. Read on to learn how to use it YOUR way!

Introduction to the Motors and Controlling Them

motor pair

Motors take electrical energy and turn it into mechanical energy through putting a current through a coil of wire that creates a magnetic field. This then interacts with magnets in the motor, causing a push / pull effect. If you do that in a proper spacing and timing then you can spin a shaft.

These motors operate in a similar was as mentioned above, but they have a bit of help; a gear box. The ratio of the gearbox is 120:1, which means that for every 120 rotations of the motor shaft you get one rotation at the end of the gear box. This is a good thing because it gives our robot enough strength (torque) to turn wheels. In this case our gearbox also changes the axis of the shaft so that we can easily use them to drive our robot.

Hardware Hookup

You should have already hooked up the motors during the assembly process of putting the robot together. But, we have a couple of things that we would like you to double check!

Initial Motor Assembly

First of all make sure that your red and black wires are plugged into your moto:bit and that they are in the correct ports. If you look closely the right and left ports are opposite from one another.

Wires Plugged In

Why is that? Well, in robotics the right and left motors are mirrors of one another, which means they go in opposite directions from one another to go forward, hence the ports being backwards. If you plug them in as the same direction your robot would spin in a circle rather than drive forward! Weird, but true.

Running Your Script

We are going to use Microsoft MakeCode to program the micro:bit. Please open a browser window and navigate to makecode.microbit.org. This should open the MakeCode environment that you used to install the moto:bit package in.

Did you install the moto:bit package? To add the moto:bit package as instructed in the Installing the moto:bit Package in MakeCode section of this tutorial.

makecode screen shot

Note: If this is your first time programming a micro:bit please be sure to see our Getting Started with the micro:bit tutorial on how to get your MakeCode program onto your micro:bit.

Now, you can either download the following example script below and drag and drop it onto your micro:bit, or use it as an example and build it from scratch in MakeCode.

Code to Note

exp_1 code

On Button Pressed

The On Button Press is an event function. Any code blocks that are placed inside of the block will only execute when that event happens. In this block when the A button is pressed on your micro:bit your robot will start moving. When it gets to the end of the program it will stop again until you press the A button again.

Turn Motors

The Turn Motors block gives you the ability to turn the motors ON or OFF in software. They are naturally OFF, so anytime you want to drive motors, you need to set them to ON. A good practice is to turn them OFF when your robot completes its task or should not be moving for long periods of time, this saves batteries and wasted power consumption.

Move Motors At

The Move Motors block is the basis of the moto:bit software package. You use this block by selecting which motor you want to control (RIGHT or LEFT), its direction (FORWARD or REVERSE) and the throttle / power percentage you would like the motor to spin at (0-100%). For your bot to move forward you need to have both motors drive in the same direction. To turn, or pivot, you set the motor directions in an opposite configuration.

Pause

The pause block is like a code stop sign. It tells the micro:bit to wait for a given amount of time in milliseconds. While it is waiting whatever you told before the pause will keep happening. So, if you want your robot to drive forward for 2 seconds, you set the robots motors to drive forward and then pause for 2000 milliseconds and then have the motors do something else, like stop.

What You Should See

Once your script uploads to your micro:bit make sure the motors switch is changed from “STOP MOTORS” to “RUN MOTORS.” Press the A button on your micro:bit and your robot will drive forward for 1 second, pivot and the drive forward for another second then stop.

Pressing Button A

Go Further: Now that you have a moving robot, can you write a program that would tell your robot to drive in a square? How about a star? What about having it dance?

Troubleshooting

  • Robot not moving - Make sure your motors are hooked up correctly in the motor ports and your motor power switch is set to “run”, the battery pack is plugged in and you have fresh batteries

  • Moving in reverse?! - You can flip the wiring of your motor or use the Set Motor Invert block in your On Start block to change what is forward vs. reverse.

  • moto:bit package is not showing up - Try installing it again from the add package option in MakeCode

Experiment 2: Staying in a Box

Introduction

Robots are smart! They are smart because they use sensors to detect what the world around them and then respond to those conditions. One of the conditions our robot can respond to is the darkness of the surface that it is driving on. It can detect lines, a gradient of darkness or a blacked out area. In this experiment you will program your robot to stay inside of a box that you have drawn on a surface.

Parts Needed

  • 1x micro:bit board (Not Included)
  • 1x Micro B USB Cable (Not Included)
  • 1x moto:bit carrier board
  • 3x Line following Sensors
  • 1x micro-B USB Cable
  • 1x 4xAA Battery Holder
  • 4x AA Batteries (Not Included)

Didn’t get the kit? Have no fear! Here are the parts you will need to complete this experiment…

micro:bit Board

DEV-14208
14.95
SparkFun moto:bit

DEV-14213
14.95
Hobby Gearmotor - 200 RPM (Pair)

ROB-13302
3.95
Wheel - 65mm (Rubber Tire, Pair)

ROB-13259
2.95
1
SparkFun RedBot Sensor - Line Follower

SEN-11769
2.95
6
Shadow Chassis

ROB-13301
12.95
7
Battery Holder - 4xAA to Barrel Jack Connector

PRT-09835
2.49
1500 mAh Alkaline Battery - AA

PRT-09100
0.5
Jumper Wire - 0.1", 3-pin, 6"

PRT-10368
1.5

Suggested Reading

Getting Started with the micro:bit

The micro:bit is a compact, powerful programming tool that requires no software installation. Read on to learn how to use it YOUR way!

Introduction to the Line Sensors

Line sensor

The Line Follower sensor is an add-on for your shadow chassis that gives your robot the ability to detect lines or nearby objects. The sensor works by detecting reflected light coming from its own infrared LED. By measuring the amount of reflected infrared light, it can detect transitions from light to dark (lines) or even objects directly in front of it.

The sensor has a 3-pin header which connects directly to the moto:bit carrier board via female to female jumper wires. A mounting hole lets you easily connect one or more of these to the front or back of your robot chassis.

Hardware Hookup

Like the motors, you should have already hooked up the line sensors during the assembly portion of this guide. You can go there now for the full assembly instructions. Double check to make sure that the wires are hooked up to your line sensors correctly!

Line Sensor Wire Hookup

The line sensors hookup to your moto:bit via female / female jumper wires that snake through the chassis of your robot up to the moto:bit. The sensors hookup to the moto:bit in the following order:

  • LEFT =>P0
  • CENTER =>P1
  • RIGHT =>P2

Double check to make sure they are hooked up correctly and in the proper orientation

Attached to moto:bit

Running Your Script

Be sure to add the moto:bit package as instructed in the Installing the moto:bit Package in MakeCode section of this tutorial.

Now, you can either download the following example script below and drag and drop it onto your micro:bit, or use it as an example and build it from scratch in MakeCode.

Calibration is very important with the line sensors to work accurately. Your environment will greatly affect the P0 analog readings and thresholds for the surface value so you might have to customize these numbers to suit your application.

Code to Note

Experiment 2 Code Screenshot

Creating a Variable

In Microsoft MakeCode you need to be able to create variables to store information for your robot to compare against, or to just remember. You can use the built in variables under the Variables drawer as shown below.

variable drawer

But, you can also make your own custom variables. To do this click on the Variables drawer and select Make New Variable. You can then name it and use it in your program.

naming variable

Set To

To store a value or piece of information in a variable you use the Set to block. This allows you to select a variable and set it to a value block of your choice. In this case the line sensor value on pin A0. We do this once in the On Start block to get a base reading from the sensor.

Analog Read Pin

To get that base reading from the line sensor we use the Analog Read Pin block to get an analog value (0 - 1023) from the line sensor. 0 is totally black and 1023 is totally saturated white. Your surface will be something probably in between.

If

To compare the current reading of the line sensor to its known baseline value that was captured and stored in the On Start block we use an if statement block. The if block accepts a logical statement. If that statement (Sensor Value < Surface - 30) is true then the if block runs then “then” section of code. If that statement is false then the “else” section of the block is run.

You may be asking yourself why subtract 30 from the surface value. Well, that number is a sensitivity value. The sensor reading fluctuates as the robot moves around, by subtracting 30 from the original surface variable we give the change in lighting a “wiggle room” of 30. If you want your sensor to be more sensitive you make the number smaller, if you need it less sensitive make it bigger.

What You Should See

Once your code is loaded find a light surface, preferably white and add a line of black tape to the surface and press the RESET button on your micro:bit. In fact, if you have a large enough space you can create a 3' square you will be perfect! Change the motor switch from “STOP MOTORS” to “RUN MOTORS.”

Stop Motors

Run Motoes

Your robot will drive forward until the black tape is directly under the center line sensors. When that happens your robot will stop, reverse, pivot a bit and try to drive forward again, hitting a line once more. If it works correctly your robot should stay inside of the box forever!

Go Further: So, you have built a robot corral! Use what you now know to build a maze for your robot to solve on its own!

Troubleshooting

  • Moto:Bit blocks not showing up - Make sure you have a network connection and you have added the package to your makeCode environment.

  • Micro:Bit not showing up on my machine - Try unplugging the USB cable and plugging it back in. Also, be sure that you have the cable inserted all the way into your micro:bit

  • Robot doesn’t detect line - If changing the width of your line doesn’t help, remember line sensor calibration settings can be very sensitive depending on your environment.

Experiment 3: Following a Line

Introduction

OK, you have your robot staying inside of box drawn on the floor, but that still seems a little odd and random. You want your robot to go somewhere, do something and then keep going! In this experiment you will elaborate what you learned from Experiment 2 to get your robot to follow a line.

Parts Needed

  • 1x micro:bit board (Not Included)
  • 1x Micro B USB cable (Not Included)
  • 1x moto:bit carrier board
  • 1x Shadow Chassis
  • 3x Line following sensors
  • 3x Servo style jumper wires
  • 1x micro-B USB Cable
  • 1x 4xAA Battery Holder
  • 4x AA Batteries (Not Included)

Didn’t get the kit? Have no fear! Here are the parts you will need to complete this experiment…

micro:bit Board

DEV-14208
14.95
SparkFun moto:bit

DEV-14213
14.95
Hobby Gearmotor - 200 RPM (Pair)

ROB-13302
3.95
Wheel - 65mm (Rubber Tire, Pair)

ROB-13259
2.95
1
SparkFun RedBot Sensor - Line Follower

SEN-11769
2.95
6
Shadow Chassis

ROB-13301
12.95
7
Battery Holder - 4xAA to Barrel Jack Connector

PRT-09835
2.49
1500 mAh Alkaline Battery - AA

PRT-09100
0.5
Jumper Wire - 0.1", 3-pin, 6"

PRT-10368
1.5

Suggested Reading

Getting Started with the micro:bit

The micro:bit is a compact, powerful programming tool that requires no software installation. Read on to learn how to use it YOUR way!

Introduction to Using Multiple Line Sensors

Multiple Lines Sensors

In the previous experiment you used a single line sensor (the middle sensor) to detect the line on the floor. That is great for staying inside of a line, but now, you need to follow a line. That is where the other two line sensors come in.

Essentially, you want the center sensor to detect the line, but not the other two, meaning that the robot is centered on the line. If one of the side sensors detect a line it means that you are veering to one side or another and your robot should correct itself. We will use the information from multiple sensors combined with an if/else statement block to build a decision tree for your robot to follow.

Hardware Hookup

Note: If you already hooked up your sensors in Experiment 2, please skip this section.

Like the motors, you should have already hooked up the line sensors during the assembly portion of this guide. You can go there now for the full assembly instructions. Double check to make sure that the wires are hooked up to your line sensors correctly!

Hooking Up Line Sensors

Line Sensor Connections to Wire

The line sensors hookup to your moto:bit via female / female jumper wires that snake through the chassis of your robot up to the moto:bit. The sensors hookup to the moto:bit in the following order:

  • LEFT =>PO
  • CENTER =>P1
  • RIGHT =>P2

Double check to make sure they are hooked up correctly and in the proper orientation

Line Sensor Connections to moto:bit

Running Your Script

Be sure to add the moto:bit package as instructed in the Installing the moto:bit Package in MakeCode section of this tutorial.

Now, you can either download the following example script below and drag and drop it onto your micro:bit, or use it as an example and build it from scratch in MakeCode.

Calibration is very important with the line sensors to work accurately. Your environment will greatly affect the P0 analog readings and thresholds for the surface value so you might have to customize these numbers to suit your application.

Code to Note

Experiment 3 Screenshot Code

lCal / rCal

Like in the previous experiment, you need to set a baseline value for the surface that your robot is driving on. This is actually called a calibration value. Like the previous experiment, we need to do this, but for two sensors; right and left. We go through the same routine we did for the single sensor previously, but for the right and left sensors.

On Button Press

As in the first experiment we use the On Button Press block to start the program. This is so you can can get a good base reading and calibrate your sensors without having to wrestle with a robot that is trying to move around.

While

The While block is a logic block that is similar to the loop block, but a bit smarter. The While block accepts a TRUE/FALSE statement, if that statement is true the block will loop whatever code is placed inside of it. If that value is false the While block is simply skipped over. We hardcode a true value into the While block so that it constantly loops when the A button is pressed. That way we have the benefits of both the event block and the loop block without needing complicated programming.

What You Should See

Once you have loaded your script place your robot on a dark line on a light / white background. Make sure you have it centered with the line just underneath the center line sensor. Make sure the motor switch is changed from “STOP MOTORS” to “RUN MOTORS” and press the A button to start.

Stop Motors

Run Motoes

Pressing Button A

Your robot should drive forward until one of the side line sensors detects the line and then it will turn in that direction to correct itself. Depending on your line shape and thickness your robot may “waddle” more or less.

Go Further: Your robot can go where you tell it by following a line. Try building an obstacle course for your robot using the line sensor!

Troubleshooting

  • Robot drives in a circle - Double check your wiring and your code, your robot is not seeing the line. Also, double check that there isn’t something like dust blocking your sensor.

  • Robot isn’t moving - Pesky motor switch! Make sure that is set to “run” and you have fresh batteries

  • Robot waddles a lot! - Change the width of your line.

  • Robot doesn’t detect line - If changing the width of your line doesn’t help, remember line sensor calibration settings can be very sensitive depending on your environment.

Experiment 4: Using the Accelerometer

Introduction

Now, what happens when something bumps into your robot? It just stays there? No! It should move out of the way, or do something. Not a smart robot! In this experiment you will use the accelerometer on the micro:bit to trigger the robot to move and also speed up if it starts to go up hill.

Parts Needed

  • 1x micro:bit board (Not Included)
  • 1x Micro B USB cable (Not Included)
  • 1x moto:bit carrier board
  • 2x wheels
  • 1x assembled shadow chassis
  • 2x Hobby Gear Motors
  • 1x 4xAA Battery Holder
  • 4x AA Batteries (Not Included)

Didn’t get the kit? Have no fear! Here are the parts you will need to complete this experiment…

micro:bit Board

DEV-14208
14.95
SparkFun moto:bit

DEV-14213
14.95
Hobby Gearmotor - 200 RPM (Pair)

ROB-13302
3.95
Wheel - 65mm (Rubber Tire, Pair)

ROB-13259
2.95
1
SparkFun RedBot Sensor - Line Follower

SEN-11769
2.95
6
Shadow Chassis

ROB-13301
12.95
7
Battery Holder - 4xAA to Barrel Jack Connector

PRT-09835
2.49
1500 mAh Alkaline Battery - AA

PRT-09100
0.5
Jumper Wire - 0.1", 3-pin, 6"

PRT-10368
1.5

Suggested Reading

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!

Accelerometer Basics

A quick introduction to accelerometers, how they work, and why they're used.

Getting Started with the micro:bit

The micro:bit is a compact, powerful programming tool that requires no software installation. Read on to learn how to use it YOUR way!

Introduction to the Accelerometer

closeup of accelerometer

Like the magnetometer (compass), the accelerometer is on the micro:bit itself.

Accelerometers are devices that measure acceleration, which is the rate of change of the velocity of an object. They measure in meters per second squared (m/s2) or in G-forces (g). A single G-force for us here on planet Earth is equivalent to 9.8 m/s2, but this does vary slightly with elevation (and will be a different value on different planets due to variations in gravitational pull). Accelerometers are useful for sensing vibrations in systems or for orientation applications. Vibration is what we are looking for!

Hardware Hookup

You have had the hardware hooked up the whole time! It is on the micro:bit! Feel free to move on.

Running Your Script

Be sure to add the moto:bit package as instructed in the Installing the moto:bit Package in MakeCode section of this tutorial.

Now, you can either download the following example script below and drag and drop it onto your micro:bit, or use it as an example and build it from scratch in MakeCode.

Code to Note

Code to Note

On [Acclerometer]

The micro:bit has a built in accelerometer that measures the gravitational forces that are acting upon it. With other microcontrollers this is sometimes hard to use and make sense of the data you receive from the sensor. But, MakeCode has simplified that for you in an event block under the Input drawer (you will see it as On Shake) that allows you to pick a number of different force levels, orientations and even patterns (like shaking it). We use this to detect a number of orientations that you can put your robot in. For example the motors will only be ON in the screen up orientation.

If you tap the robot hard enough it will run / drive away from you. If you flip it over the motors will turn off. Same thing holds true if you place it on its tail with the micro:bit pointing up.

Try playing around with the different events that you can trigger with the accelerometer. Can you get it to detect bumping into an object like the wall and have it respond???

What You Should See

Once your code is loaded to your micro:bit and your motor switch is set to “RUN MOTORS.” Your robot should not do anything at first. Give it a good tap / smack on top of the micro:bit. If you apply enough force to it your robot should run away. To stop your robot either flip the robot over to its back the motors should stop, or pick it up and set the robot on end with it sitting on its tail with the micro:bit logo pointing up. To run the program again, return the robot to its wheels right side up and smack it again.

Go Further: You can use the idea of detecting a bump in different ways. Try to write a program that giving your robot a nudge or tap starts it to drive forward for a bit, then you need to nudge it again a bit.

Troubleshooting

  • Robot Doesn’t Move - Double check to make sure you have uploaded the new code to your board. Also, make sure your motor switch is set to the “RUN MOTORS” position.

Experiment 5: Controlling a Servo - Battle Bot

Introduction

Your robot should do something more than just drive around! Maybe control a small robotic arm, a gripper or even a weapon (see the bonus experiment if this peaks your interest!) of some kind. In this experiment you will integrate servo motors with your robot to build a Battle Bot with Jousting Lances. This experiment combines all the elements you’ve learned so far in this tutorial.

Parts Needed

  • 1x micro:bit board (Not Included)
  • 1x moto:bit carrier board
  • 2x wheels
  • 1x assembled shadow chassis
  • 2x Hobby Gear Motors
  • 2x Hobby servos
  • 1x 4xAA Battery Holder
  • 4x AA Batteries (Not Included)

Didn’t get the kit? Have no fear! Here are the parts you will need to complete this experiment…

micro:bit Board

DEV-14208
14.95
SparkFun moto:bit

DEV-14213
14.95
Servo - Generic (Sub-Micro Size)

ROB-09065
8.95
8
Hobby Gearmotor - 200 RPM (Pair)

ROB-13302
3.95
Wheel - 65mm (Rubber Tire, Pair)

ROB-13259
2.95
1
SparkFun RedBot Sensor - Line Follower

SEN-11769
2.95
6
Shadow Chassis

ROB-13301
12.95
7
Battery Holder - 4xAA to Barrel Jack Connector

PRT-09835
2.49
1500 mAh Alkaline Battery - AA

PRT-09100
0.5
Jumper Wire - 0.1", 3-pin, 6"

PRT-10368
1.5

Craft Supplies

  • 2x Skewers
  • Hot Glue and Gun
  • Optional: Electrical Tape

Suggested Reading

Hobby Servo Tutorial

Servos are motors that allow you to accurately control the rotation of the output shaft, opening up all kinds of possibilities for robotics and other projects.

Getting Started with the micro:bit

The micro:bit is a compact, powerful programming tool that requires no software installation. Read on to learn how to use it YOUR way!

Introduction to the Servo Motor

alt text

Unlike the action of most motors that continuously rotate, a servo motor can rotate to and hold a specific angle until it is told to rotate to a different angle. You can control the angle of the servo by sending it a Pulse Width Modulation (PWM) pulse train (turning a pin on and off really fast at different intervals); the PWM signal is mapped to a specific angle from 0 to 180 degrees in the servo block in MakeCode.

Inside of the servo there is a gearbox connected to a motor that drives the shaft. There is also a potentiometer that gives feedback on the rotational position of the servo, which is then compared to the incoming PWM signal. The servo adjusts accordingly to match the two signals.

Hardware Hookup

In this experiment you will actually be using two different servo motors to create a Battle Bot! One will be used as a “left” jousting lance and the other as the “right”. If you look at the servos, you will notice that they three wires have different colors; red, black and white. Red is the supply voltage, black is ground and white is the signal. Hook the two servos up to the moto:bit at the two labeled servo ports. Make sure you line up ground to ground.

Male Servo Pins

The “right” servo is connected to pin P16 while the “left” is connected to pin P15. Using a bit of hot glue or tape, you can attach the servos to each side of the robot chassis.

Next, you can build the jousting lances by utilizing some grilling skewers! You will only need two that can be cut down to the needed size. You can either glue or tape each skewer to the servo to the supplied attachments. Each servo set comes with a small bag of attachments as seen below. In this experiment, we utilized the double arm micro horn, but any of them will work.

Servo Attachment Package

Don’t have any skewers laying around? Be creative here!

Bot Assembled with Servos

This Battle Bot utilized electrical tape to mount the jousting lances to the servo motors, and it ended up looking something like this…

Battle Bot

Now, set your contraption aside until you have uploaded your code.

Running Your Script

Be sure to add the moto:bit package as instructed in the Installing the moto:bit Package in MakeCode section of this tutorial.

Now, you can either download the following example script below and drag and drop it onto your micro:bit, or use it as an example and build it from scratch in MakeCode.

Code to Note

Don’t be overwhelmed by everything this code has to offer! I know it looks rather menacing, but the truth is that you’ve already done all of this code in previous experiments.

Experiment 5 Screenshot Code

Servo Write Pin to

The Servo Write Pin to block is found under the Pins drawer and it accepts a pin number that you have a servos signal wire attached to as well as an angle that you want it to rotate to. That’s the basics for controlling a servo motor with Microsoft MakeCode!

On Button A, On Button B and On Button A+B

In this example we use the On Button event blocks a lot. They allow us to break out different functions we want without messy if statements.

In this program the On Button A event block resets the calibration value for the table surface for the robot to use as a comparison value and also sets the servo positions to 90 degrees.

Press Button A

The On Button B block is used to set servo position to 45 degrees.

Press Button B

Finally the On Button A+B event block is used to run the program.

If / Then Statements

You may notice that there is a few if / then blocks inside of the if statement in the forever block. This will aid your Battle Bot in making decisions and knowing what it has to do next.

What You Should See

When your code is loaded onto your micro:bit the servo “arms” will move into a starting position and take initial readings for your line sensors to establish a comparison point to the ground environment.

Initially, the Battle Bot will move forward if none of the line sensors detect any kind of obstacle. If the center line sensor detects a direct collision the Battle Bot will immediately start both servos and move backwards. If the left or right line sensors detect an obstacle, the side that detected the obstacle will have the corresponding jousting lance start to move while turning away from it. So your Battle Bot is prepared to defend itself from any oncoming situation!

Go Further: Design and program a path for your robot to follow with a line sensor and figure out a creative way for it to know when to drop something at a specific location. Could you also program it to pick something up?

Troubleshooting

  • Servo moves in the wrong direction - Flip your servos, or change your code so that it rotates the correct direction.

  • Servo doesn’t move at all! - Double check your connections of the servos to the moto:bit to make sure that they are hooked up correctly.

Resources and Going Further

We produce a number of other kits and carrier boards that you can hook up to your micro:bit to help take your projects to the next level. Here is some further reading that may help you along in learning more about the world of electronics.

For more information on our micro:bit ecosystem, check out these tutorials:

New!

SparkFun Inventor's Kit for micro:bit Experiment Guide

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

Getting Started with the micro:bit

The micro:bit is a compact, powerful programming tool that requires no software installation. Read on to learn how to use it YOUR way!
New!

micro:climate Kit Experiment Guide

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

micro:bit Breakout Board Hookup Guide

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

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

Getting Started with MicroPython and the SparkFun Inventor's Kit for micro:bit

$
0
0

Getting Started with MicroPython and the SparkFun Inventor's Kit for micro:bit a learn.sparkfun.com tutorial

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

Introduction to MicroPython

MicroPython is an open source interpreter for the Python programming language developed specifically for microcontrollers. In this experiment guide, we will show you how to get started using MicroPython with the popular micro:bit board and our SparkFun Inventor’s Kit for micro:bit.

SparkFun Inventor's Kit for micro:bit

KIT-14300
49.95
Note: This experiment guide assumes you have experience with programming. If you have never used a programming language before, we recommend checking out the MakeCode version of this guide. MakeCode is a drag-and-drop editor that is great for beginners of all ages learning to program.

When you’re done with this guide, you’ll have the know-how to start creating your own projects and experiments with MicroPython for micro:bit!

Using MicroPython

MicroPython is just an interpreter, so it does not include a space to write and edit code. Luckily, there is an editor we can use to write our Python code. Before you get started, you’ll need to download Mu. Mu is a simple code editor for beginners that runs on Windows, OSX, Linux and Raspberry Pi.

A major benefit of using MicroPython is the interactive REPL. REPL stands for read-evaluate-print loop, which is a very long way to say you can execute code live without compiling it first and then uploading it after. To get the REPL working on Windows, you’ll need to have the Serial Driver for mbed installed.

The applications for Python are extensive, and the advantage to using Python over other programming languages include interacting with other languages and platforms, third-party modules, extensive support libraries, user-friendly data structures and, of course, it’s open source.

Some known issues with using Mu and micro:bit currently are not being able to import third-party modules, not being able to use interrupts, and not having a decent way to map numbers of one range to another. Since importing third-party modules is not supported, we will be copying and pasting the source code in the current Mu MicroPython file. As with learning any new language, Python requires time, patience, self-study and a lot of examples! Keep at it, and we will be here to help you along the way.

Project Files

To download all of the files needed to follow along with all of the experiments, click the button below.

Download the Project Files!

Software Options

To use MicroPython with the micro:bit, there are a few different options.

Suggested Reading

If you have never worked with electronics before, we recommend you be somewhat familiar with the concepts in the following tutorials:

  • Voltage, Current, Resistance, and Ohm’s Law— The most basic concepts in electronics and electrical engineering. Get very familiar with these concepts, as they will be used throughout your electronics adventure.
  • What is a Circuit?— In this guide, we will be building a variety of circuits. Understanding what that means is vital to understanding the Inventor’s Kit.
  • How to Use a Breadboard— First time working with a breadboard? Please check out this tutorial! It will help you understand why the breadboard is great for prototyping and how to use one.

Experiment 0: Hello, micro:bit!

Hello World: A programmer’s first program

A “Hello World” on the micro:bit is a little different. On most microcontrollers this program would be executed using a serial terminal. Instead of using a serial terminal, you can interact with your micro:bit using the built-in LED array. So, the “Hello World” for the micro:bit is to draw something using the LED array!

Let’s first run the program from the REPL, and then we will build a .py script and upload it to the micro:bit. Open Mu, and make sure your micro:bit is connected to your computer with a USB cable.

To open the REPL, click the icon, and you should see a second window appear at the bottom. Type help() and see what happens.

help menu

Click any of the images for a closer look.

From the REPL, type display.scroll("Hello World") and watch your micro:bit’s 5x5 LED array. Now close the REPL by clicking the REPL icon.

For the first MicroPython script, we are going to cover how to add comments, how to import a module, and how to create a loop that will run forever. At the top of the program (above), you’ll see three lines of comments. Comments are created by using the # sign and one space. You can access modules by using from and import. These words tell the interpreter which classes to import from which modules. In this case, we are importing everything from microbit. while True: is how to create a forever loop in Python. The colon is how Python blocks code the way Arduino uses a set of curly brackets. Everything indented under a colon will execute as a block of code.

Type the program above in your Mu editor, or download all the programs from this GitHub Repository. Save it, then click the Flash icon to program your micro:bit.

Let’s display an image next instead of text.

alt text

When typing display.show(Image...), let the helpful info box show you what images come built in. Then try to code your own custom image.

alt text

Experiment 1: Blinking an LED

Introduction

This is experiment 1 - blinking an LED. We get to the fun stuff: adding hardware and constructing circuits.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1X micro:bit Breakout with Headers
  • 1x LED
  • 1x 100Ω Resistor
  • 1x Jumper Wires

Didn’t Get the SIK for micro:bit?

If you are conducting this experiment and didn’t get the Inventor’s Kit, we suggest using these parts:

micro:bit Board

DEV-14208
14.95
Breadboard - Self-Adhesive (White)

PRT-12002
4.95
31
SparkFun micro:bit Breakout (with Headers)

BOB-13989
5.49
Jumper Wires - Connected 6" (M/M, 20 pack)

PRT-12795
1.95
2
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

COM-11507
0.95
2
LED - Basic Red 5mm

COM-09590
0.35

Suggested Reading

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

Introducing the micro:bit Edge Connector

edge connector

To extend the functionality of the micro:bit beyond what is already on the board, we developed a breadboard adaptor. This adaptor board makes it much easier to use all of the pins available on the micro:bit edge connector in a more user-friendly way. We also broke out ground and VCC (3.3 volts) for your convenience.

The adapter board lines up with the pins of a breadboard. We recommend using a full-sized breadboard with this breakout to give you enough room to prototype circuits on either end of the breadboard.

Introducing the LED

alt text

A Light-Emitting Diode (LED) will only let current through in one direction. Think of an LED as a one-way street. When current flows through the LED, it lights up! When you are looking at the LED, you will notice that its legs are different lengths. The long leg, the “anode,” is where current enters the LED. This pin should always be connected to the current source. The shorter leg, the “cathode,” is the current’s exit. The short leg should always be connected to a pathway to ground.

LEDs are finicky when it comes to how much current you apply to them. Too much current can lead to a burnt-out LED. To restrict the amount of current that passes through the LED, we use a resistor in line with the power source and the LED’s long leg; this is called a current-limiting resistor. With the micro:bit, you should use a 100 Ohm resistor. We have included a baggy of them in the kit just for this reason!

Hardware Hookup

Ready to start hooking everything up? Check out the wiring 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

Wiring Diagram for the Experiment

alt text

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Running Your Script

alt text

Code to Note

pin0.write_digital(1) and pin0.write_digital(0)

You’ll see that is is not much different from the previous experiment except for the lines 8 and 10. pin0.write_digital(1) sends a HIGH value, ON or a voltage of 3.3V to pin 0 on the micro:bit. pin0.write_digital(0) sends LOW value, OFF or 0V to pin 0 of the micro:bit.

What You Should See

You should see your LED blink on and off at 1-second intervals. If it doesn’t, make sure you have assembled the circuit correctly and verified and uploaded the code to your board, or see the Troubleshooting section. Change the number in the sleep() and play with the LED blink rate.

Troubleshooting

LED Not Blinking

Make sure you have it wired correctly and the correct pin to ground. Remember, short pin to ground; long pin to signal.

Still No Success

A broken circuit is no fun. Send us an email, 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 will work with a potentiometer. You will learn how to use a potentiometer to control the brightness of an LED by reading a sensor and storing its 0–1023 value as a variable, then using it as a brightness level for the LED.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1x LED
  • 1x 100Ω Resistor
  • 7x Jumper Wires
  • 1x 10kΩ Potentiometer

Didn’t Get the SIK for micro:bit?

If you are conducting this experiment and didn’t get the Inventor’s Kit, we suggest using these parts:

micro:bit Board

DEV-14208
14.95
Breadboard - Self-Adhesive (White)

PRT-12002
4.95
31
Trimpot 10K with Knob

COM-09806
0.95
6
SparkFun micro:bit Breakout (with Headers)

BOB-13989
5.49
Jumper Wires - Connected 6" (M/M, 20 pack)

PRT-12795
1.95
2
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

COM-11507
0.95
2
LED - Basic Red 5mm

COM-09590
0.35

Suggested Reading

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

Introducing the Potentiometer

alt text

A potentiometer is a resistance-based analog sensor that changes its internal resistance based on the rotation of its knob. The potentiometer has an internal voltage divider enabling you to read the change in voltage on the center pin with a microcontroller (the micro:bit). To hook up the potentiometer, attach the two outside pins to a supply voltage (5V in this circuit) and ground. It doesn’t matter which is connected where, as long as one is connected to power, and the other to ground. The center pin is then connected to an analog input pin so the micro:bit can measure the change in voltage. When you twist the knob, the sensor reading will change!

Note: The potentiometer included in the kit has three marks on it that will help you figure out which breadboard rows the pins are plugged into.

Hardware Hookup

Ready to start hooking everything up? Check out the wiring 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.

Wiring Diagram for the Experiment

alt text

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Note: The full-sized breadboard power rails have a break down the middle. If you end up using the lower half of the power rail, you will need to jump between the upper end and lower end.

Running Your Script

alt text

Code to Note

pin2.read_analog()

In this program you are reading the voltage from the potentiometer, which is 0 to 3.3 volts on pin 2. The micro:bit reads that value as a 10-bit number, which is a value range from 0 to 1023 using the call pin2.read_analog(). We are saving that number to a variable called potVal.

pin0.write_analog()

As with the analog read, the analog write deals with a range of values, but instead of reading a pin as an input, the line pin0.write_analog() outputs an analog value to a pin. We see this as a brightness range with this LED, but it could be a tone from a buzzer, a motor speed, etc. We set our analog output to the variable we stored the potentiometer value in.

A “variable” is a placeholder for values that may change in your code. You can create a variable by simply typing a name and setting it equal to what you want. Python is a dynamically typed language. This means the type of variable is determined at runtime. So you do not need to worry about declaring your variable type.

What You Should See

You should twist the potentiometer. You will notice that the LED will get brighter or dimmer based on the position of the potentiometer. If you turn the potentiometer all the way one direction, it will be fully on, and the other end will be fully off.

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 or moving the potentiometer circuit somewhere else on your breadboard.

Not Working

Make sure you haven’t accidentally connected the wiper (center pin), the resistive element in the potentiometer, to a wrong pin!

LED Not Lighting Up

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

Experiment 3: Reading a Photoresistor

Introduction

In Experiment 2, you got to use a potentiometer, which varies resistance based on the twisting of a knob and, in turn, changes the voltage being read by the analog input pin. In this circuit you’ll be using a photoresistor, which changes resistance based on how much light the sensor receives. You will read the light value of the room and have an LED turn on if it is dark and turn off if it is bright. That’s right; you are going to build a night-light!

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1X micro:bit Breakout with Headers
  • 1x LED
  • 1x 100Ω Resistor
  • 7x Jumper Wires
  • 1x Photoresistor
  • 1x 10kΩ Resistor

Didn’t Get the SIK for micro:bit?

If you are conducting this experiment and didn’t get the Inventor’s Kit, we suggest using these parts:

micro:bit Board

DEV-14208
14.95
Breadboard - Self-Adhesive (White)

PRT-12002
4.95
31
Mini Photocell

SEN-09088
1.5
7
SparkFun micro:bit Breakout (with Headers)

BOB-13989
5.49
Jumper Wires - Connected 6" (M/M, 20 pack)

PRT-12795
1.95
2
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

COM-11507
0.95
2
LED - Basic Red 5mm

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

COM-11508
0.95

Introducing the Photoresistor

alt text

The photoresistor changes its resistance based on the light to which it is exposed. To use this with the micro:bit, you will need to build a voltage divider with a 10k ohm resistor, as shown in the wiring diagram for this experiment. The micro:bit cannot read a change in resistance, only a change in voltage. A voltage divider allows you to translate a change in resistance to a corresponding voltage value.

The voltage divider enables the use of resistance-based sensors like the photoresistor in a voltage-based system. As you explore different sensors, you will find more resistance-based sensors that only have two pins like the photoresistor. To use them with your micro:bit, you will need to build a voltage divider like the one in this experiment. To learn more about resistors in general, check out our tutorial on resistors and also our tutorial on voltage dividers.

Note: Make sure you are using the 10k ohm resistor in your voltage divider with the sensors in this kit. Otherwise, you will get odd and inconsistent results.

Hardware Hookup

Ready to start hooking everything up? Check out the wiring 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.

Wiring Diagram for the Experiment

alt text

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Note: The full-sized breadboard power rails have a break down the middle. If you end up using the lower half of the power rail, you will need to jump between the upper end and lower end.

Running Your Script

alt text

Code to Note

if and else

If the light value variable that is constantly being updated in the forever loop is less than the calibration value minus 50, it is dark and the LED should turn on. The (-50) portion of the if statement is a sensitivity value. The higher the value, the less sensitive the circuit will be; the lower the value, the more sensitive it will be to lighting conditions.

The if and else statements are a simple way to set the control flow of your forever loop. If the logical statement tied to the if statement is True, then it will execute the code indented under the colon. If that statement is False, it will skip to the next statement, which is else. In this case, if the statement is True (the room is dark), then the micro:bit will turn on the LED on pin 16; else (if the room is bright), it will turn the LED off using a write_digital() command covered earlier.

calibrationval is a calibration variable. Your micro:bit takes a single reading of the light sensor before entering the forever loop and uses this value to compare against the lightVal variable in the forever loop. This value doesn’t change in the forever loop, as it is set before entering the forver loop. To update this value, you can press the RESET button on the back of your micro:bit or power cycle the board.

What You Should See

When the micro:bit runs the program, it will take a single reading from the light sensor and use that as a calibration value of the “normal” state of the room. When you place your hand over the light sensor or turn the lights off, the LED will turn on. If you turn the lights back on or uncover the light sensor, the LED will turn off.

Troubleshooting

LED Remains Dark

You may have been leaning over the light sensor when the code started. Make sure the light sensor is reading the normal light in the room at startup. Try resetting the micro:bit.

Still Not Quite Working

Double-check your wiring of the signal pin; sometimes you miss a breadboard connection by a row.

Experiment 4: Driving an RGB LED

Introduction

You know what’s even more fun than a blinking LED? Changing colors with one LED! In this circuit you’ll learn how to use an RGB LED to create unique color combinations. Depending on how bright each diode is, nearly any color is possible!

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1X micro:bit Breakout with Headers
  • 1x Common Cathode RGB LED
  • 3x 100Ω Resistors
  • 5x Jumper Wires

Didn’t Get the SIK for micro:bit?

If you are conducting this experiment and didn’t get the Inventor’s Kit, we suggest using these parts:

micro:bit Board

DEV-14208
14.95
Breadboard - Self-Adhesive (White)

PRT-12002
4.95
31
LED - RGB Clear Common Cathode

COM-00105
1.95
1
SparkFun micro:bit Breakout (with Headers)

BOB-13989
5.49
Jumper Wires - Connected 6" (M/M, 20 pack)

PRT-12795
1.95
2
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

COM-11507
0.95
2

Introducing the Red/Green/Blue (RGB) LED

alt text

The Red/Green/Blue (RGB) LED is three LEDs in one. The RGB has four pins with each of the three shorter pins controlling an individual color: red, green or blue. The longer pin of the RGB is the common ground pin. You can create a custom-colored LED by turning different colors on and off to combine them. For example, if you turn on the red pin and green pin, the RGB will light up as yellow.

But which pin is which color? Pick up the RGB so that the longest pin (common ground) is aligned to the left as shown in the graphic below. The pins are Red, Ground, Green and Blue — starting from the far left.

Note: When wiring the RGB, each colored pin still needs a current-limiting resistor in line with the micro:bit’s I/O pin that you plan to use to control it, as with any standard LED.

Hardware Hookup

Ready to start hooking everything up? Check out the wiring 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.

Wiring Diagram for the Experiment

alt text

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Run Your Script

alt text

Code to Note

Using the random module

MicroPython comes with a random module to introduce a little unknown into your programs. There are a few ways you can use the random module beyond using it as a random number generator the way it is used in this experiment. To see the documentation, read the official docs on the random module.

In this experiment we are using random to generate a random number between 0 and 255

button_a.is_pressed() and button_b.is_pressed()

button_a and button_b represent the left and right buttons on the micro:bit respectively. There are three built-in functions that can be attached to button_a or button_b:

  • is_pressed()— Will return True if the button specified is pressed. If the specified button is not pressed, it will return False.
  • was_pressed()— Will return True or False depending on whether the specified button was pressed since start-up or since the last time this statement (method) was called.
  • get_pressed()— Will return the number of times the specified button has been pressed since the device started or since the last time the statement (method) was used. Once the method is used, it will reset to zero.

elif

The elif statement lets you check for multiple expressions that might be True. In this experiment we want to do different things whether button A pressed is True or button B pressed is True.

What You Should See

You should see your LED turn on red. If you press the A button on the micro:bit, the color will change to green, and if you press the B button, the color will change to blue.

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

Experiment 5: Reading an SPDT Switch

Introduction

In this experiment you will use your first digital input: a switch. The SPDT (Single-Pole, Double-Throw) switch is a simple way to select between two options, especially when paired with an “if” state. You will use that switch to select which of the two LEDs will blink.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1x micro:bit Breakout with Headers
  • 2x LEDs (1 Red, 1 Yellow)
  • 2x 100Ω Resistors
  • 8x Jumper Wires
  • 1x SPDT Switch

Didn’t Get the SIK for micro:bit?

If you are conducting this experiment and didn’t get the Inventor’s Kit, we suggest using these parts:

micro:bit Board

DEV-14208
14.95
Breadboard - Self-Adhesive (White)

PRT-12002
4.95
31
SparkFun micro:bit Breakout (with Headers)

BOB-13989
5.49
Jumper Wires - Connected 6" (M/M, 20 pack)

PRT-12795
1.95
2
SPDT Mini Power Switch

COM-00102
1.5
LED - Basic Red 5mm

COM-09590
0.35
Resistor 100 Ohm 1/4th Watt PTH - 20 pack

COM-13761
0.95

Suggested Reading

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

Introducing the Single-Pole, Double-Throw (SPDT) Switch

alt text

The Single-Pole, Double-Throw (SPDT) switch has a common pin in the middle and then two other pins that, depending on the location of the switch, are either connected to the common (center) pin or not. To read the switch in a similar way to a button, you connected the common pin to a digital General Purpose Input/Output (GPIO) pin on your micro:bit and the other pins to 3.3V and ground. It doesn’t matter which pin is which. When you move the switch, the common pin will either be HIGH (connected to 3.3V) or LOW (connected to ground).

Hardware Hookup

Ready to start hooking everything up? Check out the wiring 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.

Wiring Diagram for the Experiment

alt text

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Note: The full-sized breadboard power rails have a break down the middle. If you end up using the lower half of the power rail you will need to jump between the upper end and lower end.

Run Your Script

alt text

Code to Note

pin0.read_digital()

Just as the write_digital() statement turns a pin on (1) or off (0), the read_digital() statement determines the state of a pin, which is either HIGH (1) or LOW (0). By building a circuit that connects 3.3V or ground to a pin, we can detect if a switch is thrown or a button is pressed.

What You Should See

Depending on the state of the switch, a different LED will blink. If you move the switch to connect the signal pin to 3.3V (HIGH) then the LED connected to pin P15 will blink. If you flip the switch and ground the signal pin, then the LED on pin P16 will start blinking, and LED 1 will turn off.

Troubleshooting

Light Not Turning On

The wires for the switch are right next to each other. Make sure that signal is in the center with voltage and ground on the outside pins. If you connect ground and voltage, your board will short out and shut down.

Make sure your power LED is on. If it is off, pull the signal wire and see if that changes anything. If you short circuit your micro:bit board, it will turn itself off to protect the circuitry.

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 Button Press

Introduction

Up until now, we’ve focused mostly on outputs. Now we’re going to go to the other end of the spectrum and play around with inputs. In Experiment 2, we used an analog input to read the potentiometer. In this experiment, we’ll be reading one of the most common and simple inputs — a push button — by using a digital input. We will use it to cycle through different colors on the RGB.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1x micro:bit Breakout with Headers
  • 1x RGB LED
  • 3x 100Ω Resistors
  • 8x Jumper Wires
  • 1x Push Button
  • 1x 10kΩ Resistor

Didn’t Get the SIK for micro:bit?

If you are conducting this experiment and didn’t get the Inventor’s Kit, we suggest using these parts:

micro:bit Board

DEV-14208
14.95
Breadboard - Self-Adhesive (White)

PRT-12002
4.95
31
LED - RGB Clear Common Cathode

COM-00105
1.95
1
Momentary Pushbutton Switch - 12mm Square

COM-09190
0.5
4
SparkFun micro:bit Breakout (with Headers)

BOB-13989
5.49
Jumper Wires - Connected 6" (M/M, 20 pack)

PRT-12795
1.95
2
Resistor 330 Ohm 1/6 Watt PTH - 20 pack

COM-11507
0.95
2
Resistor 10K Ohm 1/6th Watt PTH - 20 pack

COM-11508
0.95

Suggested Reading

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

Introducing the Push Button

alt text

A momentary push button closes or completes the circuit only while it is being pressed. The button has four pins, which are broken out into two sets of two pins. When you press down on the button and get a nice “click,” the button bridges the two sets of pins and allows current to flow through the circuit.

How do you know which pins are paired up? The buttons included in this kit will only fit across the breadboard ditch in one direction. Once you get the button pressed firmly into the breadboard (across the ditch), the pins are horizontally paired. The pins toward the top of the breadboard are connected, and the pins toward the button of the breadboard are connected.

Note: Not all buttons share this pin format. Please refer to the data sheet of your specific button to determine which pins are paired up.

Hardware Hookup

Ready to start hooking everything up? Check out the wiring 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.

Wiring Diagram for the Experiment

alt text

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Note: The full-sized breadboard power rails have a break down the middle. If you end up using the lower half of the power rail, you will need to jump between the upper end and lower end.

Run Your Script

alt text

Code to Note

Pins on the micro:bit are active-low, which means external buttons should be connected to the pin and to ground to trigger an event with a button. This cannot be changed in MicroPython the way it can be changed in MakeCode. We have also found that MicroPython has a very hard time with interrupts and can’t seem to run more than one thread at a time. With MakeCode, it is possible to run multiple threads.

pass

Since interrupts are very difficult in MicroPython, we decided to use pass. pass is a way to handle external triggers from a while loop without impacting the while loop. In this case, the external trigger is whether or not the button has been pressed. It is a kind of cheat to using interrupts. We can continuously poll pin 16 on the micro:bit to see if the button has been pressed or not.

iter

The iter()_method creates an object that can be iterated or incremented one element at a time until a specified end. At the end of the iteration, an exception is raised: “StopIteration.”

try and except

try and except allows a program to catch an unexpected (or expected in this case) error and handle the error however the programmer wants to. The error in this case would be how the iter function lets the program know it is past the last iterable value. The exception that is thrown by the iter method is “StopIteration.” We are “trying” next iter until the exception is thrown. Once the exception is thrown, we exit from try and move onto except, which will start the iterator over again.

What You Should See

When you press the button, the RGB will turn on to a color. When you press it again, the color will change, and another press will change the color once again. Press it one more time, and it will turn off. Every time you press the button, it increments a variable, and then we check against it to set the color. If the variable goes over the value of 2, we reset it to 0, which is off.

Troubleshooting

Light Not Turning On

The push button 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. Remember, though, that these are building blocks to the Iron Man suit.

Experiment 7: Reading the Temperature Sensor

Introduction

A temperature sensor is exactly what it sounds like — a sensor used to measure ambient temperature. In this experiment you will read the raw 0–1023 value from the temperature sensor, calculate the actual temperature and then print it out over the LED array on your micro:bit.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1x micro:bit Breakout with Headers
  • 3x Jumper Wires
  • 1x TMP36 Temperature Sensor

Didn’t Get the SIK for micro:bit?

If you are conducting this experiment and didn’t get the Inventor’s Kit, we suggest using these parts:

micro:bit Board

DEV-14208
14.95
Breadboard - Self-Adhesive (White)

PRT-12002
4.95
31
Temperature Sensor - TMP36

SEN-10988
1.5
16
SparkFun micro:bit Breakout (with Headers)

BOB-13989
5.49
Jumper Wires - Connected 6" (M/M, 20 pack)

PRT-12795
1.95
2

Introducing the TMP36 Temperature Sensor

alt text

The TMP36 is a low-voltage precision centigrade temperature sensor. It provides a voltage output that is linearly proportional to the Celsius temperature. It also doesn’t require any external calibration to provide typical accuracies of ±1°C at +25°C and ±2°C over the −40°C to +125°C temperature range. The output voltage can easily convert to temperature using the scale factor of 10 mV/°C.

If you are looking at the flat face with text on it, the center pin is your signal pin, the left-hand pin is supply voltage (3.3V in this tutorial), and the right-hand pin connects to ground.

Pro Tip: The TMP36 looks a lot like a transistor. Put a dot of fingernail polish on the top of your TMP36 so it’s easy to find.

Hardware Hookup

Ready to start hooking everything up? Check out the wiring 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.

Wiring Diagram for the Experiment

alt text

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Run Your Script

alt text

Code to Note

str

We have already covered display.show() but we need to convert our number (temperature) to a string (type) before displaying it to the micro:bit 5x5 LED array. Type conversion in MicroPython is a snap with a simple str placed in front of the variable holding the temperature of type number.

CHALLENGE: How would you modify this code to get the temperature in degrees Fahrenheit?

What You Should See

When your micro:bit turns on, the temperature reading from the TMP36 temperature sensor will be displayed and scrolled across the LED array.

Troubleshooting

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.

Temperature Sensor is Really Hot!

You have wired it backward! Unplug your micro:bit immediately, let the sensor cool down and double check your wiring. If you catch it soon enough, your sensor may not have been damaged and may still work.

Experiment 8: Using a Servo Motor

Introduction

This experiment is your introduction to the servo motor, which is a smart motor that you can tell to rotate to a specific angular location. You will program it to rotate to a series of locations, then sweep across its full range of motion, and then repeat.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1x micro:bit Breakout with Headers
  • 1x Servo
  • 3x Jumper Wires

Didn’t Get the SIK for micro:bit?

If you are conducting this experiment and didn’t get the Inventor’s Kit, we suggest using these parts:

micro:bit Board

DEV-14208
14.95
Breadboard - Self-Adhesive (White)

PRT-12002
4.95
31
Servo - Generic (Sub-Micro Size)

ROB-09065
8.95
8
SparkFun micro:bit Breakout (with Headers)

BOB-13989
5.49
Jumper Wires - Connected 6" (M/M, 20 pack)

PRT-12795
1.95
2

Suggested Reading

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

Introducing the Servo Motor

alt text

Unlike the action of most motors that continuously rotate, a servo motor can rotate to and hold a specific angle until it is told to rotate to a different angle. You can control the angle of the servo by sending it a PWM (Pulse Width Modulation) pulse train; the PWM signal is mapped to a specific angle from 0 to 180 degrees.

Inside of the servo there is a gearbox connected to a motor that drives the shaft. There is also a potentiometer that gives feedback on the rotational position of the servo, which is then compared to the incoming PWM signal. The servo adjusts accordingly to match the two signals.

In this experiment, the servo is powered through 3.3 volts on the red wire and ground on the black wire; the white wire is connected to pin P0.

Hardware Hookup

Ready to start hooking everything up? Check out the wiring 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.

Wiring Diagram for the Experiment

alt text

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Run Your Script

alt text

Code to Note

One of the major drawbacks to using MicroPython with the micro:bit is that you can’t import third-party modules. Or at least, we haven’t had any luck flashing two Python files to the micro:bit. This code seems long because we had to paste the Servo Class code into our script. Ignoring the Servo Class code, let’s look at what’s happening inside the forever loop.

range

The range function generates a list of numbers. In this experiment we are generating a list from 0–90 that increases by 5.

Servo(pin0).write_angle()

The Servo Class is called in statement with pin 0 as its argument. The .write_angle() function is how the servo is moved — by the number specified in the parentheses mapped to degrees on the servo motor.

What You Should See

When powered up you should see the servo move to a single location (0 degrees) and then start to sweep to 180 degrees back and forth until you turn it off or tell it to go to a different angle.

CHALLENGE: How would you modify this code to get the servo to sweep to 180 degrees on button A pressed?

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 3.3 volts and ground (GND).

Experiment 9: Using a Buzzer

Introduction

In this experiment, we will 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 set of code blocks will create a simple sound machine.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1x micro:bit Breakout with Headers
  • 1x Piezo Buzzer
  • 2x Momentary Push Buttons
  • 7x Jumper Wires

Didn’t Get the SIK for micro:bit?

If you are conducting this experiment and didn’t get the Inventor’s Kit, we suggest using these parts:

micro:bit Board

DEV-14208
14.95
Breadboard - Self-Adhesive (White)

PRT-12002
4.95
31
Momentary Pushbutton Switch - 12mm Square

COM-09190
0.5
4
Mini Speaker - PC Mount 12mm 2.048kHz

COM-07950
1.95
5
SparkFun micro:bit Breakout (with Headers)

BOB-13989
5.49
Jumper Wires - Connected 6" (M/M, 20 pack)

PRT-12795
1.95
2

Introducing the Piezo Buzzer

alt text

The buzzer is a small component with a piece of metal in it that moves when you apply a voltage across it. This motion causes a small sound, or “click.” If you turn the voltage on and off fast enough, you get different beeps, squeals, chirps and buzzes. You will use PWM to control the speed of turning the piezo on and off — and, in turn, the audio frequency coming out of the buzzer. Adjusting the PWM enables you to get legitimate notes out of the buzzer.

alt text

If you flip the buzzer over and look at the bottom, you will see that one pin has a (+) next to it. That pin gets connected to a signal from the P0 pin. The other pin should be connected to ground.

Hardware Hookup

Ready to start hooking everything up? Check out the wiring 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.

Wiring Diagram for the Experiment

alt text

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Note: The full-sized breadboard power rails have a break down the middle. If you end up using the lower half of the power rail, you will need to jump between the upper end and lower end.

Run Your Script

alt text

Code to Note

music

MicroPython has an awesome music and sound module. We spent hours generating tones and writing songs in the REPL. As you learn to compose your own music on the micro:bit we highly recommend using the REPL to become familiar with all the sounds — plus the help() feature is nice when you want to see (hear) what you can do.

The music module has 21 melodies built in. To see a list, begin typing music.play(_... in the Mu editor, and the list should pop up.

To get an in-depth tutorial on the music module, click here.

music.play()

To play a tune you need to specify a note (A, C#, F), an octave (0–8) and a duration (how long the note will be played). For example, if the button on pin 15 is pressed, the note C in octave 4 will play for a duration of 8.

What You Should See

What you should see — well, nothing! What you should hear — each button has its own tune. Enjoy your sound machine and feel free to swap out the song and tunes of your choice. Add more buttons and play statements to make your custom piano!

Try it again but with a real speaker. At the press of a button you could play the funeral march, Happy Birthday or the Nyan Cat theme with much better audio!

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.

Also, double check to make sure the push button is wired correctly. If you miswired it, then the circuit will never be completed, whether you press the button or not.

Experiment 10: Using the Accelerometer

Introduction

In this experiment you will look at combining the use of the accelerometer on the micro:bit to measure the orientation of the micro:bit and using it to control the angle of a servo.

Ready to shake, rattle and roll?

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1x micro:bit Breakout with Headers
  • 1x Hobby Servo
  • 3x Jumper Wires

Didn’t Get the SIK for micro:bit?

If you are conducting this experiment and didn’t get the Inventor’s Kit, we suggest using these parts:

micro:bit Board

DEV-14208
14.95
Breadboard - Self-Adhesive (White)

PRT-12002
4.95
31
Servo - Generic (Sub-Micro Size)

ROB-09065
8.95
8
SparkFun micro:bit Breakout (with Headers)

BOB-13989
5.49
Jumper Wires - Connected 6" (M/M, 20 pack)

PRT-12795
1.95
2

Introducing the Accelerometer

The accelerometer is a component that you won’t find in the kit’s bag of parts. Why? Because it is on the micro:bit itself! On the back of the micro:bit you can see a number of small chips. One of them is the accelerometer.

Accel closeup

An accelerometer is a sensor that measures the gravitational forces pulling on it in all three dimensions of the chip’s X, Y and Z axes.

alt text

Not only can an accelerometer measure the raw forces pulling on the chip and the object that the chip is sitting on, but it can also detect steps, shakes and other motions that have a specific pattern. On top of that, you can use an accelerometer to simply detect the orientation of the device. Did you ever wonder how your phone knows when you turn it from portrait to landscape? It is all because of the accelerometer in your phone!

Hardware Hookup

Ready to start hooking everything up? Check out the wiring 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.

Wiring Diagram for the Experiment

alt text

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Run Your Script

alt text

Code to Note

Ignoring the servo class code again, we’ve got some new stuff!

accelerometer.get_x()

The accelerometer module comes with five built-in functions and recognizes 11 gestures. To see the full documentation, click here. The accelerometer.get_x() statement will return the acceleration measurement on the x-axis as a number between -32 and 32, depending on the direction.

dict

A dictionary is a set of key value pairs, where a key is mapped to one value. This is how we map acceleration in the x direction to a number that represents degrees for a servo.

zip

Zip takes two or more iterable items and combines the “ith” element from each item into a tuple. A tuple is an immutable and can be used as keys for a dictionary. Immutable just means the list of numbers can’t be changed once they are created.

What You Should See

At the beginning of the program the servo should move to 90 degrees and then react to the orientation of the micro:bit. If you hold the micro:bit flat, the servo will be at 90 degrees. Then if you tilt the servo to the left, it will move less than 90 degrees toward the value of 0. If you move it to the right, the servo will move toward 180.

Troubleshooting

This Seems Backward

You may be holding the micro:bit in a different orientation. Flip it around and try again!

Servo Isn’t Working

Double check your wiring! Remember, red to 3.3 volts, black to ground, and white to signal.

Resources and Going Further

MicroPython is a fun and exciting way to get started on your Python programming journey. Here are some more resources to help you along.

We produce a number of other kits and carrier boards that you can hook up to your micro:bit to help take your projects to the next level. Here is some further reading that may help you along in learning more about the world of electronics.

For more information on our micro:bit ecosystem, check out these tutorials:

New!

micro:climate Kit Experiment Guide

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

micro:bot Kit Experiment Guide

Get started with the moto:bit, a carrier board for the micro:bit that allows you to control motors, and create your own robot using this experiment guide for the micro:bot kit.
New!

micro:arcade Kit Experiment Guide

We love games! We love writing games, building games and yes, even building game consoles. So we want to introduce to you the micro:arcade kit for the micro:bit!

micro:bit Breakout Board Hookup Guide

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

Open Source!

All of our experiments and guides are licensed under the Creative Commons Attribution Share-Alike 4.0 Unported License. Feel free to remix and reuse our work. But please, share the love and give us attribution for our hard work!

To view a copy of the license, visit this link, or write to: Creative Commons, 171 Second Street, Suite 300, San Francisco, CA 94105, USA.


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

SparkFun 5V/1A LiPo Charger/Booster Hookup Guide

$
0
0

SparkFun 5V/1A LiPo Charger/Booster Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The SparkFun 5V/1A LiPo Charger/Booster is a no nonsense circuit for generating an amp from a lipo, at 5 volts. It’s low cost, has a simple booster circuit realizing the PAM2401 IC, and includes protection diodes so you can run multiple cells in series for extra kick. When a booster curcuit is in operation, it draws more current the lower the input voltage, so it’s possible to violate the C rating of the battery. This circuit doesn’t care, nor do I. If you’re looking to coddle your LiPos, try the excellent Battery Babysitter. But if you need charge delivered somewhere NOW, this is the product for you.

SparkFun LiPo Charger/Booster - 5V/1A

PRT-14411
$14.95

This guide shows how to use 1x charger/booster with 1x lipo to make a pack, and how to connect several packs together for greater current or voltage.

LiPo Charger/Booster

Required Materials

A Battery

You’ll need a battery for each charger/booster you have. While really any LiPo will work, smaller batteries are easy to overload and don’t supply much charge. It is recommended to use 1Ah batteries and larger, with the form factor most suited to our 1Ah cell.

Lithium Ion Battery - 1Ah

PRT-13813
$9.95
4
Lithium Ion Battery - 2Ah

PRT-13855
$12.95
Lithium Ion Battery - 6Ah

PRT-13856
$29.95
4
Lithium Ion Battery - 850mAh

PRT-13854
$9.95
1

Recommended batteries for the 5V/1A charger booster.

A Load

Any development board that runs from a USB supply is a great thing to power with the charger/booster. It provides a stable 5 volts, and can feed power hungry boards. Take a look in the microcontrollers product category, anything with a 5V input may need mobile power.

Tip: Many development boards regulate 5V USB power down to 3.3V for logic supply. This 3.3V rail often has a pin that can be used, giving you 5V and 3.3V to work with.

A Charger

Any old micro-B charger should do the trick, the circuit will consume up to 500mA so a computer’s USB port is not recommended. You can even use the power pins to charge from a generic bench supply.

Here’s some sources that can be used to connect to the on board micro-B USB connector:

Wall Adapter Power Supply - 5.1V DC 2.5A (USB Micro-B)

TOL-13831
$7.95
8
Wall Adapter Power Supply - 5V DC 2A (USB Micro-B)

TOL-12890
$5.95
14

With the addition of a micro-B cable, the following USB supplies will work:

USB Wall Charger - 5V, 1A (Black)

TOL-11456
$3.95
2
USB Wall Charger - 5V, 1A (White)

TOL-14042

Or if you’re in the market for a larger generic supply, try these:

Power Supply - 80W DC Switching Mode

TOL-09291
$259.95
1
Mean Well Switching Power Supply - 5VDC, 20A

TOL-14098
$25.95

Required Tools

You’ll have to attach your load somehow! Make sure you’ve got a few tools on hand.

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.

Battery Technologies

The basics behind the batteries used in portable electronic devices: LiPo, NiMH, coin cells, and alkaline.

Working with Wire

How to strip, crimp and work with wire.

Electric Power

An overview of electric power, the rate of energy transfer. We'll talk definition of power, watts, equations, and power ratings. 1.21 gigawatts of tutorial fun!

What is a Battery?

An overview of the inner workings of a battery and how it was invented.

Hardware Overview

Parts of the Board

The circuit is constructed by feeding an MCP73831 charge controller IC to the LiPo battery port, and to the input of a PAM2401 boost controller. Power always flows to the boost circuit, so an enable pin is provided to allow the booster to be shut down during charging if desired. Multiple connection types are provided for the battery, charge source, and switch to allow flexibility of application.

Board Layout 1

Charger input, battery port, enable pin, and output pins of the 5V/1A Charger/Booster.

The image below shows the location of the surface mount battery switch and external switch pins which are included to provide an additional option to control the output. Two LEDs are included to provide feedback on system status.

Board Layout 2

Switch options and status LEDs provided for the 5V/1A Charger/Booster.

Functions

ItemDescription
Output Pins
Get 5V, 1A out here! The 'OUT' pins are labeled with polarity.
Battery PortInsert a LiPo battery here through the JST connector or solder directly to the PTH pins underneath the connector. These ins are labeled with polarity.
Charger Input
Supply 5V, 500mA here to charge. You can use a micro-B USB cable or solder directly to the PTH pins. These 'IN" pins are labeled with polarity.
Battery SwitchThe on-board switch is a physical battery disconnect. When in the ON position, the battery is connected to the booster/charger. When flipped to the OFF position, the battery's positive lead is isolated from all electronics, and zero current will be drawn.
EXT SW Pins
These run parallel to on-board battery switch contacts. A higher current switch can be connected through these pins. If you're constantly drawing large currents or want a remote battery disconnect switch, connect it here.
EN Pin
The EN pin is enabled by default. This pin floats high and can be connected to ground to turn the output off. This is useful if your load circuit can't be put into low power mode for charging.
Charge LED
The charge LED indicates blue when the charger IC is attempting to charge the battery. It will turn off when the battery is fully charged. Note: If current is being drawn while the battery is being charged, the charger may think the battery is never quite full and continue sourcing current.
Boost LED
This LED indicates red when voltage is present on the output pins.

Charge Status LED

The on-board blue CHARGE LED can be used to get an indication of the charge status of your battery. Below is a table of other status indicators depending on the state of the charge IC.

Charge StateLED status
No BatteryFloating (should be OFF, but may flicker)
ShutdownFloating (should be OFF, but may flicker)
ChargingON
Charge CompleteOFF

Hardware Assembly

It’s easy to get started on your bench. Simply plug the LiPo into the battery JST connector, charge with a micro-B USB supply, and solder your load to the output pins. This section shows some tips and alternate ways to configure the ports.

Connecting to the Charge and Battery Ports

(top) Without modification, the charger and battery can be plugged straight in. (bottom) Connections can be made to one or both of the battery/charger ports by way of soldering wires into the provided holes.

Covered Battery Pins

There are a pair of through-holes peeking out from underneath the JST connector. Here’s how to safely remove the JST and apply battery leads directly. This also lowers the profile of the circuit board.

Make several small cuts to split the JST housing using a cutter. If you try and take the whole thing off at once, you risk pulling up the pads.

Cutting the JST Housing

Splitting the top off the JST connector.

With the top removed, the pins aren’t captured in the housing anymore and they can be pulled off with the soldering iron one by one.

Remove JST Pins

Unsoldering the pins

Alternatively, you can hot air the JST connector off, but it may melt in the process.

Caution: When working with a live battery where voltage is always present, don't cut both leads at the same time! This will short out the battery and damage the cutters. Work with each wire individually.

Cut and strip part of the end of the wire. Then solder the end to its respective through hole.

Soldering Ground Wire

Connecting the first wire

Solder Second Wire

Connecting the second wire

Charge Source Pins

As with the JST port, you may wish to charge your lipos from a source other than a micro-B, such as a 5v barrel or bench supply. The USB port is difficult to remove without damage to the board, so leave it in and just use the ‘+’ and ‘-’ pins provided by soldering some hookup wire to the respective pins. To connect to a barrel jack easily, you could use a female barrel jack adapter.

Heads up! Never supply two power sources for charging at the same time!

Connecting to the Charge Source Through Hole Pins

The charger booster with a barrel jack attached.

External Switch Pins

The onboard switch is rated for 600mA. Using the full current output available, this rating will be violated. It won’t have any immediate effect and is alright for peaky load with a nominal 500mA draw, but can lead to heat and corrosion depending on your application. If it’s found to be a problem, solder a higher current switch (like the SPST rocker switch) into the ‘EXT SW’ pins.

High Current External Switch

A high current capable panel switch is used to bypass the on-board switch.

Using a high current switch, the two switches are now in parallel so either one can be used to energize the circuit. If using an external switch, be sure to leave the on-board switch in the OFF position.

Or you can jumper the external switch pins together and use the enable pin to switch power. Further details will be explained in the next section with the enable pin.

Enable Pin

Another method to remove battery load is to use the enable pin on the PAM2401. It’s pulled up with a resistor on the board, so leaving it floating will default to an enabled state. To disable, it can be connected to the neighboring ground pin. The pin consumes very little current so a light duty switch (like the mountable slide switch) can be used.

Enable Pin with Switch

A small switch can be used to disable the booster.

In this configuration, the onboard switch may not be necessary and can be bypassed by putting a jumper in the external switch holes. The battery won’t be truly isolated though, and can drain over time. In the disable state, the current draw from the battery is about 6uA so it should take years to discharge.

Alternately, the pin can be driven by a logic source. The pin is 6V tolerant, with a logic-high threshold at ½ battery voltage, and a lower threshold of 0.2V.

Charging a Battery

When a voltage is supplied to the charger, the MCP73831 charge IC comes alive and starts making decisions on how to regulate. First, it regulates current to 500mA until a certain voltage is reached, then it regulates voltage until current goes (close) to zero. When this happens, the charger IC shuts off.

MCP73831 Charge Current Regulation

As shown in the MCP73831 datasheet, charge current drops as battery voltage rises

The charger IC is making decisions based on the battery voltage and output load, and can be tricked into an invalid mode. Follow these rules to get a reliable charge:

  • Turn on the battery switch before connecting the charger.
  • Consume no more than 20mA from the output terminals during charging.

Connecting a Load

Eager to get your 5V? Just connect up to the output terminals!

Output Pinst

Closeup of the output terminals are marked with polarity.

But there’s always more to know. An ideal booster circuit translates all input power to output power, so if the output is providing 5V @ 1A, or 5W, 5W must also be going into the booster. But if the input voltage is down to the battery lower limit of 3V, it will require 1.666A! With an efficiency of around 85%, it requires almost 2A on the input!

Here’s a graph of the charger booster’s measured performance:

alt text

Input current (right scale) and output voltage (left scale), shown as a function of output load. Notice that the output voltage sags slightly, but is pretty well regulated, and that input current is always larger than output current for a booster circuit.

alt text

Input and output power is shown (left scale), as well as overall efficiency (right scale).

Using Multiple Charger Boosters

5V may be fine for microcontrollers, addressable LEDs, and servos, but with motors sometimes some extra kick is required. With electric motors, speed is proportional to voltage, and torque is proportional to current. So if we want robot acceleration we’d want a high torque motor (low resistance), and if we want to go fast we’ll need to supply a large voltage. This section shows how to us multiple boosters and what that means for the voltage levels.

Increasing Voltage

The boosters have bypass diodes placed across their outputs. This means that if a negative voltage is presented to the output, it will conduct rather than apply negative voltage to the rails.

This allows the boosters to be placed in series to create voltages larger than 5, with a couple of caveats.

Running with one dead battery: For each booster/charger that is not generating voltage in the stack, 0.5V will be subtracted from the sum of running boosters/chargers.

The following two diagrams show how two chargers in series interact. With both chargers on and supplying 5V, the output runs at 10V, and 1 amp is driven through the booster circuit (shown as an ideal supply).

Two Charger/Boosters in Series

Two active booster circuits working together to produce 10V

When one booster stops producing voltage, it’s still in the current loop and must pass the 1A that the other booster can provide. The protection diodes allow the current to slip by, but at the cost of a diode drop. For these B340A Schottky diodes, that’s about 0.5V. The output voltage is now 4.5V.

Two Charger/Boosters in Series with One Booster On

Picture of boosters with one dead battery

Increasing Current

Life gets a little trickier if more current is needed. By supplying your own diodes and “diode OR-ing” the outputs, you can get increased current at the cost of a diode drop, or somewhere around 4.5V. You may get away with just connecting up the outputs but run the risk of back-feeding one output with the other.

Output Voltage: The voltage of the combined boosters will be at a diode drop below the output regulated voltage.

Two Charger/Boosters in Parallel with Diodes

Two supplies in parallel can source more current, but external diodes are required.

Resources and Going Further

Now that you’ve successfully charging LiPos and boosting them up to 5V, the world is your oyster. Go plug something in!

For more information, check out the resources below:

For inspiration, I’ve built a robot using two charger boosters to get 10 volts, for a bit of extra drive speed (and fun!).

Project Example

This robot is built on the with the

Or, see the Enginursday post on building a FLiR Pi Camera to see how two boosters can be used in parallel.


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


LilyPad ProtoSnap Plus Hookup Guide

$
0
0

LilyPad ProtoSnap Plus Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The LilyPad ProtoSnap Plus is a sewable electronics prototyping board that you can use to learn circuits and programming, then break apart to make an interactive fabric or wearable project. In this tutorial we’ll introduce the components that make up the ProtoSnap board, and set up the free Arduino software you’ll need to reprogram the LilyPad USB Plus at its center. Once you’ve done this, you’ll be able to write and upload your own programs to the board, making it do almost anything you want.

LilyPad ProtoSnap Plus

DEV-14346
$39.95

At the center of the ProtoSnap Plus is a LilyPad USB Plus microcontroller, pre-wired to LilyPad pieces including a LilyPad Light Sensor, LilyPad Buzzer, LilyPad Button Board, four pairs of colored LilyPad LEDs, and a LilyPad Slide Switch. Because these components are connected together on the ProtoSnap board, you can test out your project ideas before you sew. The ProtoSnap Plus also includes Expansion Ports; these let you use alligator cables to easily connect external sensors and components to the board. After testing out your coding ideas using the attached LilyPad pieces, you can break apart the board and sew them into your project.

Required Materials

To reprogram and recharge the board, you’ll need a micro-B USB cable. This is a common cable used by many devices, so you may already have one. Double check that it is not labeled ‘Power Only’ as these type of cables will not transmit the programming data needed by the LilyPad USB Plus board. If you don’t have one you can get one from SparkFun:

USB micro-B Cable - 6 Foot

CAB-10215
$4.95
9
USB Micro-B Cable - 6"

CAB-13244
$1.95
3

Suggested Reading

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

What is an Arduino?

What is this 'Arduino' thing anyway?

Installing Arduino IDE

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

Planning a Wearable Electronics Project

Tips and tricks for brainstorming and creating a wearables project.

Hardware Overview and Features

The LilyPad ProtoSnap Plus features twelve LilyPad components connected to a LilyPad microcontroller by conductive pathways called traces. For reference, each component on the ProtoSnap has a nearby label with its name and the number of the LilyPad USB Plus sew tab it is connected to.

LilyPad Protosnap Plus parts Highlighted

LilyPad USB Plus

The LilyPad USB Plus is an Arduino-compatible microcontroller similar to the LilyPad Arduino USB - ATmega32U4 Board but with some additional features and three additional sew tabs. It is currently only available on the LilyPad ProtoSnap Plus.

Additional SMD LEDs

Features:

  • USB port for connecting to a computer.
  • Two sets of power (+) and ground (-) sew tabs.
  • Built-in RGB LED attached to pins 12 (R), 13 (G), and 14 (B).
  • A row of six white LEDs attached to pins 15-20.
  • Charging circuit for single-cell (3.7V) Lithium-Polymer batteries.

Below is a table that lists the components connected to the LilyPad USB Plus sew tabs.

LilyPad ComponentConnected to LilyPad USB Plus Sew TabDescription
LilyPad Light Sensor (S)A2LilyPad USB Plus receives ambient light level input from light sensor.
LilyPad Buzzer (+)A3A buzzer that create tones controlled by LilyPad USB Plus.
LilyPad ButtonA4LilyPad USB Plus receives button press input.
2x LilyPad Y LEDs (+)A5A pair of yellow LEDs controlled by LilyPad USB Plus.
2x LilyPad R LEDs (+)~6A pair of red LEDs controlled by LilyPad USB Plus.
2x LilyPad G LEDs (+)~A7A pair of green LEDs controlled by LilyPad USB Plus.
2x LilyPad B LEDs (+)~A8A pair of blue LEDs controlled by LilyPad USB Plus.
LilyPad SwitchA9LilyPad USB Plus receives switch state (on/off) input to change modes.
Expansion Port A9A9Clippable pads to connect another LilyPad piece to. Shares connection with the LilyPad Switch.
Expansion Port (+)(+)Clippable pads connected to LilyPad USB Plus's power (+) sew tab.
Expansion Port ~10/SCL~10/SCLClippable pads connected to LilyPad USB Plus's sew tab 10. This can be used to connect to a I2C clock pin.
Expansion Port 11/SDA11/SDAClippable pads connected to LilyPad USB Plus's sew tab 11. This can be used to connect to a I2C data pin.
Expansion Port (-)(-)Clippable pads connected to LilyPad USB Plus's ground (-) sew tab.
All components (-)(-)All components share a common ground connection back to the LilyPad USB Plus.

Powering the LilyPad ProtoSnap Plus

The LilyPad ProtoSnap Plus can be powered in two ways:

  • If you have a USB power source available (a computer, 5V USB wall adapter, USB battery pack, etc.), you can run the board from a USB cable.

  • If you’d like your project to be more portable, you can easily attach a rechargable Lithium-polymer battery to the board. See Technical Notes section for more information on batteries and charging.

Exploring the Sample Circuit

The LilyPad ProtoSnap Plus ships with pre-loaded code that showcases all of the LilyPad pieces connected to it. To power up the ProtoSnap Plus, connect it to your computer using a micro-B USB cable or attach an E-Textiles Battery. Then slide the switch on the right side of the LilyPad USB Plus to the ON position.

Switch ON

The board has two modes to choose from: when the LilyPad Slide Switch (the other switch at the bottom right of the board) is turned OFF, all of the LEDs will turn on in sequence. When the LilyPad Slide Switch is turned ON, the white LEDs on the LilyPad USB Plus will form a bar graph showing the ambient light level - move your hand over the Light Sensor to see the level change. And if you press the LilyPad Button (at the bottom left of the board), you’ll be treated to a short song.

Continue to the Setting Up Arduino section for directions on installing the LilyPad USB Plus support for Arduino to enable you to upload your own custom code.

Using the Expansion Ports

The LilyPad ProtoSnap Plus features five expansion ports connected to sew tabs on the LilyPad USB Plus. These allow you to easily attach external components to the board, including LilyPad and non-LilyPad boards. The expansion ports can accommodate alligator clips, IC clips, and other temporary attachment cables for testing and experimentation. Below are a few ways to connect an alligator cable to the sew tabs.

Alligator Clip Parallel to a Sew Tab

Alligator clip attached parallel to the expansion port.

Alligator Clip Perpendicular to a Sew Tab

Alligator clip attached perpenticular to the expansion port.

Testing a LilyPad Temperature Sensor

A LilyPad temperature sensor attached to the LilyPad ProtoSnap Plus expansion ports for testing.

Using Expansion Port A9

You may have noticed that tab A9 is connected to both the LilyPad Slide Switch and an Expansion Port. You can only use A9 for one of these connections; either the switch as an input or the expansion port as an input/output.

If you’re using an external component or sensor on expansion port A9, move the slide switch to the OFF position to keep the switch from interfering with your input or output signal.

Turn Switch OFF for A9

Below is an image of the LilyPad temperature sensor attached to the LilyPad ProtoSnap Plus expansion ports for testing.

Testing Temperature Sensor

For more information about about expansion port A9 in the Technical Notes section.

Setting Up Arduino

Note: The LilyPad ProtoSnap Plus and the LilyPad USB Plus requires Arduino version 1.8 or higher. If this is your first time using Arduino, you can install it by following our Installing the Arduino IDE tutorial. Otherwise, please make sure to install (or update to) the latest version of Arduino and verify that you are connected to the internet to download the LilyPad USB Plus software add-ons.

Now that you’ve explored the board’s features, it’s time to upload some code! When you first install Arduino, it knows how to program a number of “standard” Arduino-compatible boards. Since the LilyPad USB Plus is a newer LilyPad microcontroller, you will need to manually add it to this list by following the steps below. You’ll only have to do this once to add the board to Arduino.

Note for Linux Users: If you are installing the LilyPad ProtoSnap Plus in Linux, this document has some specific notes:https://github.com/sparkfun/LilyPad_ProtoSnap_Plus/blob/master/Documentation/LinuxInstallation.md.

1. Add SparkFun Boards to Arduino’s Preferences

Start the Arduino IDE software (version 1.8 or higher) and open the Preferences window by choosing File>Preferences from the menu.

Now copy the below text and paste it into the “Additional Boards Manager URLs” text box:

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

Additional Board Manager

No room? If there is already a URL in the box, click the button to the right of the box. This will open a window allowing you to paste the URL onto a new line.

Additional Board Manager URLs

When you’re done, click the “OK” button.

2. Install SparkFun AVR Boards

Next, you’ll add the LilyPad USB Plus through Arduino’s Boards Manager Menu. Open the Boards Manager by choosing Tools>Board>Boards Manager… (The Boards Manager option is at the very top of the list of boards; you may need to scroll up to see it.)

Board Manager

When the Boards Manager window opens, it will present a long list of options. Type “sparkfun” (without quotes) into the “Filter your search” box at the top of the window. This will shrink the list down to SparkFun’s options.

You should see several entries. Look for the one labeled SparkFun AVR Boards by SparkFun Electronics.

alt text

Troubleshooting: If you don't see a SparkFun entry, it may mean that the URL you pasted into the Additional Boards Manager section of Arduino's preferences did not load correctly in Step #1, or you're not connected to the internet. Double check that the entire link was copied into the Additional Boards Manager URLs, and that you're connected to the internet. You might also try closing and restarting the Arduino software to refresh the preferences.

Click anywhere in the SparkFun AVR Boards box. A version number and an “Install” button will appear. Click the install button. This will download and install the extension. If you have already installed the SparkFun AVR Boards support, update to the latest version (LilyPad USB Plus is included in 1.1.7 and higher).

alt text

If everything worked, a blue “INSTALLED” note should appear next to the SparkFun AVR Boards title. You’re ready to start programming.

alt text

Uploading Code

Once you’ve installed the LilyPad USB Plus extensions to Arduino, you’re ready to start programming the board!

Note that you won’t have to install the extensions again, but you will need to perform the below three steps every time you want to program the board. These three steps are:

1. Connect the LilyPad ProtoSnap Plus to your computer using a USB cable
2. Select "LilyPad USB Plus" from Arduino's "Board" menu
3. Select "LilyPad USB Plus" from Arduino's "Port" menu

Let’s go over the three steps in detail:

1. Connect the LilyPad ProtoSnap Plus to Your Computer

Place the LilyPad ProtoSnap Plus on a clean, non-metal work surface. Connect the LilyPad ProtoSnap Plus to a USB port on your computer using a micro-B USB cable. The cable can only be inserted one way, and should snap in securely.

USB Cable

Tip: Both the micro-B USB cable and the connector on the LilyPad have a subtle "D" shape to them. Match this shape to plug it in properly.

Connecto to Computer's USB Port

Slide the switch on the LilyPad USB Plus to the ON position. You will not be able to upload code to the board if it is set to the OFF position.

Turn LilyPad ProtoSnap Plus ON

2. Select LilyPad USB Plus from the Board Menu

If the Arduino board support was installed correctly, “LilyPad USB Plus” option will be available in the Tools>Board list under the SparkFun AVR Boards group. Open the menu and select LilyPad USB Plus. Depending on how many boards are already in the list, you may need to scroll down a bit to get to it. A dot (Windows) or check mark (Mac) will show next to the board in the menu when it is selected, and it will show next to Board in the Tools menu.

IMPORTANT: You'll see some LilyPad entries higher in the Arduino menu, but the LilyPad USB Plus is not one of them. You'll need to scroll down to the SparkFun section at the bottom of the list to find it. We're working on getting the LilyPad USB Plus added to the LilyPad group in the future.

Select Board Definition

Troubleshooting: If you don't see "LilyPad USB Plus" in the board list, go back to Setting Up Arduino and double check that you performed all the steps. You might try restarting Arduino as well.

3. Select LilyPad USB Plus from the Port Menu

Arduino needs to know which port your LilyPad USB Plus is attached to so it can program it. Whenever you plug a USB device into your computer, your computer will assign it a port number. This used to be difficult to determine, but this board has a handy feature that identifies itself. Go to the Tools>Port menu, and select the port that has “LilyPad USB Plus” next to it.

On Windows ports are listed as COM##; on a Mac or Linux machine they will be “/dev/cu.usbmodem####”. Your screen may look different than the image below, depending on what operating system you are using, but all should show LilyPad USB Plus next to the port address.

COM Port

Troubleshooting: If you don't see a port with "LilyPad USB Plus" next to it, ensure that the board is powered up (switch in the ON position), and that the USB cable is securely connected to both the board and your computer. Some micro-USB cables are only meant for charging and don't pass data - they'll power the board, but it won't show up in the port menu. If needed, try a different cable.

Uploading Code

To review, once you’ve:

  1. Connected the LilyPad ProtoSnap Plus to your computer using a USB cable.
  2. Selected the board type (“LilyPad USB PlusNOTLilyPad Arduino USB”).
  3. Selected the COM port.

You are ready to upload code! Let’s upload some code to try it out:

Load the “Blink” example from the menu File>Examples>01.Basics>Blink, and click the “Upload” button (the large round button with the right arrow in it). This is a very simple example program; it just blinks a LED on and off once per second.

Blink Example

Arduino will compile the code, then send it to the LilyPad USB Plus via the USB cable. While the code is uploading, the built-in LED will blink to signal the code is transferring. When the code finally runs, the RGB LED at the center of the board will slowly blink green. Success!

If this all works, congratulations! You’re all set up and ready to prototype with the LilyPad ProtoSnap Plus.

Troubleshooting: Error Messages on Upload?

If you are using a Mac and get an error message like the following:

Board LilyPad USB Plus (platform avr, package SparkFun) is unknown

It is possible that old Arduino versions left over after updates are interfering with the LilyPad USB Plus support installation. If you want to clear out this old information, follow these steps:

  1. Open Arduino’s “Preferences” window.
  2. At the bottom of the window will be a link to your preferences file. Click on it and it will open a finder window.
  3. In the finder window, look for an “Arduino15” folder and delete it.
  4. Now open a finder window and open your personal folder (the one with your login name and a house icon next to it). Look for an “Arduino” folder (possibly in “Documents”). If the “Arduino” folder contains a “Hardware” folder, delete it. Your Arduino installation is now clean. Restart Arduino and repeat the LilyPad installation instructions from the previous page.

Stitching Into a Project

Once you are done exploring the parts of the ProtoSnap Plus and prototyping your code, you can snap along the perforations on the board to remove the individual LilyPad pieces and build them into a project.

Snap LilyPad Components

Carefully snap the pieces of the ProtoSnap apart to prepare for sewing. Use a set of pliers or diagonal cutters if you are having trouble snapping the pieces apart. Discard the non-sewable pieces and scraps. The conductive pathways on the ProtoSnap can then be recreated with conductive thread by stitching the components in your project.

Sew LilyPad Components

These tutorials will give you some tips and tricks for project construction and insulation:

Insulation Techniques for e-Textiles

Learn a few different ways to protect your conductive thread and LilyPad components in your next wearables project.

LilyPad Basics: E-Sewing

Learn how to use conductive thread with LilyPad components.

Technical Notes

If you’ve already programmed Arduino for a while, read on for some additional notes about the LilyPad ProtoSnap Plus. It’s very similar to other Arduinos, but has some special features and limitations you’ll want to know about.

Pin Numbering

Below is a list of the LilyPad USB Plus I/O pins and each function.

Legend:

  • n = digital pin
  • ~n = PWM-capable pin
  • An = analog-capable pin
  • (n) = internal pin (not connected to sew tab)
  • [n] = internal pin (available on an exposed via)
FunctionDigitalAnalog
RX_LED(0)
RX_LED/SS(1)
Light Sensor2A2
Buzzer3A3
Button4A4
Yellow LED5A5
Red LED~6
Green LED~7A7
Blue LED~8A8
Switch / Expansion Port9A9
Expansion Port / SCL~10
Expansion Port / SDA11
RGB LED - Red(~12)
RGB LED - Green(~13)
RGB LED - Blue(~14)
Bar Graph LED 0(15)
Bar Graph LED 1(16)
Bar Graph LED 2(17)
Bar Graph LED 3(18)
Bar Graph LED 4(19)
Bar Graph LED 5(20)
SCLK[21]
MOSI[22]
MISO[23]

Expansion Port A9 Notes

If you look closely at the ProtoSnap board, you’ll notice that sew tab A9 is shared between the switch and an expansion port. Because of this, remember: if you’re using the A9 expansion port, ensure that the switch is turned OFF to keep the input or output signal from shorting to ground.

Switch OFF

A hard short between power and ground could damage the board. But if you look even closer at the ProtoSnap, you’ll see a tiny 1K surface-mount resistor in the ground trace connected to the switch. (On the back of the board you’ll see a zig-zag resistor symbol in that spot.) This resistor prevents hard shorts from power to ground if the switch is ON and you connect a voltage source to the expansion port (or output a HIGH signal from A9).

Using a Battery and Battery Charging

SparkFun sells a number of LiPo batteries compatible with this board. If you are new to the LilyPad system, we recommend the E-Textiles Battery. If you’re supplying your own battery, use a single-cell (3.7V) LiPo battery with a JST connector.

Batteries with larger capacities (measured as amp-hours or Ah) will run the board longer before needing recharging. How long will depend on how many LEDs your program turns on, etc. If you’re just running a few LEDs, you can expect the board to run about 5 hours for every 100mAh of battery capacity.

To recharge an attached battery, plug the board into a USB power source. While the battery is charging, the “CHG” LED will illuminate. When the battery is fully charged the LED will turn off. The default charge current is set to 100mA, so a 100mAh battery will recharge in one hour, a 1000mAh battery in 10 hours, etc. Since the board is set to charge at a rate of 100mA, we do not recommend connecting a lower capacity LiPo battery (i.e. 40mAh LiPo battery) to charge.

Connecting a Battery

It is safe to leave a LiPo battery attached to the board permanently, even with USB power applied. The battery will not be overcharged.

The battery connector can be tight; to remove a battery never pull on the wires. Use a pair of needle nose pliers or cutters to gently hold pull the plug out of the connector.

Remove LiPo Battery

Resources and Going Further

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

For more information about the LilyPad ProtoSnap Plus, check out the resources below:

Check out these tutorials for more information on using the LilyPad boards on the ProtoSnap Plus:

LilyPad Light Sensor Hookup Guide

How to hook up the LilyPad Light Sensor as well as some project ideas and example code.

Powering LilyPad LED Projects

Learn how to calculate how many LEDs your LilyPad project can power and how long it will last.

LilyPad Buzzer Hookup Guide

How to hook up the LilyPad Buzzer and make sound with code.

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

Lumenati Hookup Guide

$
0
0

Lumenati Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The Lumenati line of LED boards is designed to give your projects an edge in their lighting capacity. Based on the APA102C addressable LED, these LEDs employ a 2-wire communication protocol consisting of a clock line and a data line. While this requires one more wire than standard WS2812B addressable LEDs, the advantage is that the communication with the LEDs becomes somewhat timing independent, allowing you to run these directly off of a Raspberry Pi or other single-board computer that doesn’t normally allow for a long, precicely-timed data stream without the use of additional hardware.

SparkFun Lumenati 8-stick

COM-14359
$6.95
SparkFun Lumenati 8-pack

COM-14357
$6.95
SparkFun Lumenati 4-pack

COM-14353
$3.95
SparkFun Lumenati 3x3

COM-14360
$5.95
SparkFun Lumenati 90R

COM-14358
$3.95
SparkFun Lumenati 90L

COM-14452
$3.95

Required Materials

To get started, you’re going to need a control system. Either a Raspberry Pi or Arduino will suffice for our examples, but really anything that has GPIO can be made to work.

SparkFun RedBoard - Programmed with Arduino

DEV-13975
$19.95
11
Arduino Pro Mini 328 - 5V/16MHz

DEV-11113
$9.95
114
Arduino Pro Mini 328 - 3.3V/8MHz

DEV-11114
$9.95
39
Raspberry Pi 3

DEV-13825
$39.95
80
SparkFun SAMD21 Mini Breakout

DEV-13664
$19.95
12
Raspberry Pi Zero W

DEV-14277
$10.00
10

The APA102C addressable LEDs on the Lumenati boards operate natively with 5V logic, so it will save you trouble to choose a controller that can give you 0-5V, but it can be made to work with 3.3V logic with the use of a level translator.

SparkFun Logic Level Converter - Bi-Directional

BOB-12009
$2.95
78
SparkFun Level Translator Breakout - PCA9306

BOB-11955
$6.95
1

You will also need a power 5V power supply to run your controller and new lights. Each APA102C can draw as much as 60mA when red, green and blue are all full-on, so you’ll want to have something a little beefy. We’ve chosen a wall adapter capable of 2.5A, which should be plenty for our demonstration. But if you’ve got a bigger project in mind, check out the Mean Well 5V/20A supply.

Wall Adapter Power Supply - 5.1V DC 2.5A (USB Micro-B)

TOL-13831
$7.95
8
Wall Adapter Power Supply - 5V DC 2A (Barrel Jack)

TOL-12889
$5.95
14
Mean Well Switching Power Supply - 5VDC, 20A

TOL-14098
$25.95

Tools

Lastly, you are going to need a few tools. A soldering iron, some solder, wire and a wire stripper should do. Maybe also some tweezers if you’re not comfy with having your fingers close to the tip of a soldering iron.

Solder Lead Free - 100-gram Spool

TOL-09325
$7.95
6
Hook-Up Wire - Assortment (Stranded, 22 AWG)

PRT-11375
$16.95
15
Wire Strippers - 30AWG (Hakko)

TOL-12630
$9.95
3
Tweezers - Straight (ESD Safe)

TOL-10603
$3.95
2
Soldering Iron - 30W (EU, 230VAC)

TOL-11650
$9.95
1

Suggested Reading

We’re tried to make this hookup guide as simple as possible, but you may be lacking some basic information that could help your understanding as we go forward. For more info, check out these tutorials…

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!

Logic Levels

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

How to Solder - Castellated Mounting Holes

Tutorial showing how to solder castellated holes (or castellations). This might come in handy if you need to solder a module or PCB to another PCB. These castellations are becoming popular with integrated WiFi and Bluetooth modules.

Raspberry Pi SPI and I2C Tutorial

How to use the serial buses on your Raspberry Pi.

Hardware Overview

There are six different variations of Lumenati boards.

Lumenati Boards

The various shapes of Lumenati boards.

Each of the Lumenati boards are shown below:

4-pack

The 4-pack.

8-pack

The 8-pack.

3x3

The 3x3.

8-stick

The 8-stick

90L

The 90L.

90R

The 90R.

Daisy-chaining Lumentai Boards

Any of the boards can be used stand-alone or daisy-chained. However, the 8-stick, 90L and 90R were designed with easy daisy-chaining specifically in mind.

Castelated edges

Castelated edge connectors. Just butt them up against each other and sodler together.

There are also solder jumpers on the CO and DO (clock out and data out) of these 3 boards. Those are there so that you can interrupt those signals in case you make a closed-loop design where you don’t want the clock and data from your last LED to interfere with the clock and data to your first. +5V and ground traces are left to be contiguous in such cases to maximize current throughput. The solder jumpers on CO and DO come closed with a small trace bridging the solder pads. If you wish to open them, just take a small hobby knife (or similar implement of destruction) and carefully cut out that trace.

Note: It is critical that you cut the traces in the jumpers before you power up your LEDs if you’ve putt together a continuous loop of Lumenati boards. Otherwise, it is likely that you’ll burn out a couple of LEDs. We know this from experience.

cutting traces

Make sure you cut the traces on CO and DO before powering up a continuous-loop design.

The APA102C addressable LEDs that are used on the Lumenati boards operate on +5V power input, as well as 0-5V logic levels for clock and data. The data interface is basically an SPI-like, with the exception that there is no data available coming back from the LEDs (no MISO line). Trace widths for +5V and ground have been maximized for better current through-put for long led chains.

Additionally, LEDs on each board are labeled with numbers indicating their position in the sequence to help you design code more easily.

numbers labeled

Check those numbers!!

As mentioned earlier, each APA102C is capable of drawing close to 60mA when it’s fully on. Care should be taken to keep that in mind when designing long LED chains. Figure out what your worst-case current draw could be, and plan accordingly!

Multiple Board Assembly

This section will cover the steps necessary to connect multiple Lumenati boards together.

Plan the Layout

For our demonstration, we’ll use four Lumenati 90L boards combined with a Lumenati 8-pack for a chain of 20 LEDs. Then we’ll drive them with a Raspberry Pi 3 in our first example and a SAMD21 Breakout in the second.

To begin, gather the boards you want to use.

5x piece Lumenati

You may want to sand or file down some of the edges left from the panelization of the PCBs to aid in fitment at this point, but we’ll leave that up to your judgement.

Soldering!

The four 90L boards will form a contiguous ring of LEDs. It would be difficult to get the clock and data signals off of the last 90L board (not impossible, but difficult), so we’re going to put the 8-pack at the beginning of the chain. First, we’ll solder up the four 90L’s. To do this, you’ll need a flat surface, preferably one that doesn’t burn too much. A piece of cardboard works really great for this! Tin one of the corner connections (either power or ground) on one of the boards with some solder, like so:

tinned corner

Then, butt the board you’ve just tinned up against the next board you want in the sequence, and reheat that solder you just placed so that it bridges between the two boards and forms enough of a mechanical connection to hold them together. Take care to make sure that both boards are as flat as you can get them to maximize both electrical and mechanical connections.

connected

After you secure the first connection, solder the other three on both the top and bottom. This will make the boards as strong as possible. However, be aware that these can still break apart if put under too much stress. Mounting the boards to a solid backing is recommended, but they should still hold together fairly well if you’re making something like a Christmas ornament or the like. For our demonstration, we’re going to leave all the boards unmounted.

rest of connections soldered

Next, solder the leads between the 8-pack and the four 90L boards. Cut four lengths of wire about 1 inch in length. We suggest color coding your wires for power (red), ground (black), clock and data (your call on those). Strip both ends of each wire about 1/16 inch to 1/8 inch, and tin them.

wires

Tin all the solder pads of the 8-pack and solder your four leads to 5V (either of the two 5V pads), ground (either of the ground pads), CO and DO (Clock Out and Data Out). You can lay them out to the side if you wish, but we’re going to sit them straight up so as to make positioning of the PCB easier.

wires soldered

Place the 8-pack board in the middle of the circle of 90L boards you’ve already made. Figure out how you’d like the board oriented, and pick one of the four interfaces between the four 90L boards to which you’ll solder your four leads.

Don’t forget: Before you solder the leads, cut the jumpers marked “CO” and “DO” that are physically closest to your selected solder points. That will ensure that your logic at the end of the circle doesn’t interfere with the logic at the start.

Once you’ve done that, solder down your leads - 5V to 5V, GND to GND, CO on the 8-pack to CI on the circle, and DO on the 8-pack to DI on the circle.

cutting jumpers

Do yourself a favor and cut these now. You can burn a couple of LEDs if you forget.

An alternate method of wiring to the 90L circle would be to solder up three of the four board interfaces leaving the fourth as open holes into which you can insert your 5V, GND, CO and DO lines. You will have to determine what your positioning is going to be before doing so.

Now, you need to get power and signal to the thing you’ve constructed. To do so, just solder four more leads to the remaining 5V and GND pads on the 8-pack board, as well as CI and DI on the 8-pack. Braid the wires for some extra geek-cred. Now, it’s ready to hook up to your control system!

ready for action

Ready for action!

Example Using a Raspberry Pi 3

For this example, we’ll be using a Raspberry Pi 3, a PCA9306 Level Translator Breakout, a 5V power supply and the Lumenati boards that we put together in the last section. The hookup will look like this:

circuit diagram

Click the image for a closer look.

You’ll notice from the diagram that the Lumenati boards are powered directly from an external 5V power supply and not from the header on the Raspberry Pi. While it is possible to drive the circuit as constructed with the supplied demo code from the Pi header, the 5V that’s available there is fused. Since it is difficult to predict how much current the Pi itself is going to draw at any given moment, driving the LEDs through the Pi as well can become problematic with increased LED count and increased brightness, risking a brown-out condition with increased current consumption. Circumvent that condition entirely by tapping 5V and ground on the power supply before it reaches the Pi.

The connections of interest are in the following table.

RasPi Pin #DescriptionGoes to PCA9306 Pin
13.3V (for low-side level shifting reference)VREF1
45V (for high-side level shifting reference)VREF2
6GND (ground for level shifting reference)GND
19DataSCL1
23ClockSDA1

Astute readers will notice that we’ve connected a clock signal to what looks like a data channel and a data signal to what looks like a clock channel on the PCA9306, if the labels are to be believed. But here’s a little secret about those channels: they’re virtually identical, electrically speaking. While the labels may be incongruent, it made the wiring just slightly more uniform.

The connections from the PCA9306 Breakout to the Lumenati boards are thus:

PCA9306 PinDescriptionLumenati Pin
SDA2ClockCI
SCL2DataDI
GNDGND (ground for level shifting reference)GND

We’ve put together some really simple python code for you to get started with. The first is a really simple library to set up an array with the LED parameters and write them to the Lumenati boards.

language:python
#Set up the SPI port on the Pi
import spidev
spi = spidev.SpiDev()
spi.open(0,0)

#Create LED array by sending this function num_LEDs
def set_LED_quantity(num_LEDs):
    global NUM_LEDs
    NUM_LEDs = num_LEDs
    global LED_array
    LED_array = [[0,0,0,0]] * NUM_LEDs

#Puts LED(num) parameters into LED_array
#Red, Green and Blue (r,g,b) values must be between
#0-255. Brightness must be between 0 and 31.
def set_LED(num, r, g, b, brightness):
    if (brightness > 31) | (brightness < 0):
        brightness = 15
    if (r > 255) | (r < 0):
        r = 100
    if (g > 255) | (g < 0):
        g = 100
    if (b > 255) | (b < 0):
        b = 100

    LED_array[num] = [r, g, b, brightness | 0xE0]

#These 4 bytes have to be written at the start and
#end of each data frame when writing to the LEDs
def _start_end_frame():
    for x in range (4):
            spi.xfer2([0x00])

#Write data to the LEDs
def WriteLEDs():
    _start_end_frame()
    for LED in LED_array:
        r, g, b, brightness = LED
        spi.xfer2([brightness])
        spi.xfer2([b])
        spi.xfer2([g])
        spi.xfer2([r])

    _start_end_frame()

The second demonstrates the use of those functions and makes some pretty lights.

language:python
#This is demonstration code for the Lumenati line of APA102c boards,
#specifically using (4) 90L boards surrounding one 8-pack board.

import time

from SFE_Lumenati import set_LED_quantity, WriteLEDs, set_LED

#Set up array, 20 LEDs
set_LED_quantity(20)

#Delay duration
wait = 0.15

#Global brightness
brightness = 15 #range is 0-31

try:
    while True:

        for y in range (5):

            #center, white
            set_LED(0,25,25,25,brightness)

            #inner ring, red
            for x in range (7):
                set_LED(x+1,25,0,0,brightness)

            #outer ring, white
            for x in range (12):
                set_LED(x+8,25,25,25,brightness)

            #Write to the LEDs and wait
            WriteLEDs()
            time.sleep(wait)

            #center, red
            set_LED(0,25,0,0,brightness)

            #inner ring, white
            for x in range (7):
                set_LED(x+1,25,25,25,brightness)

            #outer ring, red
            for x in range (12):
                set_LED(x+8,25,0,0,brightness)

            #Write to the LEDs and wait
            WriteLEDs()
            time.sleep(wait)

        for y in range (5):

            #center, yellow
            set_LED(0,25,25,0,brightness)

            #inner ring, blue
            for x in range (7):
                set_LED(x+1,0,0,25,brightness)

            #outer ring, yellow
            for x in range (12):
                set_LED(x+8,25,25,0,brightness)

            #Write to the LEDs and wait
            WriteLEDs()
            time.sleep(wait)

            #center, blue
            set_LED(0,0,0,25,brightness)

            #inner ring, yellow
            for x in range (7):
                set_LED(x+1,25,25,0,brightness)

            #outer ring, blue
            for x in range (12):
                set_LED(x+8,0,0,25,brightness)

            #Write to the LEDs and wait
            WriteLEDs()
            time.sleep(wait)

except KeyboardInterrupt:
    pass

Click here to get the code. Just drop the two files from SparkFun_Lumenati_Code/Firmware/RasPi into the same folder, and run Lumenati_Demo.py. If the stars align (and you’ve done everything right), the result should look as below.

alt text

The brightness is turned down to show the colors better.

Example Using a SAMD21 Mini Breakout

Our second example uses a SparkFun SAMD21 Breakout board, which is Arduino-based, a PCA9306 Level Translator Breakout, a 5V power supply and the Lumenati boards that we put together in the assembly section. The hookup will look like this:

circuit diagram -SAMD21

Click the image for a closer look.

The circuit is almost identical to the Raspberry Pi example, except that there’s a SAMD21 Breakout where the Pi was. The specific connections to the SAMD21 are as follows:

SAMD21 Pin labelDescriptionGoes to PCA9306 Pin
VIN3.3V (for low-side level shifting reference)VREF1
VCC5V (for high-side level shifting reference)VREF2
GNDGND (ground for level shifting reference)GND
11DataSCL1
13ClockSDA1

Again, the channels on the PCA9306 with regard to SCL and SDA are not electrically critical; either channel can do either function, clock or data. This swap just made our wiring slightly cleaner. Everything else in this circuit is identical to the RasPi example.

For the code, this time we’re going to use the FastLED library. If you haven’t already done so, now is a good time to install that library. Haven’t installed a library in Arduino before? Click here for more info.

Our example code is as follows:

language:c
#include "FastLED.h"

//Number of LEDs
#define NUM_LEDS 20

//Define our clock and data lines
#define DATA_PIN 11
#define CLOCK_PIN 13

//Create the LED array
CRGB leds[NUM_LEDS];

void setup() {

      //Tell FastLED what we're using. Note "BGR" where you might normally find "RGB".
      //This is just to rearrange the order to make all the colors work right.
      FastLED.addLeds<APA102, DATA_PIN, CLOCK_PIN, BGR>(leds, NUM_LEDS);

      //Set global brightness
      FastLED.setBrightness(50);
}

void loop() {

  uint8_t x;
  uint16_t wait = 100;

  //Check out all these wacky colors! Have a look at teh FastLED documentation for more.
  //Turn on each LED in succession
  leds[0] = CRGB::Blue;
  FastLED.show();
  delay(wait);

  leds[1] = CRGB::Green;
  FastLED.show();
  delay(wait);

  leds[2] = CRGB::Purple;
  FastLED.show();
  delay(wait);

  leds[3] = CRGB::AliceBlue;
  FastLED.show();
  delay(wait);

  leds[4] = CRGB::DarkGoldenrod;
  FastLED.show();
  delay(wait);

  leds[5] = CRGB::DarkGreen;
  FastLED.show();
  delay(wait);

  leds[6] = CRGB::DeepSkyBlue;
  FastLED.show();
  delay(wait);

  leds[7] = CRGB::GreenYellow;
  FastLED.show();
  delay(wait);

  leds[8] = CRGB::LawnGreen;
  FastLED.show();
  delay(wait);

  leds[9] = CRGB::Maroon;
  FastLED.show();
  delay(wait);

  leds[10] = CRGB::FairyLight;
  FastLED.show();
  delay(wait);

  leds[11] = CRGB::Tomato;
  FastLED.show();
  delay(wait);

  leds[12] = CRGB::Turquoise;
  FastLED.show();
  delay(wait);

  leds[13] = CRGB::SpringGreen;
  FastLED.show();
  delay(wait);

  leds[14] = CRGB::Salmon;
  FastLED.show();
  delay(wait);

  leds[15] = CRGB::Sienna;
  FastLED.show();
  delay(wait);

  leds[16] = CRGB::SeaGreen;
  FastLED.show();
  delay(wait);

  leds[17] = CRGB::Teal;
  FastLED.show();
  delay(wait);

  leds[18] = CRGB::OrangeRed;
  FastLED.show();
  delay(wait);

  leds[19] = CRGB::RosyBrown;
  FastLED.show();
  delay(wait);

  //Shut them off
  for (x = 0; x < NUM_LEDS; x++)
  {
    leds[x] = CRGB::Black;
  }

  FastLED.show();
  delay(wait);

}

This example will look completely different from the RasPi example, partly because we wanted to show off some of the colors available by some crazy names in the library. The FastLED library offers a LOT of versatility, probably far more than you’re ever going to need. Check their documentation for a full listing of functions.

If you’ve already done the RasPi example, you’ve already got the Arduino code in your possession, as well. It can be found in the folder SparkFun_Lumenati_Code\Firmware\SAMD21. If you haven’t got it yet, click here to get it. Load Lumenati_demo.ino onto your SAMD21, and watch the show!

If you’ve done everything right, your LEDs should be doing this:

alt text

The brightness is turned down to show the colors better.

Resources and Going Further

Here are links to more resources for the Lumenati boards.

SparkFun Lumenati 4-pack (Circular Disc)

SparkFun Lumenati 8-pack (Circular Disc)

SparkFun Lumenati 8-stick

SparkFun Lumenati 90R

SparkFun Lumenati 90L

SparkFun Lumenati 3x3


Need some inspiration for your next LED project? Check out these other great SparkFun tutorials.

Das Blinken Top Hat

A top hat decked out with LED strips makes for a heck of a wedding gift.

Addressable RGB LED Music and Sound Visualizer

Use an Arduino and the SparkFun Sound Detector to create visualizations on Addressable RGB LED strips.

LED Cloud-Connected Cloud

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

LED Crystal Goddess Crown

Follow this tutorial to make your own Crystal Goddess Crown with LEDs!

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

Beginner's Guide to KiCad

$
0
0

Beginner's Guide to KiCad a learn.sparkfun.com tutorial

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

Introduction

If you’re like me and you’ve decided to take the plunge from EAGLE PCB to KiCad it can be really jarring. EAGLE had many quirks and rough edges that I’m sure I cursed when I first learned it back in 2005. Since then EAGLE has become a second language to me and I’ve forgotten all the hard bits. So as you migrate to KiCad remember to take breaks and breathe (and say ‘Key-CAD’ in your head). You’ll be dreaming in KiCad in no time!

KiCad Logo

This tutorial will walk you through a KiCad example project from schematic capture to PCB layout. We’ll also touch on library linking, editing, and creation. We’ll also export our PCB to gerbers so the board can be fabricated.

While this tutorial is aimed at beginners I am going to use terms such as ‘schematic components’ and ‘polygon pours’. If something doesn’t make sense that’s ok, just take a moment to do a quick search. If you really get stuck please use the comments section on the right. We always want to improve our tutorials to make them easier.

KiCad Project Window

Download and Install KiCad

Let’s get started! Head over to KiCad’s download page and download the latest version of the software for your specific platform:

Download KiCad for Your Operating System/Distribution

Run KiCad

Once installed, run KiCad. A main navigation window will display where you will be able to open all the periphery programs like schematic capture and PCB layout.

KiCad main Project Window

Click the image for a closer look

The KiCad project window looks quite empty and sad. Let's open an example!

Setting Up a Project

The ZOPT2201 UV sensor designed originally in SparkX is a great I2C UV Index sensor and will serve as our starting example for this tutorial. Download the ZOPT220x UV Sensor Breakout designs for KiCad and unzip the four files into a local directory:

ZOPT220x UV Sensor Breakout KiCad Board Files

Once the four files are located in a local directory (try looking in your downloads folder for …\ZOPT220x_UV_Sensor_Breakout-Tutorial), click File -> Open Project and open the ZOPT220x UV Sensor Breakout.pro file.

Main Project Window

Click the image for a closer look

What are all these files?

  • *.pro - Main project file to keep track of the file structure.
  • *.cmp - Defines which footprints go with which schematic components.
  • *.kicad_pcb - The PCB layout.
  • *.sch - The schematic.

These four files are all you need to share a KiCad design with a fellow collaborator. You may also need to share a footprint file, which will be explained more later on in this tutorial.

You may have had your first critical-judgment-eye-squint. Why is there a file to define which footprints go with which schematic components? This is fundamental to KiCad and is very different from how EAGLE works. It’s not a bad thing, just different.

Setting Up Schematic Component Libraries

Double click on the schematic file with Kicad’s Eeschema schematic editor. You’ll probably get an error:

Library Error

Ignore this for now. Click ‘Close’.

Component Question Marks

The schematic will load with lots of components with question marks (i.e.??). KiCad is missing the link to the devices within this schematic. Let’s get them linked!

Linking Component Libraries w/ Eeschema

From within EeSchema, click on Preferences -> Component Libraries. This will open a new window. In the image below you can see that the project file contains information about where it should look for “Component library files”. Each project has its own connections to different file structures. We need to tell this project where to find the symbols for this schematic.

Linking KiCad Library

We will need the SparkFun_SchematicComponents.lib file. Download and store it in a local directory:

Download "SparkFun_SchematicComponents.lib"

From the KiCad window, click the top ‘Add’ button. We’ll show you how to create your own schematic symbols in a bit.

Add SparkFun Schematic Component Libray

Navigate to the directory where you stored the SparkFun_SchematicComponents.lib file and click ‘Open’. This file contains all the schematic components.

Once you've added the SparkFun schematic components library file, you should see it added to the list.

Component Library Files with SparkFun Schematic Component Library

The astute will note the slightly different directory structure in the window:

C:\Users\Nathan\...

and

C:\Users\nathan.seidle\...

That's the difference between my home PC and my work PC. To avoid future errors when opening this schematic, let's remove the entry from the active library files. Highlight the C:\Users\Nathan... entry from the list and click on the ‘Remove’ button.

Click on ‘OK’ to close out the Component Libraries manager. Now close and re-open the schematic to refresh.

Schematic without ??

Congrats! No more ?? boxes. For more information about using schematic component libraries across multiple computers, check the next subsection about the “user defined search path.” Otherwise, let's start editing the schematic!

User Defined Search Path: Using Component Libraries on Multiple Computers

The schematic component libraries are assigned using KiCad's Component Library Manager. If you're like me and have schematic libraries shared across multiple computers, adding a “User defined search path” is helpful:

User Defined Search Path

In the image , I have “..&bsol;..\SparkFun-KiCad-Libraries” defined. This is the local relative path to a Dropbox folder. These component library paths are specific to this project and *.pro file. When I open this project on my laptop, it will first look for the files in the “C:\Users\nathan.seidle...” location. It will fail and then search the relative path of “ ..\SparkFun-KiCad-Libraries” and find the files. It allows me to share libs between computers and between GitHub repos without having to reassign the libraries every time I open the project on a different computer.

For now, you should continue with the tutorial. In the future, you may want to revisit this if you use KiCad across multiple computers.

Editing a Schematic

If I get you to do nothing else, I will get you to learn the keyboard shortcuts! Yes, you can click on the equivalent buttons. However, the speed and efficiency of KiCad really shines when muscle memory kicks in so start memorizing. Here are the keyboard shortcuts in KiCad’s Eeschema that we will be using frequently in this tutorial:

  • a - To add component.
  • c - Copy a component when the cursor is over another component.
  • w - To wire components.
  • v - Edit component value.
  • Esc - Escape mode or whatever command in progress and return to normal pointer mode.
  • ctrl+z - Undo. Use liberally to undo any mistakes.
  • ctrl+s - To save. Make sure to save often!

This breakout board needs a larger 4.7uF decoupling cap (because I say so). Let’s add it!

Adding Component to Schematic

Press ‘a’ to add a device to the schematic then click on the schematic:

Choose Component

There are hundreds of components (668 items according to the title bar). Feel free to dig around but to quickly find what we need type ‘cap’ into the field Filter:. Select the device labeled as C_Small from the device library. Then hit enter or click ‘OK’.

select C_Small

Place it on the schematic next to the 0.1uF cap.

Place in Schematic

After you place the capacitor, you'll notice you're still in placement mode. Hit the ‘Esc’ button on your keyboard to return to normal pointer mode. I find myself hitting escape twice a lot just to be sure I'm back in default state.

Copying Component

Once in default state put your mouse pointer on top of the 3.3V marker on the 0.1uF cap. Press ‘c’ to copy that device and place it above the new capacitor.

Copy C_Small

Do the same for the ground marker. Press ‘ctrl+s’ to save your work.

Wiring Components

Now let's wire them together. You guessed it, press ‘w’ but here's the catch: have your mouse pointer over one of the bubbles before you press ‘w’.

Wiring Schematic Components

Move your mouse to the other bubble and left click on the mouse to complete the wiring for GND. Remember if you mess up, press ‘Esc’ once or twice to return to default. Then move your mouse pointer to the bubble you want to connect and press ‘w’ and begin wiring 3.3V. The shortcut ‘w’ stands for wire.

Did something go wrong? Use ‘ctrl+z’ liberally to undo any mistakes.

Connected Capacitor

Power and ground are now connected to our capacitor.

Changing a Component Value

Let's change the value from C_Small to 4.7uF. Hover the mouse pointer over C_Small and press ‘v’ (for value change). Change C_Small in the Text field by typing 4.7uF. Then hit enter or click ‘OK’.

Change Capacitor Value

Congrats! You've just wired up your first schematic component. Press ctrl+s to save your work.

Annotate Schematic Components

But what about the C? designator?! Don't worry about it! One of the many benefits of KiCad is the ability to auto-annotate a schematic.

Click on Annotate Schematic Button


Click on the Annotate schematic components button.

Annotate Schematic Button

Use the default settings and simply click on Annotate button to confirm. KiCad will ask you if you're sure, simply press return or click ‘OK’ again.

Updated Schematic Value and Designator

Capacitor with correct value and designator! We are all set. Time to edit the PCB.

Editing a PCB Layout

Before we start editing the PCB, here are the keyboard shortcuts in KiCad’s Pcbnew that we will be using frequently in this tutorial:

  • + - Press to switch next layer.
  • - - Press to switch to previous layer.
  • m - Move item.
  • b - Update ground polygon pours.
  • Delete - Remove a trace or component.
  • x - Route new track.
  • v - Add through via.
  • n - Next grid size. Use with caution. There will be tears if you use a grid outside of 50mils or 25 mils.
  • Page Up - Return to the top copper layer.
  • Esc - Escape mode or whatever command in progress and return to normal pointer mode.
  • ctrl+z - Undo. Use liberally to undo any mistakes.
  • ctrl+s - To save. Make sure to save often!

Generate Netlist

We’ve got our schematic, now let’s get the new 4.7uF cap placed on the board. From the schematic, click on the ‘Generate netlist’ button.

Generate Netlist Button

You'll see the following window:

Netlist Window

KiCad is powerful. And with this power, comes an overwhelming number of options. Lucky for us, we are just scrapping the surface so we don't need to fiddle with any of these options. Simply press enter or click ‘Generate’ to confirm this screen. KiCad will ask you where you want to save the netlist as a *.net file with the default location being the project folder. Again, press enter or click ‘Save’ to confirm.

Configuring Layer Colors

Return to the main project window and double click the *.kicad_pcb file.

KiCad_PCB File

Welcome to PCB editing. Of all the differences between EAGLE and KiCad it was the look within PCB layout that threw me off the most. Under the View menu you will find three other views: Default, OpenGL, and Cairo. I prefer OpenGL. Lets switch Canvas to OpenGL for now.

Your mouse wheel does what you expect: Zoom In/Out and Pan by Clicking.

I don't like the layer colors! Ya, me either. To change the layer colors, on the right side menu use your mouse wheel to click on the green square next to B.Cu (bottom copper layer). I prefer the following layer colors:

  • Red 2 (Default) for F.Cu (Top Copper)
  • Blue 4 for B.Cu (Bottom Copper)
  • White for F.SilkS (Front Silk Screen)
  • Yellow 3 for B.SilkS (Bottom Silk Screen)
  • Gray 3 for Edge.Cuts (a.k.a board outline or dimensional layer in EAGLE)
  • Gray 2 (Default) for F.CrtYd (Denotes the total board space required on the top layer for the component)

Layer Colors

Pressing ‘+’ and ‘-’ will switch between top and bottom copper layers. This is useful when you need to view a certain layer.

PCB Layers Colored

It's all cosmetic but these layer colors make it easier for me to see what's going on.

Be sure to poke around the Render tab (next to the Layer tab), namely the Values and References check boxes.

Value and References

I find the Values and References extremely distracting when turned on so I leave them OFF. Many designers live and die by these values, so use as needed.

Adding a Footprint

Aren't we here to add a 4.7uF cap to the board? Where is it? It's nowhere, sorry.

What's going on? We failed to assign a footprint to the capacitor we added in the schematic. Remember, KiCad does not link schematic components to footprints the same way EAGLE does. We have to specifically connect a footprint to each schematic component that was added.

Navigate to back to schematic and click on the ‘Run CvPcb’ button to associate components and footprints:

Run CvPcb

If this is the first time you’ve run CvPcb you’ll get this warning:

CvPcb Warning

Simply click through it.

CVPcb Manager

Depending on how many libraries you have installed, this may take up to 30 seconds. We will make this better later in the tutorial but for now, be patient.

In the left column is all the footprint libraries that KiCad ships with. In the middle is the list of components in your schematic. On the right is any footprint that may work with the highlighted component in the middle. Your job is to double click on the footprint on the right that goes with the component in the middle.

To make life easier click on the ‘View selected footprint’ button.

View Selected Footprint

Now you can preview the footprint as you click down the list in the right.

Preview Footprint Window

In Windows, I press and hold the Windows button and press the left arrow and release. This will lock the CvPcb window on one side. Then select and lock the Footprint Preview Window to the right. This allows us to flip through footprints in the left window while seeing the preview on the right.

Highlight C2 in the middle column. Then double click the Capacitors_SMD:C_0603 in the right column. C2 should now be assigned a footprint.

Assign Schematic with Footprint

Re-Generate Netlist

Close the CvPcb window and click ‘Save and Exit’. We need to re-export the Netlist. Remember how to do that? Click the ‘Generate netlist’ button again, press enter twice. Open to the PCB editor either from the schematic or from the project window.

Reopen PCB Editor

Hey! It's still missing! We changed things, so we need to import the netlist! Remember how? Click on the ‘Read netlist’ button and you should see this window:

Read Netlist Window

Click ‘Read Current Netlist’ and ‘YES’ to confirm. You can also hit enter twice. You should see the new capacitor near the board.

Added Footprint Capacitor Near PCB

This is a decoupling cap so let's put it next to the 0.1uF cap that is already there. Start by hovering over the new cap and press ’m' for move.

Capacitor Footprint Moved

Left click to place the capacitor. Now press ’m' over the 0.1uF cap in the way by moving it to the left.

Capacitor 2 Footprint Moved

Press ‘b’ to update the GND polygon pours.

Updated Polygon Pours

We've got some traces to fix but this isn't too bad. Hover over the bits of traces that you want to remove and press ‘Delete’. Let's delete the trace and via that is under the capacitor's +3v3 terminal. If your pointer is over multiple items (as shown in the image below with the cursor over both the trace and capacitor), KiCad will pop up a menu to clarify your selection. This is basically asking you to pick which one you want to operate on.

Clarify Selection

If you ever run into a problem press ‘Esc’ to return to default pointer mode. If you ever delete something wrong press ‘ctrl+z’.

Deleted Trace Via

Once you've removed most of the offending traces, you can begin routing by pressing ‘x’.

Single click on the pad that has the gray air-wire and drag it to the pad that it needs to connect to. Single click again to lock the wire in place. Press ‘b’ to update the polygons.

Connect 3V3

In the image below, KiCad is trying to route this trace in an odd way. If we place the trace here it will create an acute angle which is generally bad (read up on “acid traps”). We want the trace to be a T intersection. We need to change the grid.

Odd Trace Routing

Well that’s annoying!

Press ‘n’ to go to the next grid size. I needed to hit ‘n’ only once to go to the 0.25mil grid to get this nice intersection, you may need to get to a finer grid. You can also find this in the menu options under “Grid: 0.0635mm (2.5mils).”

T Intersection

Nice T intersection!

In the image below, I am routing the GND air wires. This is not really needed because the polygon pour connects the two pads but it does illustrate how good the ‘magnetic’ routing assistance is in KiCad. It's very quick and easy to go from pad to pad.

Route Ground Air Wires

We have two air-wires left. To get these we'll need to place vias down to the bottom layer. Start by pressing ‘x’ and clicking on the start of the capacitor's air wire for GND again.

Routing Ground Air Wire Again

Bring the trace out.

GND Trace

When you've reached open ground press ‘v’ to create a via. Single click to place the via and KiCad will automatically start routing on the bottom layer. Press ‘Esc’ to stop laying down traces; the polygon pour will take it from here. Pressing ‘Page Up’ will take you back to the top layer.

GND Via

One air wire left!

To get this last air wire, you can try clicking on the GND pad of the 0.1uF cap but annoyingly KiCad won't start routing?! Why?! It's actually a good thing: the SDA trace is too close (overlapping actually) to the GND pad on the 0.1uF cap. By not letting you start routing KiCad is saying that trying to put a trace here would violate the DRC rules. What to do? Rip up the SCL and SDA lines to make some room.

Delete SCL and SDA Trace

Aha! Much better. Press ‘x’, click on the capacitor's GND terminal, bring the trace out, and press ‘v’ to drop a via in this area. Hit escape to stop routing (let the polygon take care of it). Finally, press ‘Page Up’ to return to the top layer view.

Capacitor 2 Via

Use the ‘Delete’ and ‘x’ buttons to re-route the SDA and SCL lines to finish up this board. Then press ‘b’ to update the polygons. The board should look similar to the image below.

Routed PCB

Routed with no air wires!

Congrats! We have finished routing the footprints. Now let's run the DRC to see if we're legal.

How to Remove a Component's Footprint from a PCB Layout

Before we continue let's go over the process for modifying or removing a component from a PCB layout. For example, let's say that you wanted to remove an extra capacitor or resistor from a design. You would do all the regular steps:

  1. Delete device from the schematic.
  2. Export the netlist by clicking the generate netlist button.
  3. Import the netlist into PCB Layout by clicking on the read netlist button.

The difference is a few import settings:

Delete Footprint from Netlist

During the netlist import the default settings are to ‘Keep’ exchange footprint and to ‘Keep’ extra footprints.

Here, we need to change two things:

  • Exchange Footprint -> Change: This will allow footprints to change
  • Extra Footprints -> Delete: This will remove any extra footprints that remain

You may also want to ‘Delete’ unconnected tracks to clean up any left over tracks from the component you removed.

Running Design Rule Check

Click on the ladybug with the green check mark on it to open the Design Rule Check (DRC) window.

DRC

Let's take a moment to talk trace width, trace spacing, and vias. In general, SparkFun designs boards with:

  • 10mil trace width
  • 10mil trace spacing
  • 20mil vias

We go smaller than this on many designs but if you're designing your first PCB, do not design it with 4mil traces and 8mil vias. You shouldn’t need to go that small on your first board.

Why design in 10mil trace/space when a fab house allows 8mil or smaller for the same price?

Making PCBs is tricky and for each increment of tolerance you remove you increase the chances that the PCB (proto or not) will be fabricated with an error. And those errors can be hard to identify. We design with 10mil trace/space in order to insure and reduce the probability that we’ll see PCBs with errors on the production floor. There’s nothing worse than troubleshooting a faulty product and asking yourself: “I’ve tried every rework and soldering trick in the book, is it the PCB that’s bad?”

That stated, we are seeing many PCB fab houses charge low prices for 7mil trace/space and 12mil vias. If you’ve got a complex board with tight layout challenges, it’s better use the smaller trace/space and vias. Save yourself the layout time and rely on the PCB fab house to correctly fabricate your board.

We generally use the KiCad defaults of:

  • Clearance: By Netclass
  • Min Track Width: 0.2mm = 0.0079mil
  • Min Via Size: 0.4mm = 0.0157mil

Press enter again to run the DRC with the default settings.

ErrType(): Via near track

Aw shucks! What's wrong with my board? The vias marked with red arrows are too close to the traces near by. The error message will show up in the window as an error indicating: “Via near track.” Fix them by ripping up (press ‘Delete’) any traces near the vias and re-route them (press ‘x’).

DRC Errors

After adjusting the traces causing the issues, re-run the DRC. These three flags should disappear.

Fixed DRC Markers

DRC markers have been cleared

Congrats! You've fixed those “Via near track” issues.

ErrType(): Pad near pad

But wait, we are not done yet! There are still two DRC error arrows left with the error indicating: “Pad near pad”. KiCad is trying to tell us the pads on this solder jumper are too close together. SparkFun has used this footprint for years and is comfortable with the design so let's change the Netclass clearance constraint.

More DRC Errors

Open the DRC rules from the Design Rules menu.

Design Rules

Here is where you can create specific rules for specific traces and classes of traces. The problem that we are running into is the DefaultClearance is 0.079mil (0.2mm). If we decrease this to 7mil (0.01778mm), click ‘OK’, and re-run the DRC…

Clearance Defaults

DRC errors resolved! Now reducing the DRC clearances in order to get your board to pass DRC is not an ideal solution. We want the pads on the solder jumper to be close enough to be easily jumpered with solder so increasing the distance between the pads on the footprint would be counterproductive. In general, you should set your DRC rules and stick to them.

Cleared DRC Markers

Watch Your Airwires!

One last note about DRC: Leaving airwires on your PCB is a sure fire way to generate coasters (bad, unusable PCBs).

List Unconnected

From the DRC window there is a ‘List Unconnected’ button. This will show you the location of any unconnected traces (I had to rip up the SDA trace on the bottom right side of the PCB to show this error). It's very important that you check for airwires before ordering your PCBs. As you progress through your layout, I recommend focusing on the ‘Unconnected’ count at the bottom of the screen (circled in pink). If you think you are done routing a board but still show a few unconnected wires that you can't find, the DRC window will help you locate them.

Press ‘ctrl+s’ to save your work.

Well done. You've made it through design rule checking! Now it's time to order boards.

Exporting Gerbers

We added a component to the schematic, we modified the PCB layout, and we checked for errors. Now we are confident and ready to have our boards made! Time to export the gerber files.

Generate Drill and Gerber Files

Gerber files are the ‘artwork’ or the layers that the PCB fabrication house will use to construct the board. We’ve got a great tutorial on the different layers of a PCB so be sure to read up if all this is new to you.

Click on the ‘Plot’ button next to the printer icon in the top bar to open the ‘Plot’ window.

Plotter Button and Plot Window

In general, there are 8x layers you need to have a PCB fabricated:

  • Top Copper (F.Cu)+ Soldermask (F.Mask) + Silkscreen (F.SilkS)
  • Bottom Copper (B.Cu) + Soldermask (B.Mask) + Silkscreen (B.SilkS)
  • Board outline (Edge.Cuts)
  • Drill file

In the Plot window with the Plot format set for Gerber, be sure these Layers are checked:

  • ☑ F.Cu
  • ☑ B.Cu
  • ☑ B.SilkS
  • ☑ F.SilkS
  • ☑ B.Mask
  • ☑ F.Mask
  • ☑ Edge.Cuts

Additionally, click on ‘Generate Drill File’ button. You can use the defaults here as well. More on the PTH vs. NPTH check box in a minute. For now just click ‘Drill File’ or press enter to generate the drill file.

Drill File Generation

Click on ‘Close’ in the ‘Drill Files Generation’ window.

Click ‘Plot’ to generate the gerber files for the layers and then click ‘Close’.

Time to Review Your Gerbers

This is the last chance to catch any errors before paying real money. Reviewing the gerber layers often shows you potential errors or problems before you send them off to fab.

GerbView

Return to the main KiCad project window and open up GerbView by clicking on the button.

Once KiCad’s GerbView is open, click on File -> Load Gerber File. Select all the files shown and click Open.

Load Gerber File

Next, click File -> Load EXCELLON Drill File. Load your drill files by selecting the all the drill files shown and click ‘Open’. They should be in the same directory.

Drill Files

The layout looks very different but this is a good thing. You've been staring at your design for hours and it's hard for your brain to see issues. I generally do not change the layer colors unless I have to. I want the gerber review to be jarring and different from my layout practices so that I'm more likely to catch issues.

From this view, turn off all the layers but the Top Copper (layer 5). Additionally from the Render menu, turn off the Grid and DCodes. This will make the review less cluttered.

Top Copper Layer

Now step through the different layers by toggling them on and off. You're looking for irregularities and things that look out of place. Here are some things I look for:

  • Do any traces have weird routing that could be improved?
  • Do the vias line up with the top copper where they should?
  • Does the top solder mask make sense with the SMD IC’s footprint?
  • Are the via’s covered in soldermask (also called ‘tented vias’) or are they exposed?
  • Does the top silkscreen look good? Make sense? Everything aligned the way I want it? Are pin 1 indicators clear?

Turn On  and Off Layers

Now turn everything off and repeat for the bottom layers.

Did you catch it? There are a handful of things wrong with this example.

  1. The bottom silkscreen is missing the GND indicator.
  2. The top GND silkscreen indicator is in italics.
  3. There are two drill files for some reason.

Leaving a silkscreen indicator off won't break your board but it's small defects like this that the gerber review is meant to catch.

Missing GND on Bottom

Whoops! Bottom silkscreen for GND is missing!

Homework:

Take a moment and return to the PCB layout window to edit the make these corrections.

  • Add the a silkscreen to the bottom layer for GND. To do this, select the bottom silk layer (B.SilkS) in Pcbnew. Click on Place -> Text, type “GND” in the Text: field, and click ‘OK’. You can also copy text on the bottom silkscreen layer by right clicking it, selecting Duplicate, and placing text next to the GND pad. Make sure to change text to GND by right clicking the text, selecting Properties, changing the text, and clicking ‘OK’.
  • Change the top GND indicator so it’s not italics. To do this, edit the text properties and change the Style: to Normal.
  • Plot new gerber files.
  • Review your work in GerbView to verify the fixes.

Now, we need to deal with the two drill files.

PTH vs NPTH

When generating the drill file for this design two files where generated:

  • *.drl - The standard EXCELLON drill file you need to send to PCB fab house.
  • *-NPTH.drl - The non-plated through hole drill file.

Non-plated through holes are holes on your PCB that do not have copper covering the vertical walls of the hole. This is sometimes required for advanced designs where thorough electrical isolation is needed. However, it is rare. While plated through holes (PTH) are common and cheap, NPTH requires an extra step in the PCB fabrication process and will often cost extra.

We don’t need NPTH for this design, so what happened? The ‘STAND-OFF’ footprint (i.e. used for the drill holes top of the board for mounting holes) was imported from the SparkFun Eagle library and KiCad seems to think it is a non-plated hole for some reason.

To correct this go back to the PCB layout, click on the Plotter, click ‘Generate Drill File’ and select the box that says ‘Merge PTH and NPTH holes into one file’. In a later section, we’ll go over how to edit the ‘STAND-OFF’ footprint to use a regular PTH hole.

Solder Paste Stencils

Are you doing SMD reflow? Need to order a stencil to apply the solder paste to your board? Turn on F.Paste in the Plot window to generate the top paste layer.

This *.gtp file is sent to a stencil fabricator to create the stainless steel or mylar solder paste stencil. If you’re unfamiliar with stenciling solder paste we have a fabulous tutorial.

We use OSHStencils for our proto stencils. The top paste layer is not needed to fabricate a PCB.

Order Your Board!

If you’re happy with your layout, let’s order some PCBs! Every fab house understand and works with gerber files, so navigate to the directory on your computer where your KiCad project resides.

Gerber Files to ZIP

Select and zip the following 8x files:

  • *.drl - Drill file
  • *.gbl - Gerber Bottom Layer
  • *.gbs - Gerber Bottom Soldermask
  • *.gbo - Gerber Bottom Silkscreen (Overlay)
  • *.Edge.Cuts.gm1 - Board Outline (Gerber Mechanical 1)
  • *.gtl - Gerber Top Layer
  • *.gts - Gerber Top Soldermask
  • *.gto - Gerber Top Silkscreen (Overlay)

You could zip all the files in the directory and send them off to your fab house but I don't recommend it. There are a tremendous number of PCB layout software packages generating all sorts of different file names and formats. It's often difficult to tell if *.cmp is a gerber file or something else. Does the customer care about the *.gtp file or is that just extra? It's better to give the fab house only what you want fabricated.

The final step? Order your boards! The gerbers are the universal way to communicate with a PCB vendor. There are hundreds if not thousands of PCB vendors out there. Shop around!

In addition to your gerbers, you'll need to specify via email or the PCB vendor's website various elements of the PCB:

  • What thickness PCB? 1.6mm is standard but 0.8mm is just as rigid and may help with 50 ohm trace impedance matching.
  • What color soldermask? Green is default but red looks awesome.
  • What color silkscreen? White is most common but other colors are available.
  • How many layers? This example is a 2x layer board meaning there is just a top copper and bottom copper. However, some designs need to have 4x, 10x, and even 16x layers to route the board. Additional layers increase the cost significantly.

The Soldermask Looks Big

If you had a look at the soldermask on this PCB and wondered why it looked odd, you're not alone. Let's compare the PCB's soldermask for KiCad (as shown in green) and Eagle (as shown in pink). You should notice two things:

  1. In the KiCad design, I have a pad on the main sensor that looks like it's slightly mis-placed. Pad 1 doesn't line up with the other pads. Weird. It's a problem that needs to be fixed, but the error won't kill the board.
  2. More importantly, the soldermask on the Eagle design has gaps between the pins on the connector and the sensor IC. This will help reduce solder bridging between pins. In the KiCad version, the mask apertures look too big.

KiCad Soldermask

KiCad Soldermask

Eagle Soldermask

Eagle Soldermask

In the image below, we can see the SMD Qwiic connector within Eagle. The default soldermask clearance is 0.1mm per side in Eagle.

Soldermask Clearance for Qwiic Connector

In KiCad's Pcbnew, open the ZOPT220x Breakout and click on Dimensions -> Pads Mask Clearance. KiCad's solder mask clearance has a default of 0.2mm per side. We recommend you change this value to 0.1mm. Most fab houses will use 0.1mm as their default as well. You will then need to re-export your gerbers and load them back into GerbView.

KiCad Pad Mask Clearance

Making the clearance smaller than 0.1mm will cause difficulties for the fab house to get the registration correct.

Creating a Custom KiCad Footprint Library

This section will show you how to create your own local custom footprints so that you can use them and connect them to schematic components using CvPcb. We’re going to assume you’ve already been through the previous sections of this tutorial; you should have KiCad downloaded and installed.

Open KiCad’s project manager and then click on the PCB footprint editor button.

PCB Footprint Editor

You may get the warning. That's ok, just click through it. This is KiCad's way of telling you it's going to create the default table of libraries that link to KiCad's extensive GitHub repos.

Warning

Click Preferences -> Footprint Libraries Manager. This will open the list of all the footprint libraries now accessible to you.

Footprint Libraries Manager

This is a tremendous list of libraries! Click ‘OK’ to close the manager.

PCB Footprint Libraries Tables

Let's poke around these libraries. Click on ‘Load footprint from library’ button and then ‘Select by Browser’. This is a handy tool for perusing the available footprints.

Load Footprint from Library

Navigate to the LEDs -> LED_CREE-XHP50_12V footprint. Here is an example footprint in LEDs library. Double click on this footprint to open it up in the editor.

Library Browser

Note the title bar of the editor window has changed. The active library is now LEDs and it is read only. Obviously KiCad wants to control their libraries; not just anyone can save to their repos. If we want to edit this footprint we need our own local copy.

Open Example Footprint

Let's create a local directory to keep all our local footprints. For this tutorial, please create a local folder called ‘C:\KiCadLibs\’ (or your platform's equivalent).

Now click on File->Save Footprint in New Library.

Save Footprint in New Library

I recommend using different directory names for different sets of footprints (resistors, connectors, LEDs, etc). Select the ‘KiCadLibs’ folder that was created and then type ‘\LEDs’. KiCad will create the new ‘LEDs.pretty’ directory with a file ‘C:\KiCadLibs\LEDs.pretty\LED_CREE-XHP50_12V.kicad_mod’. And we're off to the races. Except, not quite yet.

Save Footprint to Different Directory

Notice the title bar in the Footprint Editor still states the active library is LEDs and is read only. We need to switch the active directory to our local folder. I'm going to head you off: File->Set Active Directory doesn't work as it only gives you the list of libraries that KiCad ships with. Oh KiCad!

Before we can set our new footprint directory as active, we need to make KiCad aware of it. Re-open the Preferences -> Footprint Libraries Manager.

Add Footprint Libraries Wizard

Click on the ‘Append with Wizard’ button. You’ll be asked to locate the directory you want to add. In this case, we want to add the ‘Files on my computer’. Click on the ‘Next >’ button, select the directory we created (i.e. ‘C:\KiCadLibs\LEDs.pretty’. Click on ‘Next >’ a few times. When prompted ‘Where do you wish the new libraries to be added’, select ‘To Global library configuration (visible to all projects)’ and click ‘Finish’.

KiCad may throw an error because the ‘LEDs’ nickname is used twice. I renamed mine to ‘LEDs-Custom’ then click on ‘OK’ to close out the Footprint Libraries Manager.

Add Footprint Libraries Wizard Error

If you inspect the Footprint Editor tool bar again, you'll see the LEDs library is still active and read only. Now we can click on ‘File->Set Active Library’. Here is where KiCad shines - the Filter works well. Type LED and select the LEDs-Custom library.

Active Local Library

At last! We have an active local library. Now when you click ‘Save footprint in local library’ or press ‘ctrl+s’ KiCad will prompt you with a Save Footprint window with Name (annoyingly every time). Press enter and your modifications will be saved.

Now you can explore creating and editing footprints using the Footprint Editor.

After you’ve created your first footprint or two be sure to read KiCad’s KiCad Library Conventions (KLC). It’s a well documented system for creating community share-able footprints. Left to our own devices we will all create things a little differently; the KLC tries to get us all on the same page and SparkFun follows it.

In the future, if you’re creating a lot of footprints consider using git repo to manage the changes. At SparkFun, we use the following structure:

  • \SparkFun-KiCad-Libraries - A git repo directory containing all KiCad schematic component files (*.lib)
  • \SparkFun-KiCad-Libraries\Footprints - Contains directories of footprints
  • \SparkFun-KiCad-Libraries\Footprints\LEDs.pretty - Directory containing all the LED footprints (*.kicad_mod)
  • \SparkFun-KiCad-Libraries\Footprints\Sensors.pretty - Directory containing all the sensor footprints (*.kicad_mod)
  • etc.

By using a git repo, SparkFun engineers and our users can contribute schematic components and footprints.

Paring Down the KiCad Libraries

When opening CvPcb to assign footprints to the schematic components, it can take a very long time to load. This is because KiCad is pinging all the KiCad github repos and pulling down 93 libraries. To make this faster, we recommend removing the libraries that are either deprecated or libraries that you will never use.

Remove Libraries Deprecated or Never Used

It's quick and easy to remove a library: select a row in the Footprint Libraries Manager and click the ‘Remove Library’ button. If something goes wrong, don't panic! Simply click ‘Cancel’ in the manager window and the library manager will close without saving changes. If things go really wrong, you can always delete the ‘fp-lib-table’ file and restart KiCad. This will cause it to create the footprint table with the KiCad defaults.

The footprint libraries table file (on Windows 10) is located in your AppData. It should look similar to: ‘C:\Users\Nathan\AppData\Roaming\kicad\fp-lib-table’ .

Contents of fp-lib-table

The contents of ‘fp-lib-table’

Removing the deprecated libraries brings the default count down to 75 and CvPcb still takes an annoyingly long time to load. This is where you'll have to make some tough decisions. Do you plan to ever need the ‘Shielding-Cabinets’ library? Perhaps. Perhaps not. If I ever do need an RF shield for a design, it will most likely be a custom part or a part that is not in the library. So that one gets the toss.

SparkFun is taking a blended approach. We're becoming very familiar with the default KiCad libraries and using their footprints wherever it makes sense. When we find or use a package we like, we copy it over to the SparkFun-KiCad-Libraries GitHub repo. At the same time, we're continuing to leverage all our custom Eagle footprints that we've been using and creating for over a decade. We know and trust these footprints. I have had many PCBs ruined because I trusted someone else's footprint so I tend to be very paranoid. Use the community where you can but be very rigorous about checking them for correctness.

If you're needing a generic 2x5 pin male header, check the KiCad libraries. It should work fine. However, if you're using a more eclectic part, you may be better off creating the footprint from scratch. Even if the KiCad libraries contain the part, you'll want to check it against the datasheet very closely and do a one to one test print.

Using Eagle Footprints in KiCad

If you're familiar with Eagle, it can be scary to think all the time spent creating footprints will be lost when switching to KiCad. Don't fear! KiCad inherently reads Eagle footprints! Yep, it's built right in. Now don't get too excited. KiCad can't read your Eagle schematic components but we have a solution for that in a later section.

Eagle Footprint

The approach we are taking at SparkFun is to link to a local copy of all our classic Eagle Librarie Anytime we need one of the Eagle footprints, we copy and paste it into a modern KiCad library. We don't have to re-create the footprint but by moving it over to a KiCad library. We are able to then edit the footprint as needed. Furthermore, any new footprints are created from scratch and saved to the appropriate SparkFun KiCad library.

You should have already opened the PCB Footprint Editor at least once by now. This will have created a ‘fp-lib-table’ file that we will be editing shortly. Now to get started, be sure that KiCad is closed.

Download the SparkFun Eagle Libraries from GitHub.

SparkFun Eagle Library GitHub Repository

Unzip them into a local directory of your choice. I store our Eagle libraries in a DropBox folder so both my desktop and laptop can access the same set of files.

You could use the Footprint Libraries Manager located in the footprint editor but adding or removing many libraries becomes tedious; it's easier to edit the table file directly.

fp-lib-table

The contents of fp-lib-table

The ‘fp-lib-table’ tells KiCad where to find all the various libraries and what types of libraries they are (KiCad, github, EAGLE, etc).

We are going to edit this file to add in the SparkFun libraries as well as remove the deprecated libraries and libraries that SparkFun doesn't use.

Here are the files of importance:

  • original fp-lib-table - This is what KiCad creates by default. You don't really need to download it. It's just for reference.
  • sparkfun fp-lib-table - The list of SparkFun libraries. You don't need to download it, just for reference.
  • combined fp-lib-table - This is the combination of the original table, with extraneous libraries removed and SparkFun libraries added.

Download the ‘combined fp-lib-table’ to a local folder. Rename it to ‘fp-lib-table’. Now move the file to where KiCad expects it. The footprint libraries table file (on Windows 10) is located in the AppData folder similar to: ‘C:\Users\Nathan\AppData\Roaming\kicad\fp-lib-table’. You'll want to overwrite the file that is there.

Once the file is in place, re-open KiCad, open the PCB footprint editor, and finally the Footprint Libraries Manager. You should see a long list of libraries including the new SparkFun libraries.

Included SparkFun Libraries

The last step is to tell KiCad the local path to the SparkFun libraries. Currently it's a variable called SFE_LOCAL. We need to assign this to something. Close the Library Manager window, click on Preferences -> Configuration Paths. Click the ‘Add’ button. Edit the Name and Path fields.

In the image below, you can see I've set the ‘SFE_LOCAL’ variable to a local path of ‘C:\Users\nathan.seidle\Dropbox\Projects\SparkFun-Eagle-Libraries\’. Set this variable to wherever you locally stored the SparkFun Eagle Libraries.

Local Path Configuration

Congratulations! You can now see, use, and copy all the SparkFun Eagle libraries.

Included SparkFun Eagle Libraries

Creating Custom KiCad Schematic Components

Once you’ve learned to create your own schematic parts and custom footprints, you become unlimited by what technologies you can play with. Let’s get started!

From the main project window start the Schematic library editor.

Schematic Library Editor

This process is similar to how we started a custom footprint library. First, let's find a schematic symbol we want to start our custom library with. The photocell is just as common as it gets. Let's pull in the ‘R_PHOTO’ schematic component from the device library and use it to start our new custom schematic component library.

Start by clicking on the ‘Selecting working library’ (i.e. book) icon located in the upper left corner. Then select ‘device’ to set the working library.

Select Device

Click on the ‘Load component to edit from current library’ button and type r_photo in the filter to quickly locate the photoresistor component. When located, click ‘OK’.

Load Component

Click on ‘Save current component to new library’ button

Save Current Component to New Library

I recommend you store this *.lib file in the same ‘C:\KiCadLibs\’ directory we stored the footprint library within. I called my lib file ‘CustomComponents.lib’ so that I know these are mine.

Save Custom Component

Once you click ‘Save’, a warning will pop up. This is just KiCad's polite way of letting you know that you can't access your library until you link to it. So let's do that.

Warning

Click on Preferences -> Component Libraries to view the current set of libraries. In the image below, we can see the stock schematic component libraries that ship with KiCad. Next to the ‘Component library files,’ click ‘Add’.

Component Libraries

Navigate to your ‘C:\KiCadLibs’ directory and then open ‘CustomComponents.lib’. It should now appear at the bottom of the Component library files list. Click ‘OK’ to return to the library editor.

Again, click on the ‘Select working library’ button but this time either scroll to your custom list or type ‘Custom’ to find the ‘CustomComponents’ library. Click ‘OK’.

Select Working Library

Then click on ‘Load component to edit from the current library’ button and we should see only the photoresistor schematic component. Double click on R_PHOTO to begin editing it.

R_PHOTO

Now at this point, we can add new symbols from scratch to our library and we can also copy from one library to another.

How to Copy a Component to Your Custom KiCad Library

KiCad is always changing and they've made leaps and bounds improvements but copying a schematic component from one library to another is still a bit wild.

For example, let's copy the CP2104 from the silabs library into our custom library. Start by setting the active library to the one that contains the part you want to copy by clicking on the ‘Select working library’ button. In our example, we want to set silabs as the active library.

Selecting silabs library into custom library

Load the CP2104 component by clicking on the ‘Load component to edit from the current library’ button.

Now set the active library to the library we want to copy the CP2104 into. For this example, that means that we need to click on the ‘Select working library’ button and set the active library to ‘CustomComponents’.

Custom Components

Click on the ‘Update current component in current library’ button to save the component in CustomComponents.lib. The ‘Save current library to disk’ button will become enabled and you can save this component to your custom library.

Load Component to Edit

To verify it's now in the library click on the ‘Load component to edit from the current library’ button. You should see your new shiny CP2104 in the list.

How to Delete a Component from Your Custom KiCad Library

Bad CP2104! Bad component.

To remove a component, be sure you've set your custom library as the active one. Let's try removing the component that we just added in our custom library CustomComponents.lib. If you have not already, click on ‘Select working library’ to set the active library to CustomComponents. Click on the ‘Delete component in current library’ (i.e. the trash can) button. You'll be prompted for which component you want to remove. Select CP2104 from the list.

Delete a Component from Custom Library

Click ‘OK’ and then ‘Yes’ to delete the component from the library. Click the ‘Current library to disk’ button and ‘Yes’ to save.

Shout out to Joan_Sparky! He is the best! (No relation)

KiCad Library Convention

Be sure to check KiCad's KiCad Library Convention once you get comfortable creating components. These conventions take into account a heap of industry specialized knowledge that we can all benefit from.

Resources and Going Further

Congratulations! That was a big tutorial and you made it through.

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

Now that you’ve learned how to modify schematics, PCB layouts, and libraries, it’s time to try out your skills on your own custom project. We recommend using the ZOPT220x UV Sensor Breakout KiCad files as the starting point for your next project. From this example project, you can delete or add devices as you need rather than starting from a blank canvas.

Also, check out SparkFun's Enginursday blog post about KiCad.

Eagle to KiCad

If you are an EAGLE guru starting to get your feet wet with KiCad, be sure to checkout Lachlan’s Eagle to KiCad converter for converting your Eagle PCB layouts to KiCad. It’s not perfect but Lachlan has done a tremendous amount of groundwork.

Thanks for reading and if you have any comments or questions please ask them in the comments section.


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

SparkFun Troubleshooting Tips

$
0
0

SparkFun Troubleshooting Tips a learn.sparkfun.com tutorial

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

Introduction

“It’s not working!” A common utterance made when working with electronics. But, have no fear. There are numerous troubleshooting tips that make diagnosing your problem much simpler than it may seem. In this tutorial, we will be exploring a few general troubleshooting tips and possible solutions that frequently come up in SparkFun’s Technical Support department. Some of these tips may not apply to all cases and projects, but it is a good place to start to determine the source of the problem.

EL Escudo Destruction

Assumptions

The development and breakout boards that are produced by SparkFun are usually tested on a pogobed and inspected by a technician for quality control before they are packaged and sent out. Let’s assume that the boards are good to start.

Electronics Assembly

How SparkFun assembles SMD electronics.

Constant Innovation in Quality Control

In this article, we share our recent advancements in quality control. Along with making our tests more thorough, we have also made them more efficient and robust.

Suggested Reading

If you aren’t familiar with the following concepts, we recommend checking out some of these skill tutorials. The complexity of the project may require additional skills to help you troubleshoot.

How to Solder: Through-Hole Soldering

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

Working with Wire

How to strip, crimp and work with wire.

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.

How to Read a Schematic

An overview of component circuit symbols, and tips and tricks for better schematic reading. Click here, and become schematic-literate today!

Serial Terminal Basics

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

How to Use a Multimeter

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

Start Something

“I want to connect 10,080 addressable LEDs attached to a network of wireless modules and controlled by one board attached to a shark. Oh, and I have not worked with electronics before.”

Whoa, whoa, whoa. Let's take a giant step back and start simple before going crazy with a project. Also, please leave any animals out of the project! Our technical support department receives some interesting cases. The above example is a generalization of the questions that we get in support. Before we even dive into a project, let’s begin with the basics and where to look for information to get started. You will want to start by checking out any associated documents. Dream big, but start with these small steps.

Start at the Product Page and Kits

We at SparkFun try our best to provide information about the parts sold in our catalog. Besides reading the product description, try checking out a product page’s document section for resources. Depending on the product, there can be a number of useful links.

Let's take a look at the SparkFun FTDI Basic Breakout — 3.3V! The information linked on the product page can range from:

  • Schematics
  • Eagle Design Files
  • Hookup and Experimental Guides
  • Project Tutorials
  • Drivers
  • Datasheets
  • User Manuals
  • GitHub Repositories

If you scroll down past the recommended products, “Product Help and Resources” may show up if there is information linked to the product. These can range from tutorials to technical support tips to projects that the part has been used in under Hackster.io. Farther down at the bottom (not shown in this image), you will also notice a section for comments provided by users.

SparkFun Product Page

You can also check out the specific development boards used in kits to get started. There are basic examples and projects within each of these kits to help you get started with the product. If you have not worked with hardware electronics or programming before, you might want to check out the SparkFun Inventor's Kit V3.3 for RedBoard or micro:bit. These kits do not require you to solder components together.

SparkFun Inventor's Kit - V3.3

KIT-13969
4
SparkFun Inventor's Kit for RedBot

ROB-12649
$119.95
22
Raspberry Pi 3 Starter Kit

KIT-13826
$89.95
33
SparkFun Inventor's Kit for micro:bit

KIT-14300
$49.95
1
SparkFun Inventor's Kit for Photon

KIT-13320
$114.95
12
SparkFun IoT Starter Kit with Blynk Board

KIT-13865
$69.95
6

Datasheets and Manuals

Depending on the complexity of the board, there can be a lot of components on the PCB with different specs. We usually try to think about the main IC on the breakout board and look at the Absolute Maximum Ratings for the I/O pins, how much the chip can handle overall, and what the IC is able to do. Try looking at our previous tutorial on How to Read a Datasheet for tips on reading a datasheet. User manuals can also provide examples and application notes on how to use the product.

Pete Manual

Online Research for Resources

Besides browsing at SparkFun's growing list of online tutorials, YouTube videos and blog posts (i.e., Enginursdays, Engineering Roundtable, etc.), there are several other resources online. Here a few that might be of use:

The cloud knows all…that is posted on the internet. Besides using the local search engine at the top of the page, try using an online search engine with different search queries to see if anyone has done something similar to what you are doing. Chances are, there is someone in the world who has done the project (or something similar) already, and they have provided some documentation online.

Hardware Checks

So you have followed the instructions, and the part or project does not work as expected. You even tried to do exactly what the hookup guide and tutorial told you to do! Part of working with electronics and programming is diagnosing the problem and finding a remedy to get the part to function. Don't worry; it happens to the best of us, and challenges only help us learn and grow. Let’s try to find out what may be going on in your circuit!

Check Your Connections

Is the part or project connecting? Let's clarify what it means to “check your connections.” A common method of troubleshooting is to check your hardware connections and power for physical problems.

Is there continuity between the pins, and is the connection secure?

Any loose connections can cause problems because it will cause your circuit to be incomplete. It is best to double-check wired connections just in case a wire was connected incorrectly or is loose. The images below show poor electrical connections for prototyping due to the thin wires being inserted into a breadboard and female header sockets. Any bumps and vibrations applied to the circuit can cause the circuit to lose its connection.

Somewhat Reliable: Lidar Connected with Breadboard
Not Reliable: Lidar Connected to RedBoard and Breadboard
Not Reliable: Fingerprint Scanner Connected to Female Header of Arduino Pro Mini 3.3V

The small wires connected to the breadboard may become loose depending on how it was manufactured and how much wear was applied to the metal strip. The thin wires connected in the female headers are worse due to the tolerance of the socket.

For a more secure connection, it would be better to solder the wires to header pins and add heat shrink. You can also make an adapter using the SparkFun snappable protoboard or make a custom shield using any of the prototyping boards.

Are there shorts?

Shorts in your circuit can cause problems if there is a pin touching something that it is not supposed to. Make sure that components are not getting extremely hot to the touch. If pins are shorting, remove power and check to see if a loose wire is touching something that it should not. Make sure the board is not on top of a metal table.

Is the wire or cable bad?

Sometimes a wire or cable is bad, causing the circuit to not connect. You can try checking the circuit with a multimeter set to measure continuity. Otherwise, try using a different wire or cable.

Where did you get the USB cable from?

Certain cables are designed to be charging cables, so there might not be any data lines connected in the USB cable. Also, there might be internal micro tears in the cables. We recommend checking and using a different USB cable. We had an instance where a customer was using USB cables from his school's lab to upload code to an Arduino. Three out of the four cables were bad because they were damaged. The fourth cable worked with his device. You might want to try ordering a brand-new USB cable if that is the case.

Did you use the basic hookup?

If everything appears to be wired correctly, you might want to try going back to the beginning and looking at the basic hookup. Also, disconnecting the parts and rewiring each circuit can help troubleshoot. This will assist in narrowing down the problem.

Keep in mind that two parts may be named similarly or look the same, but in reality they are not. For example, while an Arduino Mega 2560 has the name Arduino in it, it may not be a direct replacement for a circuit that uses an Arduino Uno R3. There are a few subtle differences that some may not be aware of (i.e., different pin locations, limitations in Software Serial, board definition, etc). Sometimes you may need to redefine a pin or rewire the circuit to get it working as expected.

Make sure that you are grabbing the correct part from your parts bin by double-checking the IC’s label. As an example, the TMP36 is not the same as a BJT transistor. While the package appears to be the same, they are different! This is common in our SparkFun Inventor’s Kit. In another case, a customer had used a different n-channel mosfet. While the n-channel mosfet looked the same, the specs were different, causing the transistor to not fully turn on in the circuit.

Check Your Solder Joints

Are your solder joints ideal and making a sufficient connection?

Ah yes, we check the connections once again. If you are trying to connect a breakout board on a breadboard using wires, you will want to make sure that the connection between the breakout board and the wire is sufficient. The three images shown below are not ideal solder joints.

In the first image, there are no solder joints connecting the header pins to the breadboard. This is a great idea if you need help soldering header pins, but not if you are trying to connect the Pro Mini to other breakout boards.

Pro Mini No Solder On Breadboard

Not Reliable: Pro Mini and Header Pins With No Solder on Breadboard

The second image might have solder, but the joints are not ideal. The first pin along row 30 has no solder. The pin on row 29 has some solder on the header, but there is no contact with the board. The pin on row 28 is OK, but it has too much solder on it. Some of the solder blob is also extending from the pin. The pins on row 27 and 26 have an unintentional solder jumper. The pin on row 25 may have solder on the through-hole pad and pin, but it is not connecting. The only pin that seems to have an ideal solder joint is the RST pin on row 21. We would want to rework all the other pins by reheating the pins or adding more solder to make sure the pins have a sufficient solder joint. Additionally, there are unintentional solder jumpers connecting between pins on the Atmega328P IC. To remove unintentional solder jumpers, try using a solder wick and checking out the next question.

Pro Mini Bad Solder

Not Reliable: Pro Mini With Poor Solder Joints

The third image clearly shows the 1x12 header incorrectly soldered on the Pro Mini. Solder should be applied with the shorter side of the header. The black housing holding the pin should be between the PCB and the breadboard. Additionally, the solder joints are extending the length of the pins. The Pro Mini is not able to be fully inserted into a breadboard due to the length of the straight header pins.

Pro Mini With Bad Solder, Wrong Side

Not Reliable: Pro Mini With Poor Solder Joints and Header on the Wrong Side

The solution would be to add solder or rework the solder joints for a secure connection. The image below has ideal solder joints on the Pro Mini. For more information about soldering and ideal solder joints, check out our tutorial for through-hole soldering.

Ideal Solder Joints

Reliable:Ideal Solder Joints Between Arduino Pro Mini and Straight Header Pins

Are there solder jumpers connecting pins where they should?

Depending on the circuit, you may want to have a solder jumper on a certain part of the board. If there are unintentional solder jumpers on the IC or header pins, the solution would be to rework the board and remove the solder jumper.

Below is an example of a solder joint that was not intentional for the “Simon Says” PTH Soldering Kit.

Solder Jumper

To fix, you could grab a solder wick to remove the solder jumper. For more information on how to use a solder wick, try checking out the Troubleshooting section here labeled “Solder Jumpers.”

Is there water-soluble flux residue on the boards?

If you are using water-soluble flux, you want to make sure to remove any water soluble flux residue that is left on the board. This is to prevent pin oxidation and temporary shorts between pins caused by dendrites. Below is an image of water-soluble flux residue left on a production panel.

Flux on Board

While some circuits may work fine with the flux left in place, we have seen dirty boards wreak havoc on boards that are sending a signal through a serial UART (i.e., uploading code to an Arduino or sending an ASCII character to another UART) or I2C. It is better to avoid any issues caused by water-soluble flux left on the board. In fact, the SparkFun boards that we assembled are washed if they use this type of flux!

To remove water-soluble flux residue, you can use a little deionized water or isopropyl alcohol and a toothbrush. Alternatives to deionized water may be to use non-mineral bottled water first before tap water for hobby use. However, deposits from tap water could form and cause problems in the future. Using compressed air, you would dry the board to remove any excess flux residue or water that is on the board. Hot air from a heat gun or rework station can also be used to dry the board.

Certain components are sensitive to water, so you should be careful about getting these components wet. Here is a short list of components that should avoid contact with water:

  • Character LCDs
  • 7-Segment LED Displays
  • Batteries
  • GPS Modules
  • Wireless Modules
  • Barometric Pressure Sensors
  • Slide Potentiometers
  • Microphones
  • Speakers
  • Heart Rate Monitor ICs

If water gets trapped in them and you power the board, it will probably damage the component.

Length of Wire

Are you using extra long wires?

Depending on the conducting material that you are using, the resistance of conductive thread and wires can increase over a certain distance. This is more apparent with conductive thread and the solution may be to double your thread.

If you are using wire over a distance of more than a few hundred feet, you may also notice issues. For example, there have been a few cases where an I2C sensor was not working properly after a certain length. Since I2C was designed to work over a short distance, sensors can have issues sending data when used over a certain number of feet. The solution may be to adjust the pull-up resistors or be clever in sending data (i.e., using a microcontroller for each sensor node and adding a wireless device).

Check Another Computer

Have you tried using a different computer?

We recommend checking with another computer to see if the device can work. We’ve had issues where a device was not working on a customer’s laptop but was working on his/her computer. There was something with the settings of the computer that was preventing them from using the device properly.

Is there a problem with the USB Hub or USB port that you are using?

Try connecting directly to a USB port instead of through a USB hub. The device might not be getting enough power or might not be communicating correctly. Also, there can be issues with using some USB-to-serial converters with USB 3.0. Try testing on a different computer. In some instances, customers were able to get it working on a USB 2.0 hub when the device was not working with a USB 3.0 port.

Check Your Logic Levels

Can I connect a 3.3V sensor to a 5V board?

Not all boards use the same voltage for logic levels. For example, the RedBoard Programmed with Arduino and the Arduino Uno R3 use 5V logic. However, if you move to other boards like the ESP8266, SAMD21, Arduino Due or Raspberry Pi, the I/O pins are not 5V tolerant. Make sure the logic levels match or are tolerant with whatever device you are connecting to the development board.

If the signal only needs to be converted down, you could use three 10k ohm resistors to build a voltage divider. For signals being sent both directions, you could use a logic level converter (i.e., Bi-Directional Logic Level Converter, PCA9306 Level Translator, TXB0104 Voltage Level Translator, etc.) to communicate safely. For more information about logic levels, try checking out the tutorial below.

Logic Levels

June 3, 2013

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

Stacking Multiple Boards

Are you stacking more than one board (i.e., Arduino Shield, Raspberry Pi HAT, Beaglebone Cape, etc.) together on top of your development board?

It may be possible to stack boards together, but that depends on the pins each board is using. Try checking out the board’s design files, schematic and basic example code to determine what pins are being used for each shield. You may need to reroute pins, redefine pins or change the serial addresses (i.e., I2C, SPI) in the code when stacking multiple board together with a development board. When using multiple boards, you will need to combine example code to get it working in the project.

Check Your Location for Interference

Is the component not working in a room or building?

Is there magic in the air or ghosts in your electronics? Maybe. Or you can just try using the board in a different location. This is common among GPS receivers if you are using it inside a building. To avoid GPS lock problems, try using the GPS receiver closer to the perimeter of the building, outside, in a different location to avoid surrounding buildings, or using an external antenna that extends outside.

We’ve also seen problems with ultrasonic sensors when used in certain parts of our building. For example, the HC-SR04 ultrasonic sensor would work fine in one location of the building, but we noticed that the HVAC’s acoustic noise was tuned just enough to interfere with the sensor. To avoid this noise, we had to use the sensor in a different part of the building.

Using a magnetometer and seeing abnormal readings? This might be caused by hard and soft irons in the environment. Try looking at this old tutorial from our retired 9DOF Razor to find more about hard and soft irons.

Check Your Power

Is your power supply sufficient enough?

Make sure that you have a power supply that is able to provide the power that your system needs. For example, if you are lighting up three WS2812B addressable LEDs with an Arduino, a 5V/1A power supply would be sufficient. However, this is a different story if you are lighting up two or more 5M addressable LED strips. For such large installations, you would need a beefy power supply for long lengths and probably need to add power between each 5M segment.

If a power supply is not able to provide enough power, your microcontroller or single-board computer may brown out. As another example, the Raspberry Pi 3 consumes just a bit more current compared to its previous models. While the previous 5V/2A power supplies worked for the earlier generations of the Raspberry Pi, a 5.1V/2.5A power supply is needed to power the Pi 3 sufficiently.

Why does my Arduino stop working every time my motor starts up?

Try checking your power supply. It’s possible that the motors are causing a dip in voltage and causing the microcontroller to brown out. It is usually suggested to have an external power supply connected to the motors to prevent brownouts and resetting the microcontroller. Make sure to connect the GND to the rest of the system for reference. You could also use a beefier power supply that is able to provide enough power for both the motor and microcontroller.

Why does my project work with a power supply connected to a wall outlet but not with a 9V battery?

Depending on the battery chemistry and the manufacturer of the battery, the discharge rate may be different from a power supply that is connected to a wall outlet. The internal resistance is higher for 9V batteries compared with other battery types. Also, the internal resistance varies among manufacturers. Therefore, it is not an ideal source for high-current applications. You may want to consider using other battery chemistries to power the project.

Power Cycle

My project was working fine when connected to the wall outlet for a few months, but it is now not working as expected.

Try power cycling the project by removing power and powering the circuit back up. If there is a reset button, you may be able to just hit that button. You may need to unplug the power supply from the wall outlet, disconnect the power Vin, wait a few seconds, reconnect the power supply to Vin, and insert the power supply back into the wall outlet. Try testing the wall adapter with a multimeter to see if it is still outputting power or plugging a known good lamp into the wall outlet.

Heat Dissipation

Is it normal that my motor driver is getting hot to the touch?

Heat dissipation is normal when using a motor driver and motor. Depending on how hard the driver IC is being pushed and the power supply being used, you may need a heatsink to achieve the full potential of the motor driver. Such breakout boards are usually designed to help with some heat dissipation. In addition to adding a heatsink, there are methods of dealing with heat.

Electrostatic Discharge (ESD)

Did you ground yourself before touching the device?

Certain devices are sensitive to static electricity. When moving around, a person can build up static electricity and discharge it through the board. It can be worse during the winter when walking over carpet. Make sure to touch a metal cabinet to ground yourself. While some boards can handle a few minor shocks, the IC can be damaged after a certain point.

Limitations of the Product

Are you using the component as expected?

When a product is released to the wild, it might not be used as intended. For example, usually you think of LEDs as emitting light. However, it is possible to use a microcontroller and LED to detect light.

Now don’t expect all components to be able to do what they are not intended to do. For example, the XBee Series 1 transceiver may be able to transmit data wirelessly, but do not expect it to be able to stream video reliably like a WiFi dongle. The specifications (i.e., data rate) are different.

Wireless

Why won’t my wireless device connect to the wireless network?

Try checking to see if you are using the correct WiFi network name and password. It is possible that the credentials were entered incorrectly. The example codes provided with WiFi-enabled devices (like the SparkFun ESP8266 Thing Development Board) require you to manually enter the network name and password.

Just like checking another computer, you may want to try testing the WiFi-enabled device on another WiFi network. Using a WiFi-enabled device can be a problem if you are using the device in a school network. Due to a school’s configuration, you may need to contact your local IT department that manages the wireless network to allow the device to connect. It also may be possible that the wireless router is damaged or not compatible with the wireless-enabled device.

Why won’t my wireless device work inside of a metal enclosure?

Placing a wireless device inside a metal enclosure (i.e., a Faraday cage) essentially limits and can block any electromagnetic fields. Signals being sent or received will not be able to be transmitted. Try using an external antenna so that the transceiver is able to extend outside of the metal enclosure.

Software Checks

There are many languages out there. For the scope of this tutorial and troubleshooting, we are going to focus on the Arduino IDE (Integrated Development Environment) and common problems when uploading code to an Arduino development board. However, some of these tips may be useful when troubleshooting in other development environments.

FTDI Drivers

Did you install the FTDI drivers?

If you have not uploaded to an Arduino that uses an FTDI before or connected an FTDI to your computer, you need to make sure that you have installed the latest FTDI drivers. Try looking at the tutorial listed below for installing the driver for your operating system.

How to Install FTDI Drivers

June 4, 2013

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

The tutorial is based off of FTDI’s instructions. For more in-depth guidance, try looking at FTDI’s Installation Guides.

How do I know if I have the FTDI drivers installed?

With the device is plugged in, you can see a few COM ports when you select Tools > Serial Port in the Arduino IDE’s menu. When you unplug the device and reopen Tools > Serial Port, you might see a COM port disappear. By process of elimination, you can see what COM port it has enumerated to. You can also see this when you open your device manager checking the Ports (COM & LPT) tree.

How do I know if my FTDI is sending serial data?

To verify that the FTDI is working, you could do a serial loop back test or echo test. In order to perform this test, you would connect a jumper wire between the UART pins Rx and Tx. Open a serial terminal (like Tera Term) with the setting 9600 baud, 8-none-1-none. By typing into the serial terminal, any characters sent using a keyboard will be echoed back on the screen. You should also see the Rx and Tx status LEDs indicating when data is being sent.

Arduino IDE Versions

Is there something wrong with my Arduino IDE?

There are improvements and benefits with each version release of the Arduino IDE. However, there can be unforeseen bugs and differences in the way that code is compiled. If there are warnings in the error output, usually you can ignore them. If you are having issues compiling, sometimes you need to uninstall and reinstall the Arduino IDE on a computer. You can also try deleting certain Arduino files.

If the Arduino-based development board does not require a certain IDE version, you can try rolling back and using a lower version of the Arduino IDE (like v1.6.5). Rolling back and testing with a stable/working IDE may be the solution until the next release.

Board Selection

Did you select the correct board definition?

If you did not select the correct board definition, you will not able to upload code. Check the Arduino’s associated documentation for more information on the correct board selection. You can find a list of Arduino board definitions in the Tools > Board selection menu.

Why am I not able to see my Arduino board in the board selection menu?

There can be some issues with the Arduino IDE v1.6+ due to the different file structure requirements. This may cause an Arduino board to not show up in the default list.

The latest SparkFun Arduino-compatible board updates can be found on the SparkFun Arduino board add-on GitHub repository. This repository contains support for SparkFun’s Arduino-compatible development boards and instructions on how to install the board add-ons:

SparkFun Arduino Board Add-On GitHub Repo

If you tried installing the latest board and code is still not compiling, you may want to roll back to a previous version of the board add-on. If there was more than one board version released, you should be able to click on the board in the board manager and see a small dropdown menu for different versions.

COM Port Selection

Did you select the correct COM port?

You need to make sure that you are selecting the correct COM port in your Tools > Serial Port menu. With the device plugged in, you can see a few COM ports when you select Tools > Serial Port in the Arduino IDE’s menu. When you unplug the device and reopen Tools > Serial Port, you might see a COM port disappear. By process of elimination, you can see what COM port it has enumerated to. You can also see this when you open your device manager checking the Ports (COM & LPT) tree.

Installed Arduino Libraries

Does your example code require libraries to be installed?

If you don’t install the libraries, Arduino won’t understand certain functions because they were not defined for it. You will usually be able to see example code try to include it near the top of the sketch file. I recommend looking at this tutorial to properly install the libraries.

Installing an Arduino Library

January 11, 2013

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

I installed the necessary Arduino libraries, so why is it still not compiling?

Try reinstalling the Arduino IDE. There was one case when one of our engineers uninstalled and reinstalled the Arduino IDE when he had problems with a library. Otherwise, you may want to reinstall the Arduino library. Sometimes the library downloaded is corrupt or accidentally installed wrong, so you would need to reinstall the Arduino library.

Corrupt Bootloader or Bricked Arduino

How do I recover my Arduino if the bootloader is corrupt?

If you have another Arduino microcontroller or an AVR programmer, you could reinstall the bootloader. The tutorial listed below was written for an Arduino Uno with ATmega328P. If you are using a different AVR microcontroller or Arduino-compatible board, you may need to select a different board definition to burn its bootloader.

Installing an Arduino Bootloader

December 4, 2013

This tutorial will teach you what a bootloader is, why you would need to install/reinstall it, and go over the process of doing so.

My Arduino with ATmega32U4 stopped working after uploading new code. What happened to my ATmega32U4-based microcontroller?

Most likely the wrong board definition was selected when uploading code, or something is interfering with the register that handles COM port communication. There is a way to recover the ATmega32U4-based Arduino using the double reset method. You may need an AVR programmer as a last resort. Try checking out the comment here for links to more in-depth tips on recovering ATmega32U4s with different bootloaders.

Semantics Error and Debugging

Why is my code not working even though it compiles?

This sounds like a pretty general question, but it’s likely a semantic error. While the code is able to compile and is free from syntax errors, the code might not be written to do what you intended. Assuming the hardware connections and boards are good, it is possible that:

  • A pin or variable was not initialized correctly.
  • A variable was not calculated and saved correctly.
  • The wrong variable is printing to the Serial Monitor.
  • You are using values outside of an array[].
  • There is a baud rate mismatch.
  • A delay() function is preventing a certain line from executing fast enough.
  • The sequence of code is not executed properly.

The list of reasons why this may be happening can go on depending on the complexity of the project. The simplest method of debugging can be turning on an LED when we reach a certain part of the code. However, the best method of troubleshooting Arduino code is to try to step through using the serial.print() function to debug. If used correctly, the function is more flexible and can indicate that we have entered a line of code.

Maybe you want to print “I entered this function” to the Serial Monitor after pressing a button or when a sensor reaches a certain value. The serial.print() function can also be used to inspect variables in order to know what to expect from a sensor’s output range. The function can also be used to verify calculations. Other environments allow you to step through the code to simulate what may happen without the need for serial.print().

SparkFun Troubleshooting Checklist

Regardless of our level of experience, failure rates can be reduced and issues can sometimes be resolved faster by having a checklist. Here is a list of questions to ask yourself when troubleshooting your project:

Hardware Checks

Check Your Connections

     ▢ Is there continuity between the pins, and is the connection secure?
     ▢ Are there shorts?
     ▢ Is the wire or cable bad?
     ▢ Where did you get the USB cable?
     ▢ Did you use the basic hookup?
     ▢ Are your solder joints ideal and making a sufficient connection?
     ▢ Are there solder jumpers connecting pins where they should?
     ▢ Is there water-soluble flux residue on the boards?

Length of Wire

     ▢ Are you using extra long wires?
     ▢ Have you tried using a different computer?
     ▢ Is there a problem with the USB Hub or USB port that you are using?

Check Your Logic Levels

     ▢ Can you connect a 3.3V sensor to a 5V board?

Stacking Multiple Boards

     ▢ Are you stacking more than one board (e.g., Arduino shield, Raspberry Pi HAT, Beaglebone Cape, etc.) together on top of your development board?

Check Your Location for Interference

     ▢ Is the component not working in a particular room or building?

Power Supply

     ▢ Is your power supply sufficient?
     ▢ Does your Arduino stop working every time your motor starts up?
     ▢ Does your project work with a power supply connected to a wall outlet but not with a 9V battery?

Power Cycle

     ▢ Was your project working fine when connected to the wall outlet for a few months, but is now not working as expected?

Heat Dissipation

     ▢ Is your motor driver getting hot to the touch? Is this normal?

Electrostatic Discharge (ESD)

     ▢ Did you ground yourself before touching the device?

Limitations of the Product

     ▢ Are you using the component as expected?

Wireless

     ▢ Will your wireless device not connect to the wireless network?

     ▢ Will your wireless device not work inside of a metal enclosure?

Software Checks

FTDI Drivers

     ▢ Did you install the FTDI drivers?
     ▢ How can you tell if you have the FTDI drivers installed?
     ▢ How can you tell if your FTDI is sending serial data?

Arduino IDE Versions

     ▢ Is there something wrong with your Arduino IDE?

Board Selection

     ▢ Did you select the correct board definition?

COM Port Selection

     ▢ Did you select the correct COM port?

Installed Arduino Libraries

     ▢ Does your example code require libraries to be installed?

     ▢ You installed the necessary Arduino libraries, so why is it still not compiling?

Corrupt Bootloader or Bricked Arduino

     ▢ How do you recover your Arduino if the bootloader is corrupt?
     ▢ Your Arduino with ATmega32U4 stopped working after uploading new code. What happened to the ATmega32U4-based microcontroller?

Check, Test and Recheck

Maybe you rushed through a step. Try checking back through the troubleshooting checklist. Or maybe your assumption was wrong? Check your assumptions. While rare, it’s possible that there is something on the board that is bad (e.g., tombstoned SMD components, insufficient solder or a bad PCB).

Help!

Still having problems after going through the troubleshooting checklist, tests and rechecks? We do have a small team of technical support representatives who might be able to help you with your SparkFun product(s)! Technical support is here to help suggest products to purchase and ensure that those products are working as expected. We find that email is the best form of contact, as we can share the highest level of information and documentation this way.

When contacting SparkFun technical support, please be ready with as much information as possible. In some cases, customers were able to resolve their issues by gathering some of this information:

  • SparkFun Order or Customer Number— This is the invoice number that can be found at the top of your order’s packing list. You can also find your customer number by logging into your account. Below is an image of where you can find your invoice number if your order was from SparkFun.

Location of Order Number

  • SparkFun Part Number (i.e., SKU)— This can be found in the invoice's list of items or on the product page.

SKU

  • High-Quality, Clear Images of Solder Joints and Setup— A few high-quality, clear images of the solder joints and setup will be useful. Make sure that the image is focused and there is adequate lighting. Look at the photo to verify that we can see the circuit before submitting.

    Below shows a poor image of the setup, where it is hard to see what is going on. That candy bar does look appealing, though.


    The image below shows a clear picture of the solder joints that can help us troubleshoot.



    The image below shows a clear image of the setup and pin connections. While the wires are cut off, we should be able to follow the connections. However, it may be a problem when troubleshooting if there is more than one wire with the same color.



  • Information About Your Setup— This can include the power supply’s voltage and current settings, if the board was powered, modifications to the board, additional parts connected to the system, or your environment.

Once you have this information ready, check out our support page for more assistance and availability.

SparkFun Technical Support Page

Resources and Going Further

Check out some of SparkFun’s resources below:


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

Qwiic Shield for Arduino & Photon Hookup Guide

$
0
0

Qwiic Shield for Arduino & Photon Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The Qwiic Shield (for Arduino or Particle Photon) is the first step in getting acquainted with SparkFun’s Qwiic connect ecosystem. It connects the I2C bus (GND, 3.3V, SDA, and SCL) on your Arduino or Photon board to a series of SparkFun Qwiic connectors. The board already has the circuitry to convert the 5V given to the 3.3V required by I2C boards in our Qwiic ecosystem. The Arduino shield also has holes for mounting Qwiic boards. Since the Qwiic system allows for daisy chaining (as long as your devices are on different addresses) you can stack as many sensors as you’d like to create a tower of sensing power!

SparkFun Qwiic Shield for Arduino

DEV-14352
$5.95
Qwiic Shield for Photon

SPX-14202
$2.95

Required Materials

To follow along with this hookup guide, you will need any Arduino with the R3 header footprint, or a Photon Board. This includes the Uno, RedBoard and many other Arduino compatible boards! Here are just a few of the compatible boards.

Arduino Uno - R3

DEV-11021
$24.95
102
SparkFun RedBoard - Programmed with Arduino

DEV-13975
$19.95
11
Arduino Mega 2560 R3

DEV-11061
$45.95
45
Particle Photon (Headers)

WRL-13774
$19.00
25

Now you probably didn’t buy the Qwiic shield if you didn’t have any Qwiic products to use with it, right? Well, if you don’t have any Qwiic products, the following might not be a bad place to start.

SparkFun Environmental Combo Breakout - CCS811/BME280 (Qwiic)

SEN-14348
$34.95
SparkFun GPS Breakout - XA1110 (Qwiic)

GPS-14414
$44.95
Qwiic Visible Spectral Sensor - AS7262

SPX-14290
1
Qwiic Adapter

SPX-14237
$0.95

Finally, you’ll need our handy Qwiic connectors to easily connect sensors to your Qwiic shield. Below are a few options.

Qwiic Cable - 500mm

PRT-14429
$1.95
Qwiic Cable - 100mm

PRT-14427
$1.50
Qwiic Cable - 50mm

PRT-14426
$0.95
Qwiic Cable - 200mm

PRT-14428
$1.50

Required Tools

You will need a soldering iron, solder, and general soldering accessories to solder the header pins to the Qwiic shield for Arduino.

Soldering Iron - 30W (US, 110V)

TOL-09507
$9.95
6
Solder Lead Free - 15-gram Tube

TOL-09163
$3.50
2

Suggested Reading

If you aren’t familiar with our new Qwiic system, we recommend reading here for an overview. We would also recommend taking a look at the following tutorials if you aren’t familiar with them.

How to Solder: Through-Hole Soldering

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

Arduino Shields

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

I2C

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

Hardware Overview

Qwiic Shield for Arduino

The Qwiic Shield’s have 4x Qwiic connect ports, all on the same I2C bus. Logic level converters are included for the Qwiic connect port’s SDA and SCL lines so you do not have to worry about using the Qwiic system with 5V (or 3.3V) devices.

In addition to this, a large prototyping area is included. As shown in the image below, the Qwiic shield for Arduino has a few neat features such as a few 3-by-1 rails to help with prototyping.

1x3 rail Arduino Shield

There are also buses for ground, 5V and 3.3V on the shield for Arduino outlined below.

Voltage and GND Rails on Arduino Shield

The headers also allow for every pin on the microcontroller of your choice to still be accessed through the female headers.

Qwiic Shield for Photon

The Qwiic shield for the Particle Photon also has buses for 3.3V and ground. However, they are much smaller.

Qwiic Shield for Photon

Hardware Assembly

To get started with your Qwiic shield or Arduino, all you’ll need to do is solder on headers. For a detailed description of how to do this as well as more information on Arduino shields, simply check out our Arduino shield tutorial. It’ll get you going with attaching those headers to your shield properly.

Once you’ve attached headers to your Qwiic Shield for Arduino, you’re ready to plug it into your Qwiic enabled board of choice. If you need to mount a Qwiic sensor, just grab a few standoffs and screws. Plug in any Qwiic enabled board and get going!

qwiic action

Resources and Going Further

For more information, check out the resources below:

Now that you have your Qwiic shield ready to go, it’s time to check out some of SparkX’s Qwiic enabled products, many of which are on their way to becoming good old fashioned SparkFun products.

Qwiic Micro OLED

SPX-14269
$14.95
Qwiic Magnetometer - MLX90393

SPX-14294
$14.95
Qwiic Mux - PCA9548A

SPX-14293
$14.95
Qwiic Water-Resistant OLED

SPX-14287
$24.95

But I Already Have Sensors!

If you already have a handful of SparkFun sensors and parts? SparkFun has been putting our standard GND/VCC/SDA/SCL pinout on all our I2C boards for many years. This makes it possible to attach a Qwiic Adapter that will get your SparkFun I2C sensor or actuator onto the Qwiic system.

Here is the list of the boards that have the standard I2C pinout and will work with the Qwiic adapter board:


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

SparkFun GPS Breakout - XA1110 (Qwiic) Hookup Guide

$
0
0

SparkFun GPS Breakout - XA1110 (Qwiic) Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The XA1110 GPS module from GTOP is a rare bird indeed. GPS modules are hard to come by, but an I2C GPS+GLONASS module? Now we’re cooking with peanut oil! This small module also utilizes the MediaTek MT3333 chipset, loaded with specialized SparkFun firmware that enables both I2C and Serial ports simultaneously. Using I2C means you won’t have to tie up your serial port with GPS, leaving it open to other possibilities.

SparkFun GPS Breakout - XA1110 (Qwiic)

GPS-14414
$44.95

This module is configured with an on-board RTC battery that enables a warm-start functionality. (Giving the XA1110 just five seconds to first fix) A U.FL connector gives you the option to hook up an external antenna via a U.FL cable

This hookup guide will show you how to get started figuring out where on Earth you are. You’ll also learn how to change the update rate of the GPS up to 10 Hz as well as change the baud rate.

Required Materials

To get started, you’ll need a microcontroller to, well, control everything.

SparkFun RedBoard - Programmed with Arduino

DEV-13975
$19.95
11
SparkFun ESP32 Thing

DEV-13907
$19.95
48
Raspberry Pi 3

DEV-13825
$39.95
80
Particle Photon (Headers)

WRL-13774
$19.00
25

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

SparkFun Qwiic Shield for Arduino

DEV-14352
$5.95
Qwiic Shield for Raspberry Pi

SPX-14292
Qwiic Shield for ESP32

SPX-14203
Qwiic Shield for Photon

SPX-14202
$2.95

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

Qwiic Cable - 500mm

PRT-14429
$1.95
Qwiic Cable - 100mm

PRT-14427
$1.50
Qwiic Cable - 50mm

PRT-14426
$0.95
Qwiic Cable - 200mm

PRT-14428
$1.50

Suggested Reading

If you aren’t familiar with our new Qwiic system, we recommend reading here for an overview. We would also recommend taking a look at the following tutorials if you aren’t familiar with them.

GPS Basics

The Global Positioning System (GPS) is an engineering marvel that we all have access to for a relatively low cost and no subscription fee. With the correct hardware and minimal effort, you can determine your position and time almost anywhere on the globe.

I2C

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

Qwiic Shield for Arduino & Photon Hookup Guide

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

Hardware Overview

Below is a table listing all of the hardware features and specs for the XA1110.

CharacteristicRange
Operating Voltage3.3V: Regulated to 1.8V - 3.6V
Current25 mA (typical)
Hot/Warm/Cold Start1/5/15 seconds
Update Rate1 Hz (default), 0.1-10 Hz
I2C Interface100kHz & 400kHz (3.3V)
I2C Address100kHz & 400kHz (3.3V)
UART9600 bps (default), 4800-115200 bps (3.3V)
Position Accuracy
Satellites99 during search, 33 during tracking
Sensitivity-148dBm Acquisition, -165dBm Tracking
Max Altitude80km (the mesosphere) using the example configuration sketch to enable high-altitude balloon mode
RTC Battery5.5mAh, enables warm start for 15 days without power

Pins

The following table lists all of the XA1110’s pins and their functionality.

PinDescriptionDirection
GNDGroundIn
3.3VPowerIn
SDADataIn
SCLClockIn
INTInterrupt, goes low when NMEA data is ready, after packet is read, the pin pulls highOut
WakeWake upIn
RSTPulling low will reset the moduleIn
PPSProvides one pulse-per-second signalOut
RXUART receiver; to receive commandsIn
TXUART transmitter; outputs GPS informationOut

Optional Features

The XA1110 breakout has several optional features. The first of which is the option to disable the pulse-per-second LED. This can be done by slicing the connection on the JP5 jumper with a hobby knife. The I2C pull-up resistors can also be disconnected by clearing the jumper labeled “I2C PU”. Both jumpers are shown in the below image.

pull up resitor jumper

There is also a U.FL connector on the board, outlined below, which can be used in conjunction with the U.FL cable to connect to an external antenna

U.FL connector

Hardware Assembly

If you haven’t yet assembled your Qwiic Shield, now would be the time to head on over to that tutorial. With the shield assembled, Sparkfun’s new Qwiic environment means that connecting the sensor could not be easier. Just plug one end of the Qwiic cable into the XA1110 breakout, the other into the Qwiic Shield and you’ll be ready to upload a sketch and figure out where you are. It seems too easy, but thats why we made it this way!

XA1110 plugged into shield

Library Overview

First, you’ll need to download and install the Sparkfun I2C GPS library, this can be done using the button below or by using the Arduino Library Manager.

Download the SparkFun I2C GPS Library

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

Before we get started developing a sketch, let’s look at the available functions of the library.

  • boolean begin(TwoWire &wireport = Wire, uint32_t i2cSpeed = I2C_SPEED_STANDARD);begin() is used to start the GPS, it runs sort of like this:
    • Starts running the I2C port at the given port and clock speed
    • Pings the module and checks for a response
    • Returns TRUE if the response is received, FALSE if not.
  • void check();— Checks the module for new data.
  • uint8_t available();— Returns the available number of bytes. Will call check() if zero is available.
  • uint8_t read();— Returns the next available byte.
  • void enableDebugging(Stream &debugPort = Serial);— Outputs various messages to assist in debugging.
  • void disableDebugging();— Pretty self explanatory, turns off debugging.
  • boolean sendMTKpacket(String command);— Can be used to send a command or configuration to the GPS module.
    • The input buffer on the MTK is 255 bytes, so strings must be shorter than 255 bytes.
    • After ending a transmission, give the module 10 ms to process the message.
  • String createMTKpacket(uint16_t packetType, String dataField);— Creates a config sentence (String) from a packetType and any settings. See ‘MTK NMEA Packet’ datasheet for more info.
  • String calcCRCforMTK(String sentence);— XORs bytes to create MTK packet.

Note: Due to a new QZSS satellite recently launched by the Japanese, users in the Asia-Pacific region (Longitude 70 to -160 degrees East) can experience huge drifts in location over the course of 2 hours. In order to remedy this, two options are available. The first is to simply reset the module every 2 hours. The second option is to disable the QZSS feature entirely. To do this, simply use the following command in your setup loop. sendMTKpacket($PMTK352,1*2B);

Examples

You should have downloaded the SparkFun I2C GPS Library in the previous step, if not, go back and click the button to download it. Within should be contained the library along with five examples. We’re going to get you started with the first two examples.

Upload the following example to the microcontroller of your choice.

language:c
#include "SparkFun_I2C_GPS_Arduino_Library.h"
I2CGPS myI2CGPS; //Hook object to the library

void setup()
{
  Serial.begin(115200);
  Serial.println("GTOP Read Example");

  if (myI2CGPS.begin() == false)//Checks for succesful initialization of GPS
  {
    Serial.println("Module failed to respond. Please check wiring.");
    while (1); //Freeze!
  }
  Serial.println("GPS module found!");
}

void loop() //Writes GPS data to the Serial port with a baud rate of 115200
{
  while (myI2CGPS.available()) //available() returns the number of new bytes available from the GPS module
  {
    byte incoming = myI2CGPS.read(); //Read the latest byte from Qwiic GPS

    if(incoming == '$') Serial.println(); //Break the sentences onto new lines
    Serial.write(incoming); //Print this character
  }
}

This first example outputs the raw NMEA sentences. Which look something like this:

NMEA output

If your GPS doesn’t have a satellite fix, you will simply get zeroes instead of numbers. These NMEA sentences may be a little hard to wrap your head around if you don’t fluently speak GPS, so let’s move onto the second example, which will take this data, and use the TinyGPS library to transform it into some sensible latitude and longitude data. The second example requires the TinyGPS library, which can be downloaded using the button below.

Download the Tiny GPS Library

The below example code will take these NMEA sentences and use the displayInfo() function to output some nice and friendly latitude and longitude readings.

language:c
#include <SparkFun_I2C_GPS_Arduino_Library.h> //Use Library Manager or download here: https://github.com/sparkfun/SparkFun_I2C_GPS_Arduino_Library
I2CGPS myI2CGPS; //Hook object to the library

#include <TinyGPS++.h> //From: https://github.com/mikalhart/TinyGPSPlus
TinyGPSPlus gps; //Declare gps object

void setup()
{
  Serial.begin(115200);
  Serial.println("GTOP Read Example");

  if (myI2CGPS.begin() == false)
  {
    Serial.println("Module failed to respond. Please check wiring.");
    while (1); //Freeze!
  }
  Serial.println("GPS module found!");
}

void loop()
{
  while (myI2CGPS.available()) //available() returns the number of new bytes available from the GPS module
  {
    gps.encode(myI2CGPS.read()); //Feed the GPS parser
  }

  if (gps.time.isUpdated()) //Check to see if new GPS info is available
  {
    displayInfo();
  }
}

//Display new GPS info
void displayInfo()
{
  //We have new GPS data to deal with!
  Serial.println();

  if (gps.time.isValid())
  {
    Serial.print(F("Date: "));
    Serial.print(gps.date.month());
    Serial.print(F("/"));
    Serial.print(gps.date.day());
    Serial.print(F("/"));
    Serial.print(gps.date.year());

    Serial.print((" Time: "));
    if (gps.time.hour() < 10) Serial.print(F("0"));
    Serial.print(gps.time.hour());
    Serial.print(F(":"));
    if (gps.time.minute() < 10) Serial.print(F("0"));
    Serial.print(gps.time.minute());
    Serial.print(F(":"));
    if (gps.time.second() < 10) Serial.print(F("0"));
    Serial.print(gps.time.second());

    Serial.println(); //Done printing time
  }
  else
  {
    Serial.println(F("Time not yet valid"));
  }

  if (gps.location.isValid())
  {
    Serial.print("Location: ");
    Serial.print(gps.location.lat(), 6);
    Serial.print(F(", "));
    Serial.print(gps.location.lng(), 6);
    Serial.println();
  }
  else
  {
    Serial.println(F("Location not yet valid"));
  }
}

The output of this code in the serial monitor should look similar to the below image. If the module does not yet have a fix, you will see Location not yet valid instead of a latitude and longitude reading.

long lat output

Resources and Going Further

You’ve finally figured out where you are! Now it’s time to take this GPS and incorporate it into your own project.

For a little more information, check the resources below:

For more GPS related fun, check out these other SparkFun tutorials.

Copernicus II Hookup Guide

A guide for how to get started with the Copernicus II GPS module.

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.

GPS Logger Shield Hookup Guide

How to assemble and hookup the SparkFun GPS Logger Shield. Never lose track of your Arduino again!

Building an Autonomous Vehicle: The Batmobile

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

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

AS726X NIR/VIS Spectral Sensor Hookup Guide

$
0
0

AS726X NIR/VIS Spectral Sensor Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The AS726X Spectral Sensors from AMS brings a field of study to consumers that was previously unavailable, spectroscopy! It’s now easier than ever to measure and characterize how different materials absorb and reflect different wavelengths of light. Don’t know what part of the spectrum you want to look at? You’re in luck! Sparkfun carries two different flavors of spectrometer. The AS7262 detects wavelengths in the visible range while the AS7263 detects wavelengths just below the visible range, in the Near Infrared (NIR) range.

SparkFun Spectral Sensor Breakout - AS7263 NIR (Qwiic)

SEN-14351
$24.95
SparkFun Spectral Sensor Breakout - AS7262 Visible (Qwiic)

SEN-14347
$24.95

Required Materials

To follow along with this hookup guide, you will need one of the following Qwiic shields to match your preference of microcontroller:

SparkFun Qwiic Shield for Arduino

DEV-14352
$5.95
Qwiic Shield for Raspberry Pi

SPX-14292
Qwiic Shield for ESP32

SPX-14203
Qwiic Shield for Photon

SPX-14202
$2.95

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

Qwiic Cable - 500mm

PRT-14429
$1.95
Qwiic Cable - 100mm

PRT-14427
$1.50
Qwiic Cable - 50mm

PRT-14426
$0.95
Qwiic Cable - 200mm

PRT-14428
$1.50

Suggested Reading

If you aren’t familiar with our new Qwiic system, we recommend reading here for an overview. We would also recommend taking a look at the following tutorials if you aren’t familiar with them.

How to Solder: Through-Hole Soldering

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

Serial Communication

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

Light

Light is a useful tool for the electrical engineer. Understanding how light relates to electronics is a fundamental skill for many projects.

I2C

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

Qwiic Shield for Arduino & Photon Hookup Guide

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

Hardware Overview

The AS7262 detects 450, 500, 550, 570, 600, and 650nm of light each with 40nm of full-width half-max detection. The AS7263 can detect 610, 680, 730, 760, 810, and 860nm of light each with 20nm of full-width half-max detection.

Communication

The AS726X is unique as it can communicate by both an I2C interface (through the onboard Qwiic connectors, or pins at the bottom of the board) and serial interface using AT commands (pins at the top of the board).

Serial Ports

While I2C is the default setting (The default I2C address is 0X49 for both AS7262 and AS7263) Serial communication can be enabled by removing solder from the jumpers labeled JP1, adding solder to the jumper labeled JP2 (on the back of the board), and using Sparkfun’s USB-to-Serial breakout to interface directly with the computer.

Solder Jumper 1

Solder Jumper 2

LED

The board also has multiple ways for you to illuminate the object that you are trying to measure for a more accurate spectroscopy reading. There is an onboard, 5700K LED that has been picked out specifically for this task. However, if you aren’t satisfied with the onboard LED, you can grab your own through hole incandescent. While you should find a bulb rated for 3.3V, a bulb rated for higher voltage, like 5V, will still work, but will not run as bright as it normally would with 5V. We’ve found that Mouser is a good place to look for these. If you are going to go that route and use your own bulb, be sure to disable the onboard LED by removing the solder from the JP4 jumper.

Solder Jumper 4

Hardware Assembly

The beauty of Sparkfun’s new Qwiic environment means that connecting the sensor could not be easier. Just plug one end of the Qwiic cable into the AS726X, the other into one of the Qwiic Shields, and stack the board on a development board. You’ll be ready to upload a sketch to start taking spectroscopy measurements. It seems too easy, but thats why we made it this way! Here’s an example using the RedBoard Programmed with Arduino.

alt text

Library Overview

Before we get started, we’ll need to download and install SparkFun’s AS726X Arduino library.

Download the SparkFun AS726X Library

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

Before we get started developing a sketch, let’s look at the available functions of the library.

  • void begin(TwoWire &wirePort, byte gain, byte measurementMode);— Initializes the sensor with user given values for the wire port, gain, and measurement
  • void takeMeasurements();— Sensor writes spectral measurements to memory locations.
  • void takeMeasurementsWithBulb();— Illuminates onboard bulb, calls takeMeasurements();, then turns off the onboard bulb.
  • void printMeasurements();— Fetches data from memory and outputs calibrated measurements using Serial.print();
  • void printUncalibratedMeasurements();— Fetches data from memory and outputs uncalibrated measurements using Serial.print();
  • byte getTemperature();— Fetches the temperature in degrees Celsius.
  • float getTemperatureF();— Fetches the temperature in degrees Fahrenheit.
  • void setMeasurementMode(byte mode);— Changes the measurement mode to 0, 1, 2, or 3
    • 0: Continuous reading of VBGY (Visible) / STUV (IR)
    • 1: Continuous reading of GYOR (Visible) / RTUX (IR)
    • 2: Continuous reading of all channels
    • 3: One-shot reading of all channels (power-on default)
  • boolean dataAvailable();— Returns true or false based on whether or not data is available to be read.
  • void enableIndicator();— Powers on the surface mounted blue indicator LED.
  • void disableIndicator();— Powers off the surface mounted blue indicator LED.
  • void setIndicatorCurrent(byte current);— Sets the current on the indicator LED. The default is current = 3, or 8 mA.
    • 0: 1 mA
    • 1: 2 mA
    • 2: 4 mA
    • 3: 8 mA
  • void enableBulb();— Powers on the surface mounted blue indicator LED.
  • void disableBulb();— Powers off the surface mounted blue indicator LED.
  • void setBulbCurrent(byte current);— Sets the current limit on the indicator LED and optional bulb (They are connected in parallel) The default is current = 0 or 12.5 mA.
    • 0: 12.5 mA
    • 1: 25 mA
    • 2: 50 mA
    • 3: 100 mA
  • void softReset();— Gives the sensor a 1 second reset.
  • void setGain(byte gain);— Pass in a 0, 1, 2 or 3 to change the gain.
    • 0: 1x
    • 1: 3.7x
    • 2: 16x
    • 3: 64x (power-on default)
  • void setIntegrationTime(byte integrationValue);— This sets the time over which samples are taken.
    • Takes a value between 0 and 255.
    • Integration time will be 2.8 ms * integrationValue.
  • void enableInterrupt();— Pulls the interrupt pin low. (Note: not yet implemented)
  • void disableInterrupt();— Pulls the interrupt pin high.
  • If you’d like access to just one channel, getting uncalibrated and calibrated spectral readings for the AS7262 (Visible) sensor can be accomplished with the following commands:
    • int getViolet();
    • int getBlue();
    • int getGreen();
    • int getYellow();
    • int getOrange();
    • int getRed();
    • float getCalibratedViolet();
    • float getCalibratedBlue();
    • float getCalibratedGreen();
    • float getCalibratedYellow();
    • float getCalibratedOrange();
    • float getCalibratedRed();
  • A similar set of functions is available for accessing individual channels on the AS7263 (Near Infrared) sensor.
    • int getR();
    • int getS();
    • int getT();
    • int getU();
    • int getV();
    • int getW();
    • float getCalibratedR();
    • float getCalibratedS();
    • float getCalibratedT();
    • float getCalibratedU();
    • float getCalibratedV();
    • float getCalibratedW();

Software

Example 1 — Basic Readings

The below sketch will get you up and running taking calibrated spectral readings on all 6 channels. Once this sketch is uploaded, open the serial monitor with a baud rate of 115200 to display the spectral data from the sensor.

language:c
#include "AS726X.h"
AS726X sensor;

void setup() {
  sensor.begin();
}

void loop() {
  sensor.takeMeasurements();
  sensor.printMeasurements();//Prints out all measurements (calibrated)
}

If we want, we can change the gain, measurement mode, and Wire that I2C uses by calling the begin() function with a few arguments. First, let’s look at what values we can assign to which characteristic.

Example 2 — Sensor Settings

The below example code will initialize our sensor with a gain of 16x, measurement mode of 0, and our regular I2C port (you can run the sensor on a different I2C port if you have the right hardware, a Teensy perhaps?).

language:c
#include "AS726X.h"
AS726X sensor;

byte GAIN = 2;
byte MEASUREMENT_MODE = 0;

void setup() {
    sensor.begin(Wire, GAIN, MEASUREMENT_MODE);
}

void loop() {
    sensor.takeMeasurements();
    sensor.printMeasurements();
}

Expected Output

Here is a picture of what to expect when bringing your AS726X online for either of the above sketches. (The program will print “AS7263 online!” instead if you have that sensor)

Example Output for AS7262

Resources and Going Further

Now that you’ve successfully got your AS726X 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:

New!

Qwiic Shield for Arduino & Photon Hookup Guide

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

CCS811/BME280 (Qwiic) Environmental Combo Breakout Hookup Guide

Sense various environmental conditions such as temperature, humidity, barometric pressure, eCO2 and tVOCs with the CCS811 and BME280 combo breakout board.
New!

SparkFun GPS Breakout - XA1110 (Qwiic) Hookup Guide

Figure out where in the world you are with the Qwiic SparkFun GPS Breakout - XA1110.

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


Night Sky Halloween Costume

$
0
0

Night Sky Halloween Costume a learn.sparkfun.com tutorial

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

Introduction

In this project, we’ll create a wearable costume using conductive thread to connect LilyPad LEDs to a LilyTiny, powered by LilyPad battery holders. Make your own by following the step-by-step instructions below.

Heads up! This project is designed for advanced sewers who have experience working with LilyPad products.

Design and build time: 3-5 Weeks

Final Project

Suggested Reading

If this is your first sewable electronics project, we recommend you read our LilyPad Basics tutorial.

Polarity

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

Series and Parallel Circuits

An introduction into series and parallel circuits.

Insulation Techniques for e-Textiles

Learn a few different ways to protect your conductive thread and LilyPad components in your next wearables project.

Planning a Wearable Electronics Project

Tips and tricks for brainstorming and creating a wearables project.

Powering LilyPad LED Projects

Learn how to calculate how many LEDs your LilyPad project can power and how long it will last.

LilyPad Basics: E-Sewing

Learn how to use conductive thread with LilyPad components.

Materials and Tools

Let’s go over all of the things you’ll need to sew your project together.

Items required for the Night Sky Costume:

You Will Also Need:

  • Cape Pattern (or any garment pattern of your liking)
  • Denim Fabric for Lining (yardage based on pattern requirements)
  • Galaxy Printed Fabric (yardage based on pattern requirements)
  • Sewing Machine
  • Navy or Black Thread
  • Hot Glue Gun w/ Extra Hot Glue Sticks
  • Scissors
  • Pins
  • Sewing Needles
  • Glow-in-the-Dark Puff Paint
  • Iron-on Adhesive
  • Clothing Iron
  • Colored Pencils in White, Red, and Yellow

Understanding Your Circuit

In this project, you will be sewing several of the same circuit. The cape that we have made includes 10 circuits. Let’s take a few minutes to understand what these look like and how they work before we get started.

Notice that the silver sew tabs on your LilyPad LEDs and battery holders are labeled either positive or negative. Many electronic components like these have polarity, meaning electric current can only flow through them in one direction.

LED Polarity

If hooked up incorrectly, they will not light up. Batteries are also polarized; they have a positive and negative side. Always check the labels on LilyPad pieces to make sure they are correctly oriented before sewing together a circuit.

LED Constellation

The following diagram illustrates the circuit you will be following in order to add twinkling LEDs to your garment. The number of constellations will determine how many LEDs you will need, as well as how many circuits you will be building. I will be including 18 - 21 LEDs per circuit, meaning 6-7 LEDs per I/O pin, as seen below.

circuit diagram

Notice how the LEDs have been grouped into three sets. No matter how many LEDs are included in your circuit, you will want to divide them into three groups as shown. The ‘-’ tab of every single LED in your circuit connects to the rest with conductive thread, as well as the ‘-’ tab on the LilyTiny and the ‘-’ tab for power.

The ‘+’ tabs will be treated differently. For each group of LEDs, you will connect all the ‘+’ tabs inside that group together with conductive thread, and then connect them to either pins 0, 1, or 3 on the LilyTiny. We are not using pin 2 in this project as the pre-programmed animation is not ideal for the design. This circuit configuration is an example of LEDs in a parallel circuit. For power, you will need two LilyPad battery holders per circuit also wired in parallel in order to boost the longevity of power for a long night out. Connect the ‘+’ tab of one of the battery holders to the ‘+’ tab of the LilyTiny, and then the ‘-’ tab of the same holder to the ‘-’ tab of the LilyTiny. Then connect the ‘-’ tab of the second holder to ‘-’ of the first holder, and ‘+’ on the second holder to ‘+’ on the first holder.

Notice that the battery holder is dulled out in our circuit diagram. That is because it will lie on the opposite side of the fabric to LEDs and LilyTiny. The LEDs and LilyTiny should lie face-up on the backside of the fabric, or the side that will not be against your body. The battery holders should be on the other side of the liner, which will be against your body and remains exposed, allowing for access to replace batteries and switch on/off.

Preparing your Garment

Before we start sewing the circuits, there are a few steps we need to take to prepare our garment.

STEP 1:

Iron your fabric. Before cutting out the pattern it is important to remove creases and wrinkles.

iron fabric

STEP 2:

Following the pattern instructions, cut the lining out of the denim fabric. All LilyPad components will be sewn onto the lining. We are using denim because it is a heavier fabric with a strong structure, making it ideal for adding sewable electronics. A flimsier fabric will be much more difficult to work with.

Cut the outer layer of the garment from the cotton night sky fabric and set aside for later.

cut fabric

STEP 3:

Sew the lining together according to the pattern instructions.

sew lining

STEP 4:

Download the design file provided.

Download Cape Constellation Design Here

Using it as a guide, draw the constellations on the side of the lining that will not be against your body with a white colored pencil.

Note: For this project, it is important to plan the approximate design of constellations on your garment. If you're making a cape garment, you can use our design file (provided in the link above) as a guide. You can also design your own constellation map for a garment of a different shape. You will use this document as a road map as you move forward in the project. No matter the style of your garment or the pattern of constellation, the steps to complete the project will be the same.

draw constellations

STEP 5:

Using a Sharpie, make a small dot on each star in the constellations you drew on the fabric. The white pencil tends to fade as you work, so these Sharpie dots will help you along the way.

sharpie

Arranging Your Circuit

Each dot you marked with the Sharpie represents where a single LilyPad LED will live. Almost 200 LEDs have been included on our cape. That translates to 10 circuits. Count the number of dots you drew and divide that by 18-21 to figure out how many circuits you will be breaking the constellations into. It is OK if some circuits have a few more LEDs than others.

Do not worry about LEDs in a given constellation being part of separate circuits, as the wiring will be hidden upon completion.

While working on this project, we found it to be best practice to work on one circuit at a time. The following steps describe how to make a single circuit. Repeat until all the LEDs on your garment are sewn into a circuit.

STEP 6:

Find a set of 18-21 dots on your garment and place LilyPad LEDs over them. Place the LilyTiny somewhat centered among the LEDs and two LilyPad coin cell battery holders upside down, as they will ultimately be placed on the opposite side of the garment.

Plot LEDs

STEP 7:

Using the circuit diagram provided above and a white pencil, start to draw out the circuit design on the fabric. Keep in mind that traces cannot cross each other as that will cause a short.

When you have figured out the general arrangement of LilyTiny to LEDs, that will allow you to sew the circuit together as expressed in the diagram and start to hot glue the electronic components down in place. Make sure that the ‘+’ and ‘-’ tabs are arranged properly. The battery holders will live on the opposite side of the garment, so do not glue them down just yet but rather keep them in place for reference by leaving them upside down.

Remember: Glue is great for keeping your components in place, but it can interfere with your circuit. Try to keep glue clear of sew tabs.

Plan Circuit

STEP 10:

Using a red colored pencil, draw lines from I/O pins 0, 1, and 3, past the ‘+’ tabs to the LEDs that they will connect to.

Note: Notice that pin 2 is not being used. This pin has a built in blink animation when connected to an LED. While a lovely animation, it doesn't suit the purpose of this project, so we are sticking to pins 0, 1, and 3.

Then use a yellow colored pencil (or any color other than red) to draw a ground line connecting all ‘-’ tabs according to the diagram.

Drawn Circuit

You will use these drawn lines as a guide on the sewing machine, so they should be straight and pass by all the sew tabs they will eventually be connected to.

Once the circuit has been drawn, flip the garment over and hot glue the two battery holders into place.

Stitching It Together

If you need help sewing with conductive thread, this tutorial covers the basics.

STEP 11:

Place a bobbin of conductive thread into your sewing machine, keeping the regular sewing thread on top. Sew along the lines drawn with the two colored pencils. These will act like rails on a breadboard as we move forward. Leave long tails of thread at the beginning and end of each sewn path.

Sewing Machine

STEP 12:

Connect the individual sew tabs on your components to the conductive thread paths that are acting as rails. For components near the end of the path, thread your needle with the conductive thread tail left at the end of the path and sew it around the tab. For the rest of the components, tie a new piece of conductive thread around the conductive thread on the rail, making sure it is secured tightly and that there is physical connection between the two threads. Then sew it around the sew tab of your component. In this step it is most important to make sure you are making strong connections. This usually means sewing over the tabs and knotting around the thread rails many times over. Also, do not forget to connect the battery holders on the opposite side of the fabric to the circuit!

The components should look like this when the tabs have been sewn:

LilyPad LED sewn

The opposite side of the fabric with the conductive thread rails should look like this:

Opposite Side of LilyPad LED

Repeat until all components in a single circuit are connected according to the diagram via conductive thread.

STEP 13:

Conductive thread can fray and easily cause an unnoticeable short, especially around the tails left from sewing and knotting around your connections. In order to protect these connections and avoid unnecessary shorts, lay your garment out with the battery holders up. Cut down the tails around your connections, and then immediately add a dab of hot glue to keep it both secure and insulated.

STEP 14:

Once all of the loose thread has been either snipped away and/or insulated, you can test the circuit. Add batteries to the holders and switch them on. If an LED is not working, now is your time to figure out why and fix it. Issues usually include loose connections or shorts, and you may need to re-sew a component or two. Make sure to build in plenty of time for de-bugging your circuits.

Test

Repeat steps 6–14 for the remainder of LEDs on your garment. We found that each circuit can take approximately 5–6 hours. So again, make sure you give yourself plenty of time to complete these steps.

Finishing the Garment

Once all your LEDs have been sewn into working circuits and you have tested/debugged them, you can finish sewing your garment together.

STEP 15:

Remove the conductive thread from your sewing machine and replace it with regular thread. Sew together your cotton fabric for the outer layer of the garment according to the pattern.

sew fabric

STEP 16:

Sew the lining (with your circuits) with the outer cotton fabric. The battery side of the lining and the outer side of the cotton should be touching while you do this. The LED/LilyTiny side and wrong side of the cotton should be facing out — kind of an inside out situation. Make sure you leave 6–12 inches of unsewn hem to bring the right side out later, as shown in step 19.

combine lining and fabric

STEP 17:

Lay out the garment flat, with the lining face up, and iron on double-sided, iron-on adhesive to the areas around your circuit.

iron on adhesive 1

STEP 18:

Peel the paper off the iron-on adhesive.

peel adhesive

STEP 19:

Using the area of unsewn hem, pull the right side out from the inside so that the LEDs and LilyTinys will now be inside, and the battery packs will be outside. Once completed, your garment should be right side out, and the raw edges of fabric hidden inside.

right side out

STEP 20:

Make sure the garment is fully right side out and begin to iron over the hems, making a clean, flat edge.

iron hems

STEP 21:

Iron around your circuits to activate the iron-on adhesive against the cotton. This will keep the two fabrics from separating, thus making sure your LEDs can be visible at all times.

iron adhesive

STEP 22:

Find the unsewn area on the hem. Fold the raw edges inward. Pin them together, and then sew along the edge.

finish hem

STEP 23:

Sew on any notions (i.e., buttons or clasps).

add notions

STEP 24:

Put batteries in all your battery holders and turn on all of the circuits. Lay the garment out with the cotton fabric side up. Using the constellation map, draw lines between stars using glow-in-the-dark puff paint.

connect constellations

STEP 25:

Leave it overnight to dry.

let dry

STEP 26:

Flip the cape over to the other side and cover all the conductive thread traces with the remainder of the puff paint. This will insulate all of your circuits and make the garment safer to wear. Let dry overnight.

Insulate Conductive Thread

STEP 27:

Once dry, turn on the switches for each battery holder to light up the LEDs.

Close Up

STEP 28:

Put on the cape and enjoy!

Final Project

Resources and Going Further

For more information related to the Night Sky Halloween Costume, check out the resources below:

These tutorials will guide you through concepts and advanced projects:

Planning a Wearable Electronics Project

Tips and tricks for brainstorming and creating a wearables project.

Choosing a LilyPad Arduino for Your Project

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

Marquee Party Bag

This tutorial provides everything you need to know to make your own Marquee Party Bag!

Fairy LED Bracelet

Light up the world - and your wrist - with this quick and easy rechargeable firefly LED bracelet.

LED PomPom Headbands

Follow this tutorial to make your own light up PomPom headband! Try the beginner version if you are new to electronics or the advanced version if you have some more experience!

Twinkle Zodiac Constellation

Create a quick and easy piece of e-textile art based on a Zodiac sign using a LilyTiny, LilyPad LEDs, battery holder, conductive thread, and coin cell battery.

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

Getting Started with LilyPad

$
0
0

Getting Started with LilyPad a learn.sparkfun.com tutorial

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

Introduction

The LilyPad system is a set of sewable electronic pieces designed to help you build soft, sewable, interactive e-textile (electronic textile) projects. Using LilyPad pieces is a great way to experiment with electronics through the lens of crafting or fiber arts. Each LilyPad piece has large conductive sew tabs for easy sewing and a rounded shape so as not to snag fabric or cut thread. In this guide, we will walk you through features of the LilyPad system and some general concepts.

The LilyPad system was designed by Leah Buechley while pursuing her Ph.D. in computer science at the University of Colorado Boulder. The commercial version of the kit, which launched in 2007, was collaboratively designed by Leah and SparkFun Electronics.

Leah

LilyPad Creator Leah Buechley

LilyPad Basics: Parts of a Circuit

Every LilyPad circuit, no matter how complex, has three basic parts: (1) a power source, (2) conductive paths (conductive thread stitching) between electronic components, and (3) the LilyPad pieces that are connected together to light up, make sound or perform other behaviors (the “function” of your project).

Anatomy of LilyPad Circuit

1. Choosing a Power Source

All LilyPad projects need a power source — most use either a 3V CR2032 coin cell battery or a 3.7V lithium polymer rechargeable battery. Which power solution you need will depend on a few factors: the size of your project, the type of LilyPad Arduino you choose, and whether you would rather replace or recharge a battery. The LilyPad line includes a stand-alone sewable coin cell holder or built-in battery connections for 3V coin cell batteries or 3.7V lithium polymer batteries (available on select LilyPad boards).

LilyPad Coin Cell Battery Holder - Switched - 20mm

DEV-13883
$1.95
3
LilyPad Simple Power

DEV-11893
$9.95

2. Conductive Thread Connections

LilyPad boards are made to be sewn together using conductive thread, a special thread made with stainless steel fibers. Used instead of copper wiring to connect LilyPad pieces together, conductive thread provides a soft and flexible connection between components that is incorporated directly into fabric. Each LilyPad piece has a large sew tab to accommodate a variety of needle sizes for attaching conductive thread.

Conductive Thread - 60g (Stainless Steel)

DEV-11791
$41.95
9
Conductive Thread Bobbin - 30ft (Stainless Steel)

DEV-10867
$2.95
3
Conductive Thread Bobbin - 12m (Smooth, Stainless Steel)

DEV-13814
$3.95

Learn more about sewing with conductive thread in the Lilypad Basics: E-Sewing tutorial.

LilyPad Basics: E-Sewing

Learn how to use conductive thread with LilyPad components.

3. LilyPad Pieces

The LilyPad line includes a variety of sewable components for creative projects. Choose from LEDs in a variety of colors, buttons, switches, sensors, buzzers, and controller (Arduino) boards. Check out all of the individual LilyPad pieces here. Which pieces you choose to build into your project will depend on your individual vision and goals. Read on for more about the different types of LilyPad projects you can make.

Lilypad Pieces

View the full line of LilyPad boards here.

Types of LilyPad Projects

LilyPad projects can be divided into three main categories: (1) e-sewing, (2) pre-programmed, and (3) programmed with Arduino. Read the next few sections for more details on each project type.

Sewed LilyPad ProtoSnap Plus

E-Sewing

A great way to try out sewing with conductive thread without programming is to create e-sewing projects.

Preprogrammed Circuits

LilyPad LEDs and a LilyPad Coin Cell Battery Holder will light up a project, and the possibilities can be expanded to include simple interactive elements like buttons or switches, which you can purchase or make yourself. We recommend e-sewing projects if you are new to sewing or want to create a quick and easy light-up craft.

Here are some e-sewing projects to try:

Light-Up Plush

Craft a light-up plush with LilyPad LEDs controlled by pressing a button and sliding a switch in the creature's hands.

Glowing Pin

Create a quick and easy piece of e-textile art using a LilyPad LED, battery holder, conductive thread, and coin cell battery.

Illuminated Mask

Use LilyPad LEDs, a switched battery holder, and coin cell battery to make a fun light up mask for your next costume party.

Suggested Materials:

  • Needle
  • Scissors
  • Felt or Fabric
  • Hot Glue and Glue Gun
  • Conductive Thread
  • Coin Cell Battery
  • LilyPad Coin Cell Battery Holder
  • LilyPad LEDs
  • Optional: LilyPad Button Board, LilyPad Slide Switch, metal snaps, conductive thread

Pre-Programmed Circuits

If you are ready to try some flashier effects with LEDs or explore how programmed projects work without writing the code yourself, pre-programmed LilyPad boards are a great option.

Pre-Programmed Circuits

The LilyPad line includes four products that are project-ready: the LilyTiny, LilyTwinkle, LilyTwinkle ProtoSnap and LilyMini ProtoSnap— just sew and glow!

LilyPad LilyMini ProtoSnap

DEV-14063
$14.95
2
LilyTiny

DEV-10899
$4.95
11
LilyTwinkle

DEV-11364
$4.95
6
LilyTwinkle ProtoSnap

DEV-11590
$14.95
1

The LilyTiny and LilyTwinkle are small LilyPad boards with pre-loaded programs on them. Just hook them up to a LilyPad Coin Cell Battery Holder and some LilyPad LEDs to see different light patterns display on the LEDs. Both the LilyTiny and LilyTwinkle use the same circuit board and controller, but differ in the code they ship with.

LilyTiny

The LilyTiny has a different light pattern programmed for each numbered sew tab. Tab 0 controls a “breathing” fade, tab 1 flashes a heartbeat pattern, tab 2 creates an on/off blink, and tab 3 produces a random fading effect (twinkle). The LilyTiny is a great way to try out different light patterns in a project.

LilyTiny

DEV-10899
$4.95
11

Try checking out a demo of the LilyTiny below.

See the LilyTiny in Action

Here are some LilyTiny projects to try:

LDK Experiment 6: Microcontroller Circuits

Learn how to build a simple microcontroller circuit using the pre-programmed LilyTiny Board

LilyTiny Plush Monster

Craft a stuffed monster while exploring the LilyTiny preprogrammed microcontroller. This is a project based on the Plush Monster Activity created at MIT's High-Low Tech Lab by Emily Lovell, Jie Qi, and Natalie Freed.

Twinkle Zodiac Constellation

Create a quick and easy piece of e-textile art based on a Zodiac sign using a LilyTiny, LilyPad LEDs, battery holder, conductive thread, and coin cell battery.

Suggested Materials:

  • Needle
  • Scissors
  • Felt or Fabric
  • Hot Glue and Glue Gun
  • Conductive Thread
  • LilyTiny
  • LilyPad Coin Cell Battery Holder
  • Coin Cell Battery
  • LilyPad LEDs

LilyTwinkle

If you are looking for an overall sparkling effect on a project, the LilyTwinkle has all four numbered tabs programmed with a random fading effect, mimicking twinkling stars or fireflies. The LilyTwinkle also comes in a LilyTwinkle ProtoSnap, a pre-wired board containing everything you need to test and sew a LilyTwinkle project.

LilyTwinkle

DEV-11364
$4.95
6

Try checking out a demo of the LilyTwinkle below.

See the LilyTwinkle in Action

Here are some LilyTwinkle projects to try:

Soft Circuits: LED Feelings Pizza

Here we will learn how to say how you feel with pizza. Electric pizza.

Firefly Jar Assembly Guide

Make a soft circuit firefly jar with conductive thread, LEDs, and the LilyTwinkle!

Twinkling Trick or Treat Bag

Make a light up goodie bag with conductive thread, LEDs, and the LilyTwinkle!

Suggested Materials:

  • Needle
  • Scissors
  • Felt or Fabric
  • Hot Glue and Glue Gun
  • Conductive Thread
  • LilyTwinkle or LilyTwinkle ProtoSnap
  • LilyPad Coin Cell Battery Holder (included if using ProtoSnap)
  • Coin Cell Battery (included if using ProtoSnap)
  • LilyPad LEDs (included if using ProtoSnap)

LilyMini ProtoSnap

LilyPad LilyMini ProtoSnap

DEV-14063
$14.95
2

For something more interactive, try the LilyMini ProtoSnap — a pre-wired, pre-programmed LilyPad board with a LilyPad Light Sensor and LilyPad Button attached to it. The LilyMini includes a built-in coin cell battery holder to eliminate additional sewing. Test out the circuit with the pre-wired connections, then snap apart and sew into a project. The LilyMini ProtoSnap has three pre-programmed modes (indicated by a built-in RGB LED): white (all LEDs on), magenta (LEDs fade in and out in a “breathing” pattern with speed affected by covering the light sensor), and cyan (when the light sensor is covered, LEDs twinkle).

See the LilyMini ProtoSnap in Action

Here are some LilyMini projects to try:

LilyMini ProtoSnap Hookup Guide

Explore the LilyPad LilyMini ProtoSnap and learn how to use it.

Night-Light Pennant with LilyMini ProtoSnap

Use the pre-programmed LilyMini ProtoSnap to make an interactive pennant that reacts to ambient light levels.

Suggested Materials:

  • Needle
  • Scissors
  • Felt or fabric
  • Hot Glue and Glue Gun
  • Conductive Thread
  • LilyMini ProtoSnap (includes Coin Cell Battery)

Programmed with Arduino

Have an idea for a custom project and ready to program? The LilyPad line has a variety of LilyPad Arduino microcontrollers to choose from, all compatible with free Arduino software.

LilyPad ProtoSnap Plus connected to computer

The LilyPad ProtoSnap Plus is a great place to start prototyping a project — it includes seven LilyPad boards pre-wired to a LilyPad microcontroller for experimenting with code before you sew.

LilyPad ProtoSnap Plus

DEV-14346
$39.95

The LilyPad ecosystem also includes four stand-alone LilyPad controllers, the LilyPad Arduino USB, LilyPad Arduino 328 Main Board, LilyPad Arduino Simple Board, and LilyPad Arduino SimpleSnap. These controller boards can be connected to most of the LilyPad boards for light-up, sound-making, or sensing projects.

LilyPad Arduino USB - ATmega32U4 Board

DEV-12049
$24.95
7
LilyPad Arduino 328 Main Board

DEV-13342
$15.95
1
LilyPad Arduino Simple Board

DEV-10274
$19.95
LilyPad Arduino SimpleSnap

DEV-10941
$29.95
1

Check out Choosing a LilyPad Arduino for Your Project for a side-by-side comparison of each board’s features.

Choosing a LilyPad Arduino for Your Project

October 27, 2015

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

Resources and Going Further

Start with a Kit

The LilyPad Sewable Electronics Kit — Includes everything you need to make 4 e-sewing projects: glowing pin, illuminated mask, light-up plush, and night-light pennant (with LilyMini). Craft supplies also included.

LilyPad Sewable Electronics Kit

KIT-13927
$99.95
4

Plan Your Project

Check out Planning a Wearable Electronics Project for tips on brainstorming and prototyping, as well as technical considerations.

Planning a Wearable Electronics Project

August 13, 2015

Tips and tricks for brainstorming and creating a wearables project.

Get Inspired

Take a look at our LilyPad Project Gallery to browse projects made with LilyPad or read some of SparkFun’s blog posts on LilyPad and wearables.

Start LilyPad Project


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

Lumenati Alien Garden

$
0
0

Lumenati Alien Garden a learn.sparkfun.com tutorial

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

Introduction

I recently visited one of Disney World’s newest parks: Pandora - The World of Avatar. Instead of souvenirs, I brought home a hankering for my own alien garden. This tutorial will show how to use Lumenati LED boards to light up a variety of succulent plants in your own alien garden.

Alien Garden

Required Materials

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

Suggested Reading

If you have not worked with the Lumenati boards before, we suggest looking at the following guide:

New!

Lumenati Hookup Guide

October 12, 2017

Lumenati is our line of APA102c-based addressable LED boards. We'll show you how to bring the sparkle to your projects!

Hardware Hookup

Before you can begin building the garden, you’ll want to wire and solder all the boards. Measure how far apart you want all the plants to be and cut wire lengths accordingly.

Start by connecting your first Lumenati board to the SparkFun Redboard or whichever microcontroller you’ve chosen. Wire the first board as shown in the table below. There are two sets of 5V and GND pins; make sure that you leave one set open to make the next step easy!

RedBoardFirst Lumenati Board
GNDGND
5V5V
13CI
11DI

Next, connect your first and second Lumenati boards. You want to connect CO on the first board to CI on the second, and DO to DI. Use the second set of 5V and GND pins on the first board to connect to the second board. Once again, leave one set of 5V and GND open on the newest board!

First Lumenati BoardSecond Lumenati Board
GNDGND
5V5V
COCI
DODI

Repeat this process from the second board to the third. If you have more plants, you can continue adding boards this way. Ensure you have a power supply that can supply enough current if you decide to add more boards!

Second Lumenati BoardThird Lumenati Board
GNDGND
5V5V
COCI
DODI

Once the wiring is complete, it’s a good idea to upload code to the RedBoard and test everything out before installing into the garden. See the next section for the code.

testing

Upload the Code

Plug the RedBoard or microcontroller of choice into your computer. Open the Arduino IDE, copy the sketch below, and upload the code to the board. Please note that this example uses the FastLED library. You will need to have it installed for this sketch to work. You can find the latest version here. Alternatively, you can search for the ‘fastled’ in the Library Manger and install it that way.

language:c
#include "FastLED.h"

//Number of LEDs; edit this if you've added more boards or changed the sizes
#define NUM_LEDS 16

//Define our clock and data lines
#define DATA_PIN 11
#define CLOCK_PIN 13

//Create the LED array
CRGB leds[NUM_LEDS];

void setup() {

      //Tell FastLED what we're using. Note "BGR" where you might normally find "RGB".
      //This is just to rearrange the order to make all the colors work right.
      FastLED.addLeds<APA102, DATA_PIN, CLOCK_PIN, BGR>(leds, NUM_LEDS);


      //Set colors for all of the LEDs; Fast LED has a HUGE selection of colors, so
      //browse through them and find the best matches for your plants.
      leds[0] = CRGB::DeepPink;          //  First Flower
      leds[1] = CRGB::Teal;              //
      leds[2] = CRGB::DeepPink;          //
      leds[3] = CRGB::Teal;              //
      leds[4] = CRGB::Purple;            // Second Flower
      leds[5] = CRGB::Green;             //
      leds[6] = CRGB::Purple;            //
      leds[7] = CRGB::DarkGreen;         //
      leds[8] = CRGB::Blue;              // Third Flower
      leds[9] = CRGB::Green;             //
      leds[10] = CRGB::Purple;           //
      leds[11] = CRGB::DarkGreen;        //
      leds[12] = CRGB::Purple;           //
      leds[13] = CRGB::Green;            //
      leds[14] = CRGB::Purple;           //
      leds[15] = CRGB::DarkGreen;        //



      //Set global brightness
      FastLED.setBrightness(50);
      FastLED.show();

}

void loop() {

  // set the length for delays and initial brightness for each flower
  uint8_t x;
  uint16_t wait = 50;
  uint8_t flower1 = 75;
  uint8_t flower2 = 255;
  uint8_t flower3 = 75;


    //To bring them to life, I'm dimming and brightening the LEDs to make them "pulse"
    //a little bit. Flower1 will get progressively brighter, while Flower2 gets dimmer.
    while (flower1 < 255)
      {
        flower1++;
        flower2--;
        leds[0].setHSV( 192, 255 , flower1 );
        leds[1].setHSV( 96, 255 , flower1 );
        leds[2].setHSV( 192, 255 , flower1 );
        leds[3].setHSV( 96, 255 , flower1 );
        leds[4].setHSV( 192, 255 , flower2 );
        leds[5].setHSV( 96, 255 , flower2 );
        leds[6].setHSV( 192, 255 , flower2 );
        leds[7].setHSV( 96, 255 , flower2 );
        FastLED.show();
        delay (wait);
      }


    //Once flower1 is at max brightness, they'll reverse, and flower1 will grow dimmer
    //while flower2 grows brighter.
     while (flower1 > 75)
      {
        flower1--;
        flower2++;
        leds[0].setHSV( 192, 255 , flower1 );
        leds[1].setHSV( 96, 255 , flower1 );
        leds[2].setHSV( 192, 255 , flower1 );
        leds[3].setHSV( 96, 255 , flower1 );
        leds[4].setHSV( 192, 255 , flower2 );
        leds[5].setHSV( 96, 255 , flower2 );
        leds[6].setHSV( 192, 255 , flower2 );
        leds[7].setHSV( 96, 255 , flower2 );
        FastLED.show();
        delay (wait);
      }


  FastLED.show();
  delay(wait);

}

Building the Garden

Now to integrate the lights into your plants! I went through a couple of types of silk plants, and even tried making a few by hand out of Polymorph, before deciding that plastic succulents diffused the lights best. Start with an array of small fake plants. Mine are mounted on mossy rocks, but small pots will work well and offer a place to hide the electronics. I’ll be tucking mine into some rocks in a cubby built into my home.

plants

I also picked up some mossy tiles, more mossy rocks, and some real stones. The extra materials will help you to hide the wires.

moss

Whether your plants are in pots, rocks, or just bare, they should be on a pick. Give them a tug to pull them out of what they’ve been mounted on, revealing the pick.

alt text

Note that pick sizes can vary dramatically.

alt text

Slide each pick through one of the Lumenati board standoff holes, then back into the mounting. Given the natural variations in pick size, it may be necessary to use a hobby knife to shave it down to fit. If necessary, add a dot of glue to hold each pick in place.

alt text

Repeat for both Lumenati 4-packs.

alt text

And, for the Lumenati 8pack.

alt text

When all of your plants have the LEDs implanted, you’re ready to place them!

alt text

I’m using a small grotto that’s been in my house since I moved in, just waiting for some decorations. There is lots of control over the light level in here, so it’s a great spot! This will also work well in a flower pot, planter, or pretty much anywhere you might want plants.

Here’s my grotto before anything goes in:

alt text

First I installed a fountain and the larger moss tiles to fill some space and add some movement. I also added a power strip with USB outlets to make sure there’s somewhere to plug in everything.

alt text

I added a couple more moss blocks and a potted fern to the back corner, to help cover the outlet, then tucked my succulents into place around the fountain.

alt text

Using the heavier real stones to hold the wires down and out of the way, fill the remaining space with the rest of your plants and materials. Cover any remaining wires with styrofoam moss rocks.

alt text

Turn off the overhead lights for a more dramatic effect:

alt text

Closeups of my alien flowers:


Resources and Going Further

Need some inspiration for your next LED project? Check out these other great SparkFun tutorials.

RGB Panel Hookup Guide

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

Boss Alarm

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

Cherry MX Switch Breakout Hookup Guide

How to assemble and use the Cherry MX Switch Breakout, allowing you to turn a matrix of mechanical switches into a full-size keyboard!

Spectacle Light Board Hookup Guide

All the information you need to use the Spectacle Light Board in one place.

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

Using Flask to Send Data to a Raspberry Pi

$
0
0

Using Flask to Send Data to a Raspberry Pi a learn.sparkfun.com tutorial

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

Introduction

In this tutorial, we’ll show you how to send data from cheap WiFi nodes to a Raspberry Pi over an internal WiFi network. It relies on the Flask framework for Python, which is a relatively simple-to-use method of creating a web application that can execute Python scripts.

Glamour shot of two boards from tutorial

We’ll use a Raspberry Pi 3 and SparkFun ESP8266 Thing to demonstrate. We’re going to send a very simple signal from the Thing board to the RasPi - just a signal to turn an attached LED on or off. Hopefully, it’ll be obvious from the example how to send more complex signals and run more complex scripts upon receipt.

Suggested Reading

Before you tackle this project, there are a few other tutorials you may want to check out.

How to Solder: Through-Hole Soldering

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

ESP8266 Thing Hookup Guide

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

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.

Required Materials

You’ll need the items on this wishlist to complete this tutorial. Substitutions can be made; a Raspberry Pi Zero W can be substituted for the Pi 3, for instance, and individual components can be sourced instead of the full starter kit.

Required Tools

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

Soldering Iron - 30W (US, 110V)

TOL-09507
$9.95
6
Solder Lead Free - 15-gram Tube

TOL-09163
$3.50
2

Hardware Hookup

You’ll need to do some basic breadboarding to prepare for this tutorial. Don’t worry, we’ll walk you through all of it.

Raspberry Pi Connections

The connections for the Pi are simple: we’re just connecting one LED to GPIO pin 2. See the Fritzing diagram below for information on how to do that.

Raspberry Pi connection diagram

ESP8266 Thing Connections

Hook up two of the buttons as seen in the Fritzing diagram below.

Thing connection diagram

One of the buttons will turn the remote LED on, the other will turn it off. We’re going to assume that you’re capable of soldering the headers onto the ESP8266 Thing board yourself, but if you need some help, check out our soldering tutorial.

This is also where you’ll use the long, centered breakaway headers. A six-pin group of them inserted into the breadboard aligned with the programming pins on the Thing will give you a place to plug in the FTDI board.

Raspberry Pi Software

Let’s get down to business and program the Raspberry Pi to serve a web app that we can use for data connection. This tutorial assumes that you have some familiarity with Linux and Python to follow along.

Installing Flask

The first step is adding support for Flask to the RasPi. Python is already installed and support for using GPIO through Python, so we don’t need to worry about that.

All of these commands can be run either on a serial terminal opened on the Raspberry Pi directly with the Pi hooked up to a monitor, or remotely with a Pi via an SSH connection. However, we’re not going to get into how to set up and run a Pi without a monitor.

The first thing you need to do is install the Flask framework. There are a lot of additional packages that can be used with Flask, but we only need the basic package for this tutorial.

sudo pip install flask

Next, we’re going to create the directory within which the app will run. These commands will create the directory and ensure that you’re working inside that directory.

mkdir FlaskTutorial
cd FlaskTutorial

The next step is to create a blank Python file in the directory called “app.py”. This is the file that we’re going to put our code into. Open that file in your favorite text editor (the Pi has vi, nano, and a textpad).

touch app.py

Then put the following code into it.

language:python
#!/usr/bin/python

from flask import Flask
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)  # Sets up the RPi lib to use the Broadcom pin mappings
                        #  for the pin names. This corresponds to the pin names
                        #  given in most documentation of the Pi header
GPIO.setwarnings(False) # Turn off warnings that may crop up if you have the
                        #  GPIO pins exported for use via command line
GPIO.setup(2, GPIO.OUT) # Set GPIO2 as an output

app = Flask(__name__)   # Create an instance of flask called "app"

@app.route("/")         # This is our default handler, if no path is given
def index():
    return "hello"

# The magic happens here. When some http request comes in with a path of
#  gpio/x/y, the Flask app will attempt to parse that as x=pin and y=level.
#  Note that there is no error handling here! Failure to properly specify the
#  route will result in a 404 error.
@app.route('/gpio/<string:id>/<string:level>')
def setPinLevel(id, level):
    GPIO.output(int(id), int(level))
    return "OK"

# If we're running this script directly, this portion executes. The Flask
#  instance runs with the given parameters. Note that the "host=0.0.0.0" part
#  is essential to telling the system that we want the app visible to the
#  outside world.
if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000)

There are comments in the code to cover most questions but I want to highlight three things:

  • First, there’s no error checking here. The message is passed as the path requested via an HTTP request, and that request can contain just about anything. A request of the format GET /gpio/2/0 will set the pin low, for instance. However, GET /bats/are/bugs is equally valid, it just won’t do anything and the app will return a “404 error.”

  • Second, the parameter host='0.0.0.0' is required to let the app know that you want the application visible to external clients. If you omit this, you’ll still be able to test the app by visiting localhost:5000 in a web browser on the Pi, it just won’t be visible externally.

  • Third, the most commonly used port number is 5000, but you can use any port you want.

ESP8266 Thing Firmware

Now we’ll need to program the Thing. This portion assumes that you’ve followed the SparkFun ESP8266 Thing hookup guide and can program the ESP8266.

Example Code

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

Here’s the firmware that I’ve written to send the proper page requests to the Raspberry Pi.

language:cpp
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>

ESP8266WiFiMulti WiFiMulti;

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

  // ESP8266 takes a few moments to boot, so we give it a few seconds
  for(uint8_t t = 4; t > 0; t--)
  {
    Serial.printf("[SETUP] WAIT %d...\n", t);
    Serial.flush();
    delay(1000);
  }

  // Add the WiFi access point information
  WiFiMulti.addAP("SSID", "PASSWORD");

  // Set our buttons pins to inputs with pullup resistors enabled
  pinMode(12, INPUT_PULLUP);
  pinMode(13, INPUT_PULLUP);

}

void loop()
{
  // wait for WiFi connection
  if((WiFiMulti.run() == WL_CONNECTED))
  {
    // Check if button 12 is pressed...
    if (digitalRead(12) == LOW)
    {
      //...and if so, issue a GET request of the format
      //  gpio/x/y, where x is the desired pin and y is the
      //  desired level to set the pin to. Currently the
      //  Flask app only supports pin 2.
      HTTPClient http;
      // Be sure to change this IP address and port number
      //  to match yours!!!
      http.begin("http://10.8.253.193:5000/gpio/2/0");
      int httpCode = http.GET();
      http.end();
    }
    // Repeat the process for pin 13.
    if (digitalRead(13) == LOW)
    {
      HTTPClient http;
      // Be sure to change this IP address and port number
      //  to match yours!!!
      http.begin("http://10.8.253.193:5000/gpio/2/1");
      int httpCode = http.GET();
      http.end();
    }
  }
  else
  {
    Serial.println("No WiFi");
  }
}

Hopefully, the code and comments make it clear what’s going on. Two quick reminders:

  • First, the IP address and port number in the functions http.begin() are mine from development. You’ll have to change them to match the IP address and port number used on your Raspberry Pi.

  • Second, don’t forget to put in your SSID and PASSWORD for your wireless network.

Try It Out!

By now, you ought to have everything ready to go. You’ll need to start the script on the Raspberry Pi. Enter these commands in the subdirectory where you created the ‘app.py’ file:

chmod a+x app.py
./app.py

You should see a message, then, like the one below.

Output of the script run on the Raspberry Pi

As you can see, I pressed the buttons a couple of times to show you what it looks like when a client makes an HTTP request. Flask reports the IP address of the client, the date and time stamp of the request, the contents of the request, and the result of the request (in this case, 200, or “success”). This is a useful tool to make sure that your requests are actually making it through to the Flask server and not disappearing into the ether somewhere.

Resources and Going Further

Now that you’ve successfully got Flask framework up and running between a Raspberry Pi and ESP8266, it’s time to incorporate it into your own project!

For more information, check out the resources below:

  • Flask Framework - Official Flask website.
  • Simple Flask Tutorial - This basic Flask tutorial will walk you through taking Flask a little bit farther than we have here.
  • Complex Flask Tutorial - This more advanced tutorial walks you through far more complex tasks with Flask, leading up to creating a Twitter clone that you can host yourself!

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

SparkFun Inventor's Kit Experiment Guide - v4.0

$
0
0

SparkFun Inventor's Kit Experiment Guide - v4.0 a learn.sparkfun.com tutorial

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

Introduction

The SparkFun Inventor’s Kit (SIK) is your map for navigating the waters of beginning embedded electronics. This guide contains all the information you will need to build five projects encompassing the 16 circuits of the SIK for the SparkFun RedBoard. At the center of this manual is one core philosophy: that anyone can (and should) play around with electronics. When you’re done with this guide, you will have built five great projects and acquired the know-how to create countless more. Now enough talk — let’s start something!

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

SIK V4 Guide PDF

SparkFun Inventor’s Kit - v4.0

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 - v4.0

KIT-14265
$99.95
SparkFun Inventor's Kit for Arduino Uno - v4.0

KIT-14418
$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.

The SparkFun Inventor’s Kit V4.0 is licensed under the Creative Commons Attribution Share-Alike 4.0 International License.

Baseplate Assembly

Before you can build circuits, you’ll want to fist assemble the breadboard baseplate. This apparatus makes circuit building easier by keeping the breadboard and the RedBoard microcontroller connected together without the worry of disconnecting or damaging your circuit. The larger the circuit, the more wires needed to build it. The more wires there are, the easier it is for one of those wires to come undone.

To begin, grab all the parts: the RedBoard, the breadbaord, the included screwdriver, the baseplate and the two baseplate screws.

Baseplate1

If the screwdriver end is a flathead screwdriver, pull the shaft out, rotate it around to the Phillips head screwdriver side, and reinsert the shaft.

Next, peel the adhesive backing off the breadboard.

Baseplate2

Carefully align the breadboard over its spot on the baseplate. The text on the breadboard should face the same direction as the text on the baseplate. Firmly press the breadboard to the baseplate to adhere it.

Baseplate3

Align the RedBoard with its spot on the baseplate. The text on it should face the same direction as the text on the breadboard and the baseplate. Grab on of the two included screws, and firmly screw it into one of the four stand-off holes found on the RedBoard. The plastic holes are not threaded, so you will need to apply pressure as you twist the screwdriver.

Baseplate4

Screw the second screw in the stand-off hole diagonally across from the first. With that, your baseplate is now assembled.

Baseplate5

Arduino Uno Baseplate Assembly

Newer versions of the Arduino Uno come with a clear, plastic baseplate of their own. It will need to be removed before the Uno can be attached to the breadboard baseplate. To remove it, pull it from the Uno.

Uno

You may now attach the Uno to the baseplate as shown in the instructions above.

Uno on baseplate

Please Note: The Arduino Uno and the SparkFun RedBoard are pin-for-pin identical. Though the circuits in this guide show the SparkFun RedBoard, the Arduino Uno can be interchanged and used with all the same circuit diagrams and hookup tables. All the pin names and locations are the same on both development platforms.

The SparkFun RedBoard

The SparkFun RedBoard is your development platform. At its roots, the RedBoard is essentially a small, portable computer, also known as a microcontroller. It is capable of taking inputs (such as the push of a button or a reading from a light sensor) and interpreting that information to control various outputs (like blinking an LED light or spinning an electric motor). That’s where the term “physical computing” comes in; this board is capable of taking the world of electronics and relating it to the physical world in a real and tangible way.

The SparkFun RedBoard is one of a multitude of development boards based on the ATmega328 microprocessor. It has 14 digital input/output pins (six of which can be PWM outputs), six analog inputs, a 16MHz crystal oscillator, a USB connection, a power jack, and a reset button. You’ll learn more about each of the RedBoard’s features as you progress through this guide.

Check out the guide below to learn more about the SparkFun RedBoard.

RedBoard Hookup Guide

January 7, 2014

How to get your RedBoard up-and-blinking!

Understanding Breadboards

A breadboard is a circuit-building platform that allows you to connect multiple components without using a soldering iron.

If you have never seen or used a breadboard before, it is highly recommended you read the following guide that explains the breadboards anatomy and how to use one.

How to Use a Breadboard

May 14, 2013

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.

Install the Arduino IDE and SIK 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.

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 V4.0 Code

You can also download the code from GitHub.

Place the SIK-Guide-Code folder in the Arduino IDE examples directory:

  • Windows: drag the SIK-Guide-Code folder into C:\program files\Arduino-x\examples
  • MacOS: Right-click on the Arduino IDE app and click “Show Package Contents…”. Drag the SIK-Guide-Code folder into Contents/Resources/Java
  • Linux: see http://www.arduino.cc/playground/Learning/Linux

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.


USB Serial Driver Quick Install

August 31, 2017

How to install USB serial drivers on Windows, MacOS , and Linux.

Select your Board: Arduino/Genuino 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/Genuino 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. This will be the same serial port seen when installing FTDI drivers.

With that, you’re now ready to begin building your first circuit!

Project 1: Light

Welcome to your first SparkFun Inventor’s Kit project. Each project is broken up into several circuits, each designed to help you learn about new technologies and concepts. The knowledge gained from each circuit will play a part in building each project. This first project will set the foundation for the rest of the projects in the guide and will aid in helping you understand the basic fundamentals of circuit building and electricity!

In Project 1, you will learn about light-emitting diodes (LEDs), resistors, inputs and sensors — using all of those technologies to build and program your own multicolored night-light! The night-light uses a sensor to turn on an RGB (Red, Green, Blue) LED when it gets dark, and you will be able to change the color using an input knob.

Project 1

New Components Introduced in This Project

Each of the components listed below will be described in more detail as you progress through each project.

  • LEDs
  • Resistors
  • Potentiometers
  • Photoresistors

New Concepts Introduced in This Project

Each of the concepts listed below will be described in more detail as you progress through each project.

  • Polarity
  • Ohm’s Law
  • Digital Output
  • Analog vs. Digital
  • Analog Input
  • Analog to Digital Conversion
  • Voltage Divider
  • Pulse-width Modulation
  • Functions

You Will Learn

  • How to upload a program to your RedBoard or Arduino Uno
  • Circuit building basics
  • How to control LEDs with digital outputs
  • How to read sensors you analog inputs

Light-Emitting Diodes, or LEDs (pronounced el-ee-dees), are small, powerful lights that are used in many different applications. You can find LEDs in just about any source of light nowadays, from the bulbs lighting your home to the tiny status lights flashing on your home electronics. Blinking an LED is the classic starting point for learning how to program embedded electronics. It’s the “Hello, World!” of microcontrollers.

In this circuit, you’ll write code that makes an LED flash on and off. This will teach you how to build a circuit, write a short program and upload that program to your RedBoard.

Circuit 1A Hero Shot

Parts Needed

Grab the following quantities of each part listed to build this circuit:

parts


New Components and Concepts: Each circuit will introduce new components or parts that will be used in the circuit. Each circuit will also introduce a few new concepts that will help you understand what your circuit and code is doing and why.

New Components

LED (Light Emitting Diode)

Light-Emitting Diodes (LEDs) are small lights made from a silicon diode. They come in different colors, brightnesses and sizes. LEDs have a positive (+) leg and a negative (-) leg, and they will only let electricity flow through them in one direction. LEDs can also burn out if too much electricity flows through them, so you should always use a resistor to limit the current when you wire an LED into a circuit.

LED

Resistors

Resistors resist the flow of electricity. You can use them to protect sensitive components like LEDs. The strength of a resistor (measured in ohms) is marked on the body of the resistor using small colored bands. Each color stands for a number, which you can look up using a resistor chart.

Resistors

New Concepts

Polarity

Many electronics components have polarity, meaning electricity can only flow through them in one direction. Components like resistors do not have polarity; electricity can flow through them in either direction. However, components like an LED that do have polarity only work when electricity flows through them in one direction.

Ohm’s Law

Ohm’s law describes the relationship between the three fundamental elements of electricity: voltage, resistance and current. This relationship can be represented by the following equation:

Ohm's Law

Where

  • V = Voltage in volts
  • I = Current in amps
  • R = Resistance in ohms (&ohm;)

This equation is used to calculate what resistor values are suitable to sufficiently limit the current flowing to the LED so that it does not get too hot and burn out.

Digital Output

When working with microcontrollers such as the RedBoard, there are a variety of pins to which you can connect electronic components. Knowing which pins perform which functions is important when building your circuit. In this circuit, we will be using what is known as a digital output. There are 14 of these pins found on the RedBoard and Arduino Uno. A digital output only has two states: ON or OFF. These two states can also be thought of as HIGH or LOW or TRUE or FALSE. When an LED is connected to one of these pins, the pin can only perform two jobs: turning the LED on and turning the LED off. We’ll explore the other pins and their functions in later circuits.

Digital Pins

The 14 digital pins highlighted.

Hardware Hookup

We recommend familiarizing yourself with each of the components used in each circuit first.

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.

Pay close attention to the LED. It is polarized. 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.

Bent resistor

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

Circuit Diagram

Circuit Diagrams: SparkFun uses a program called Fritzing to draw the circuit diagrams you see throughout this guide and throughout all of our online guides. Fritzing allows us to create diagrams that make it easier for you to see how your circuit should be built.

alt text

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

Hookup Tables: Many electronics beginners find it helps to have a coordinate system when building their circuits. For each circuit, you'll find a hookup table that lists the coordinates of each component and where it connects to the RedBoard, the breadboard, or both. The breadboard has a letter/number coordinate system, just like the game Battleship.
ComponentRedBoardBreadboardBreadboard
A1 LED ( - )A2 LED ( + )
330Ω Resistor
(orange, orange, brown)
E2F2
Jumper WireGNDE1
Jumper WireDigital Pin 13J2

In the table, polarized components are shown with a warning triangle and the whole row highlighted yellow.

Open Your First Sketch

Open the Arduino IDE software on your computer. Open the code for Circuit 1A 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-V_4 > SIK_Circuit_1A-Blink

Experiment_List

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
Circuit 1A-Blink

Turns an LED connected to pin 13 on and off. Repeats forever.

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v40
Download code at: https://github.com/sparkfun/SIK-Guide-Code
*/

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

void loop()
{
  digitalWrite(13, HIGH);   // Turn on the LED
  delay(2000);              // Wait for one second
  digitalWrite(13, LOW);    // Turn off the LED
  delay(2000);              // Wait for one second
}
/*
 / Try changing the 2000 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.
 */

What You Should See

The LED will flash on for two seconds, off for two seconds, then repeat. If it doesn’t, make sure you have assembled the circuit correctly and verified and uploaded the code to your board, or see the Troubleshooting section at the end of this section.

circuit 1A action shot

Program Overview

  1. Turn the LED on by sending power to Pin 13.
  2. Wait 2 seconds (2000 milliseconds).
  3. Turn the LED off by cutting power to Pin 13.
  4. Wait 2 seconds (2000 milliseconds).
  5. Repeat.

One of the best ways to understand the code you just uploaded is to change something and see how it affects the behavior of your circuit. For this first circuit, try changing the number found in these lines of code: delay(2000);. What happens if you change both to 100? What happens if you change both to 5000? What happens if you change just one delay and not the other?

Onboard LED PIN 13: You may have noticed a second, smaller LED blinking in unison with the LED in your breadboard circuit. This is known as the onboard LED, and you can find one on almost any Arduino or Arduino-compatible board including the RedBoard. In most cases, this LED is connected to digital pin 13 (D13), which is the same pin used in this circuit. This LED is useful for troubleshooting, as you can always upload the Blink sketch to see if that LED lights up. If so, you know your board is functioning properly. If you do not want this LED to blink with other LEDs in your circuits, simply use any of the other 12 digital pins (D0-D12).

Code to Note

Code to Note: The sketches that accompany each circuit introduce new programming techniques and concepts as you progress through the guide. The Code to Note section highlights specific lines of code from the sketch and explains them in further detail.
CodeDescription
Setup and Loop:
void setup(){code to run once}&void loop(){code to run forever}
Every Arduino program needs these two functions. Code that goes in between the curly brackets of setup() runs once, then the code in between the loop() curly brackets runs over and over until the RedBoard is reset or powered off.
Input or Output?:
pinMode(13, OUTPUT);
Before you can use one of the digital pins, you need to tell the RedBoard whether it is an INPUT or OUTPUT. We use a built-in "function" called pinMode() to make pin 13 a digital output. You'll learn more about digital inputs in Project 2.
Digital Output:
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).
Delay:
delay(time in milliseconds);
Causes the program to wait on this line of code for the amount of time in between the brackets. After the time has passed, the program will continue to the next line of code.
Comments:
//This is a comment
Comments are a great way to leave notes in your code explaining why you wrote it the way you did. You'll find many comments in the examples that further explain what the code is doing and why. Comments can be single line using //, or they can be multi-line using /* */.

Coding Challenges

Coding Challenges: The Coding Challenges section is where you can find suggestions for changes to the circuit or code that will make the circuit more challenging. If you feel underwhelmed by the tasks in each circuit, visit the Coding Challenges section to push yourself to the next level.
ChallengeDescription
Persistence of VisionComputer screens, movies and the lights in your house all flicker so quickly that they appear to be on all of the time but are actually blinking faster than the human eye can detect. See how much you can decrease the delay time in your program before the light appears to be on all the time but is still blinking.
Morse CodeTry changing the delays and adding more digitalWrite() commands to make your program blink a message in Morse code.

Troubleshooting

Troubleshooting: Last, each circuit has a Troubleshooting section with helpful tips and tricks to aid you in any problems you encounter along the way.
ProblemSolution
I get an error when uploading my codeThe most likely cause is that you have the wrong board selected in the Arduino IDE. Make sure you have selected Tools > Board > Arduino/Genuino Uno.
I still get an error when uploading my codeIf you're sure you have the correct Board selected but you still can't upload, check that you have selected the correct Serial Port. You can change this in Tools > Serial Port >your_serial_port.
Which Serial Port is the right one?Depending on how many devices you have plugged into your computer, you may have several active Serial Ports. Make sure you are selecting the correct one. A simple way to determine this is to look at your list of Serial Ports. Unplug your RedBoard from your computer. Look at the list again. Whichever Serial Port has disappeared from the list is the one you want to select once you plug your board back in to your computer.
My code uploads, but my LED won’t turn onLEDs will only work in one direction. Try taking it out of your breadboard, turning it 180 degrees, and reinserting it.
Still not working?Jumper wires unfortunately can go "bad" from getting bent too much. The copper wire inside can break, leaving an open connection in your circuit. If you are certain that your circuit is wired correctly and that your code is error-free and uploaded but you are still encountering issues, try replacing one or more of the jumper wires for the component that is not working.

Circuit 1B: Potentiometer

Potentiometers (also known as “pots” or “knobs”) are one of the basic inputs for electronics devices. By tracking the position of the knob with your RedBoard, you can make volume controls, speed controls, angle sensors and a ton of other useful inputs for your projects. In this circuit, you’ll use a potentiometer as an input device to control the speed at which your LED blinks.

Project1_Circuit1B_Hero

Parts Needed

Grab the following quantities of each part listed to build this circuit:

parts

New Components

Potentiometer

A potentiometer (trimpot for short) is 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. Internal to the trimpot is a single resistor and a wiper, which cuts the resistor in two and moves to adjust the ratio between both halves. Externally, there are usually three pins: two pins connect to each end of the resistor, while the third connects to the pot’s wiper.

potentiometer

New Concepts

Analog vs. Digital

Understanding the difference between analog and digital is a fundamental concept in electronics.

We live in an analog world. There is an infinite number of colors to paint an object (even if the difference is indiscernible to our eye), an infinite number of tones we can hear, and an infinite number of smells we can smell. The common theme among all of these analog signals is their infinite possibilities.

Digital signals deal in the realm of the discrete or finite, meaning there is a limited set of values they can be. The LED from the previous circuit had only two states it could exist in, ON or OFF, when connected to a Digital Output.

Analog Inputs

So far, we’ve only dealt with outputs. The RedBoard also has inputs. Both inputs and outputs can be analog or digital. Based on our definition of analog and digital above, that means an analog input can sense a wide range of values versus a digital input, which can only sense two states.

You may have noticed some pins labeled Digital and some labeled Analog In on your RedBoard. There are only six pins that function as analog inputs; they are labeled A0–A5.

analog pins vs digital pins

The six analog pins highlighted.

Voltage Divider

A voltage divider is a simple circuit that turns some voltage into a smaller voltage using two resistors. The following is a schematic of the voltage divider circuit. Schematics are a universally agreed upon set of symbols that engineers use to represent electric circuits.

voltage divider

A potentiometer is a variable resistor that can be used to create an adjustable voltage divider.

Schematic symbol for a potentiometer

A potentiometer schematic symbol where pins 1 and 3 are the resistor ends, and pin 2 connects to the wiper

If the outside pins connect to a voltage source (one to ground, the other to Vin), the output (Vout) at the middle pin will mimic a voltage divider. Turn the trimpot all the way in one direction, and the voltage may be zero; turned to the other side, the output voltage approaches the input. A wiper in the middle position means the output voltage will be half of the input.

Voltage dividers will be covered in more detail in the next circuit.

Hardware Hookup

The potentiometer has three legs. Pay close attention into which pins you’re inserting it on the breadboard, as they will be hard to see once inserted.

Potentiometers are not polarized. You can attach either of the outside pins to 5V and the opposite to GND. However, the values you get out of the trimpot will change based on which pin is 5V and which is GND.

potentiometer_pinout

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

Circuit Diagram

Circuit 1B

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

ComponentRedBoardBreadboardBreadboardBreadboard
Jumper Wire5V5V Rail ( + )
Jumper WireGNDGND Rail ( - )
A1 LED ( - )A2 LED ( + )
330Ω Resistor
(orange, orange, brown)
E2F2
Jumper WireE1GND Rail ( - )
Jumper WireDigital Pin 13J2
PotentiometerB25B26B27
Jumper WireAnalog Pin 0 (A0)E26
Jumper WireE255V Rail ( + )
Jumper WireE27GND Rail ( - )

In the table, polarized components are shown with a warning triangle and the whole row highlighted yellow.

Open the Sketch

To open the code, go to: File > Examples > SIK_Guide_Code-V_4 > SIK_Circuit_1B-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
Circuit 1B-Potentiometer

Changes how fast an LED connected to pin 13 blinks, based on a potentiometer connected to pin A0

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v40
Download code at: https://github.com/sparkfun/SIK-Guide-Code
*/

int potPosition;       //this variable will hold a value based on the position of the potentiometer

void setup()
{
  Serial.begin(9600);       //start a serial connection with the computer

  pinMode(13, OUTPUT);      //set pin 13 as an output that can be set to HIGH or LOW
}

void loop()
{
  //read the position of the pot
  potPosition = analogRead(A0);    //set potPosition to a number between 0 and 1023 based on how far the knob is turned
  Serial.println(potPosition);     //print the value of potPosition in the serial monitor on the computer

  //change the LED blink speed based on the trimpot value
  digitalWrite(13, HIGH);           // Turn on the LED
  delay(potPosition);              // delay for as many miliseconds as potPosition (0-1023)

  digitalWrite(13, LOW);            // Turn off the LED
  delay(potPosition);              // delay for as many miliseconds as potPosition (0-1023)
}

What You Should See

You should see the LED blink faster or slower in accordance with your potentiometer. The delay between each flash will change based on the position of the knob. 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.

circuit 1B action shot

Program Overview

  1. Read the position of the potentiometer (from 0 to 1023) and store it in the variable potPosition.
  2. Turn the LED on.
  3. Wait from 0 to 1023 milliseconds, based on the position of the knob and the value of potPosition.
  4. Turn the LED off.
  5. Wait from 0 to 1023 milliseconds, based on the position of the knob and the value of potPosition.
  6. Repeat.
The Serial Monitor: The Serial Monitor is one of the Arduino IDE's many great built-in tools. It can help you understand the values that your program is trying to work with, and it can be a powerful debugging tool when you run into issues where your code is not behaving the way you expected it to. This circuit introduces you to the Serial Monitor by showing you how to print the values from your potentiometer to it. To see these values, click the Serial Monitor button, found in the upper-right corner of the IDE in most recent versions. You can also select Tools > Serial Monitor from the menu.

You should then see numeric values print out on the monitor. Turn the potentiometer, and you should see the values change as well as the delay between each print.



If you are having trouble seeing the values, ensure that you have selected 9600 baud in the dropdown menu and have auto scroll checked.

Code to Note

CodeDescription
Integer Variables:
int potPosition;
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 potPosition of type int (integer). We will cover more types of variables in later circuits. Don't forget that variable names are case-sensitive!
Serial Begin:
Serial.begin(9600);
Serial commands can be used to send and receive data from your computer. This line of code tells the RedBoard that we want to "begin" that communication with the computer, the same way we would say "Hi" to initiate a conversation. Notice that the baud rate, 9600, is the same as the one we selected in the monitor. This is the speed at which the two devices communicate, and it must match on both sides.
Analog Input:
potPosition = analogRead(A0);
We use the analogRead() function to read the value on an analog pin. analogRead() takes one parameter, the analog pin you want to use, A0 in this case, and returns a number between 0 (0 volts) and 1023 (5 volts), which is then assigned to the variable potPosition.
Serial Print:
Serial.println(potPosition);
This is the line that actually prints the trimpot value to the monitor. It takes the variable potPosition and prints whatever value it equals at that moment in the loop(). The ln at the end of print tells the monitor to print a new line at the end of each value; otherwise the values would all run together on one line. Try removing the ln to see what happens.

Coding Challenges

ChallengeDescription
Changing the RangeTry multiplying, dividing or adding to your sensor reading so that you can change the range of the delay in your code. For example, can you multiply the sensor reading so that the delay goes from 0–2046 instead of 0–1023?
Adding More LEDsAdd more LEDs to your circuit. Don't forget the current limiting resistor for each one. Try making multiple LEDs blink at different rates by changing the range of each using multiplication or division.

Troubleshooting

ProblemSolution
The potentiometer always reads as 0 or 1023Make sure that your 5V, A0 and GND pins are properly connected to the three pins on your potentiometer. It is easy to misalign a wire with the actual trimpot pin.
No values in Serial MonitorMake sure that you have selected the correct baud rate, 9600. Also ensure that you are on the correct Serial Port. The same Serial Port you use when uploading code to your board is the same Serial Port you use to print values to the Serial Monitor.

Circuit 1C: Photoresistor

In circuit 1B, 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. Using this sensor you can make a simple night-light that turns on when the room gets dark and turns off when it is bright.

Project1_Circuit1C_Hero

Parts Needed

Grab the following quantities of each part listed to build this circuit:

parts

New Components

Photoresistor

Photoresistors, or photocells, are light-sensitive, variable resistors. As more light shines on the sensor’s head, the resistance between its two terminals decreases. They’re an easy-to-use component in projects that require ambient-light sensing.

Photoresistor

New Concepts

Analog to Digital Conversion

The world we live in is analog, but the RedBoard lives in a digital world. In order to have the RedBoard sense analog signals, we must first pass them through an Analog to Digital Converter (or ADC). The six analog inputs (A0–A5) covered in the last circuit all use an ADC. These pins “sample” the analog signal and create a digital signal for the microcontroller to interpret. The “resolution” of this signal is based on the resolution of the ADC. In the case of the RedBoard, that resolution is 10-bit. With a 10-bit ADC, we get 2 ^ 10 = 1024 possible values, which is why the analog signal varies between 0 and 1023.

Voltage Divider Continued

Since the RedBoard can’t directly interpret resistance (rather, it reads voltage), we need to use a voltage divider to use our photoresistor, a part that doesn’t output voltage. The resistance of the photoresistor changes as it gets darker or lighter. That changes the amount of voltage that is read on the analog pin, which “divides” the voltage, 5V in this case. That divided voltage is then read on the analog to digital converter.

Left: A regular voltage divider circuit. Vout will be a constant voltage. Right: A variable voltage divider circuit. Vout will fluctuate as the resistance of the photoresistor changes.

The voltage divider equation assumes that you know three values of the above circuit: the input voltage (Vin), and both resistor values (R1 and R2). Given those values, we can use this equation to find the output voltage (Vout):

Vout = Vin * (R2 / (R1 + R2))

If R1 is a constant value (the resistor) and R2 fluctuates (the photoresistor), the amount of voltage measured on the Vout pin will also fluctuate.

Hardware Hookup

Note that the photoresistor is not polarized. It can be inserted in either direction.

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

Circuit Diagram

Circuit_1C

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

ComponentRedBoardBreadboardBreadboard
Jumper Wire5V5V Rail ( + )
Jumper WireGNDGND Rail ( - )
A1 LED ( - )A2 LED ( + )
330Ω Resistor
(orange, orange, brown)
E2F2
Jumper WireE1GND Rail ( - )
Jumper WireDigital Pin 13J2
PhotoresistorA26B25
10kΩ Resistor
(brown, black, orange)
C26D27
Jumper WireAnalog Pin 0 (A0)E26
Jumper WireE255V Rail ( + )
Jumper WireE27GND Rail ( - )

In the table, polarized components are shown with a warning triangle and the whole row highlighted yellow.

Open the Sketch

To open the code, go to: File > Examples > SIK_Guide_Code-V_4 > SIK_Circuit_1C-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
Circuit 1C-Photoresistor

Use a photoresistor to monitor how bright a room is, and turn an LED on when it gets dark.

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v40
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
*/

int photoresistor = 0;              //this variable will hold a value based on the position of the knob
int threshold = 750;                //if the photoresistor reading is below this value the light will turn on

void setup()
{
  Serial.begin(9600);               //start a serial connection with the computer

  pinMode(13, OUTPUT);              //set pin 13 as an output that can be set to HIGH or LOW
}

void loop()
{
  //read the position of the knob
  photoresistor = analogRead(A0);   //set photoresistor to a number between 0 and 1023 based on how far the knob is turned
  Serial.println(photoresistor);    //print the value of photoresistor in the serial monitor on the computer

  //if the photoresistor value is below the threshold turn the light on, otherwise turn it off
  if (photoresistor < threshold){
    digitalWrite(13, HIGH);         // Turn on the LED
  } else{
    digitalWrite(13, LOW);          // Turn off the LED
  }

  delay(100);                       //short delay to make the printout easier to read
}

What You Should See

The program stores the light level in a variable, photoresistor. Then, using an if/else statement, the program checks to see what it should do with the LED. If the variable is above the threshold (it’s bright), turn the LED off. If the variable is below the threshold (it’s dark), turn the LED on. You now have just built your own night-light!

Project1_Circuit1C_Action

Open the Serial Monitor in Arduino. The value of the photoresistor should be printed every so often. When the photoresistor value drops below the threshold value set in the code, the LED should turn on (you can cover the photoresistor with your finger to make the value drop).

Note: If the room you are in is very bright or dark, you may have to change the value of the “threshold” variable in the code to make your night-light turn on and off. See the Troubleshooting section for instructions.

Program Overview

  1. Store the light level in the variable photoresistor.
  2. If the value of photoresistor is above the threshold (it’s bright), turn the LED off.
  3. If the value of photoresistor is below the threshold (it’s dark), turn the LED on.

Code to Note

CodeDescription
If/else Statements:
if(logic statement) {
code to be run if the logic statement is true}
else {
code to be run if the logic statement is false }
The if/else statement lets your code react to the world by running one set of code when the logic statement in the round brackets is true and another set of code when the logic statement is false. For example, this sketch uses an if statement to turn the LED on when it is dark, and turn the LED off when it is light.
Logical Operators:
(photoresistor
Programmers use logic statements to translate things that happen in the real world into code. Logic statements use logical operators such as 'equal to' (==), 'greater than' (>), and 'less than' (), to make comparisons. When the comparison is true (e.g., 4

Coding Challenges

ChallengeDescription
Response PatternRight now your if statement turns the LED on when it gets dark, but you can also use the light sensor like a no-touch button. Try using digitalWrite() and delay() to make the LED blink a pattern when the light level drops, then calibrate the threshold variable in the code so that the blink pattern triggers when you wave your hand over the sensor.
Replace 10K&ohm; Resistor with LEDAlter the circuit be replacing the 10K&ohm; resistor with an LED (the negative leg should connect to GND). Now what happens when you place your finger over the photoresistor? This is a great way to see Ohm's law in action by visualizing the change in resistance's affect on the current flowing through the LED.

Troubleshooting

ProblemSolution
The light never turns on or always stays onStart the Serial Monitor in Arduino. Look at the value that the photoresistor is reading in a bright room (e.g., 915). Cover the photoresistor, or turn the lights off. Then look at the new value that the photoresistor is reading (e.g., 550). Set the threshold in between these two numbers (e.g., 700) so that the reading is above the threshold when the lights are on and below the threshold when the lights are off.
Nothing is printing in the Serial MonitorTry unplugging your USB cable and plugging it back in. In the Arduino IDE, go to Tools > Port, and make sure that you select the right port.

Circuit 1D: RGB Night-Light

In this circuit, you’ll take the night-light concept to the next level by adding an RGB LED, which is three differently colored Light-Emitting Diodes (LEDs) built into one component. RGB stands for Red, Green and Blue, and these three colors can be combined to create any color of the rainbow!

Project1_Circuit1D_Hero

Parts Needed

Grab the following quantities of each part listed to build this circuit:

parts

New Components

RGB LED

An RGB LED is actually three small LEDs — one red, one green and one blue — inside a normal LED housing. The RGB LED included in this kit has all the internal LEDs share the same ground wire, so there are four legs in total. To turn one color on, ensure ground is connected, then power one of the legs just as you would a regular LED. If you turn on more than one color at a time, you will see the colors start to blend together to form a new color.

RGB LED

New Concepts

Analog Output (Pulse-width Modulation)

You can use the digitalWrite() command to turn pins on the RedBoard on (5V) or off (0V), but what if you want to output 2.5V? The RedBoard doesn’t have an Analog Output, but it is really good at switching some digital pins on and off fast enough to simulate an analog output. analogWrite() can output 2.5 volts by quickly switching a pin on and off so that the pin is only on 50 percent of the time (50% of 5V is 2.5V). By changing the percent of time that a pin is on, from 0 percent (always off) to 100 percent (always on), analogWrite() can output any voltage between 0 and 5V. This is what is known as pulse-width modulation (or PWM). By using PWM, you can create many different colors with the RGB LED.

Digital (PWM~): Only a few of the pins on the RedBoard have the circuitry needed to turn on and off fast enough for PWM. These are pins 3, 5, 6, 9, 10 and 11. Each PWM pin is marked with a ~ on the board. Remember, you can only use analogWrite() on these pins.

Creating Your Own Simple Functions

When programmers want to use a piece of code over and over again, they write a function. The simplest functions are just chunks of code that you give a name to. When you want to run that code, you can “call” the function by typing its name, instead of writing out all of the code. More complicated functions take and return pieces of information from the program (we call these pieces of information parameters). In this circuit, you’ll write functions to turn the RGB LED different colors by just typing that color’s name.

Hardware Hookup

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.

Just like a regular LED, an RGB LED is polarized and only allows electricity to flow in one direction. Pay close attention to the flat edge and to the different length leads. Both are indicators to help orient the LED correctly.

RGB LED Pins

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

Circuit Diagram

Circuit_1D-RGB_Nightlight

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

ComponentRedBoardBreadboardBreadboardBreadboardBreadboard
A5 (RED)A4 (GND)A3 (GREEN)A2 (BLUE)
330Ω Resistor
(orange, orange, brown)
E2F2
330Ω Resistor
(orange, orange, brown)
E3F3
330Ω Resistor
(orange, orange, brown)
E5F5
Jumper WireE4GND Rail ( - )
Jumper WireDigital Pin 9J5
Jumper WireDigital Pin 10J3
Jumper WireDigital Pin 11J2
Jumper Wire5V5V Rail ( + )
Jumper WireGNDGND Rail ( - )
PotentiometerB15B16B17
Jumper WireAnalog Pin 1 (A1)E16
Jumper WireE155V Rail ( + )
Jumper WireE17GND Rail ( - )
PhotoresistorA26B25
10kΩ Resistor
(brown, black, orange)
C26D27
Jumper WireAnalog Pin 0 (A0)E26
Jumper WireE255V Rail ( + )
Jumper WireE27GND Rail ( - )

In the table, polarized components are shown with a warning triangle and the whole row highlighted yellow.

Open the Sketch

To open the code, go to: File > Examples > SIK_Guide_Code-V_4 > SIK_Circuit_1D-RGBNightlight

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
Circuit 1D-RGB Nightlight

Turns an RGB LED on or off based on the light level read by a photoresistor.
Change colors by turning the potentiometer.

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v40
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
 */

int photoresistor;          //variable for storing the photoresistor value
int potentiometer;          //variable for storing the photoresistor value
int threshold = 700;            //if the photoresistor reading is lower than this value the light wil turn on

//LEDs are connected to these pins
int RedPin = 9;
int GreenPin = 10;
int BluePin = 11;

void setup() {
  Serial.begin(9600);           //start a serial connection with the computer

  //set the LED pins to output
  pinMode(RedPin,OUTPUT);
  pinMode(GreenPin,OUTPUT);
  pinMode(BluePin,OUTPUT);
}

void loop() {

  photoresistor = analogRead(A0);         //read the value of the photoresistor
  potentiometer = analogRead(A1);

  Serial.print("Photoresistor value:");
  Serial.print(photoresistor);          //print the photoresistor value to the serial monitor
  Serial.print("  Potentiometer value:");
  Serial.println(potentiometer);          //print the photoresistor value to the serial monitor

  if(photoresistor < threshold){          //if it's dark (the photoresistor value is below the threshold) turn the LED on
    //These nested if staments check for a variety of ranges and
    //call different functions based on the current potentiometer value.
    //Those functions are found at the bottom of the sketch.
    if(potentiometer > 0 && potentiometer <= 150)
      red();
    if(potentiometer > 150 && potentiometer <= 300)
      orange();
    if(potentiometer > 300 && potentiometer <= 450)
      yellow();
    if(potentiometer > 450 && potentiometer <= 600)
      green();
    if(potentiometer > 600 && potentiometer <= 750)
      cyan();
    if(potentiometer > 750 && potentiometer <= 900)
      blue();
    if(potentiometer > 900)
      magenta();
  }
  else {                                //if it isn't dark turn the LED off

    turnOff();                            //call the turn off function

  }

  delay(100);                             //short delay so that the printout is easier to read
}

void red (){

    //set the LED pins to values that make red
    analogWrite(RedPin, 100);
    analogWrite(GreenPin, 0);
    analogWrite(BluePin, 0);
}
void orange (){

    //set the LED pins to values that make orange
    analogWrite(RedPin, 100);
    analogWrite(GreenPin, 50);
    analogWrite(BluePin, 0);
}
void yellow (){

    //set the LED pins to values that make yellow
    analogWrite(RedPin, 100);
    analogWrite(GreenPin, 100);
    analogWrite(BluePin, 0);
}
void green (){

    //set the LED pins to values that make green
    analogWrite(RedPin, 0);
    analogWrite(GreenPin, 100);
    analogWrite(BluePin, 0);
}
void cyan (){

    //set the LED pins to values that make cyan
    analogWrite(RedPin, 0);
    analogWrite(GreenPin, 100);
    analogWrite(BluePin, 100);
}
void blue (){

    //set the LED pins to values that make blue
    analogWrite(RedPin, 0);
    analogWrite(GreenPin, 0);
    analogWrite(BluePin, 100);
}
void magenta (){

    //set the LED pins to values that make magenta
    analogWrite(RedPin, 100);
    analogWrite(GreenPin, 0);
    analogWrite(BluePin, 100);
}
void turnOff (){

    //set all three LED pins to 0 or OFF
    analogWrite(RedPin, 0);
    analogWrite(GreenPin, 0);
    analogWrite(BluePin, 0);
}

What You Should See

This sketch is not dissimilar from the last. It reads the value from the photoresistor, compares it to a threshold value, and turns the RGB LED on or off accordingly. This time, however, we’ve added a potentiometer back into the circuit. When you twist the pot, you should see the color of the RGB LED change based on the pot’s value.

Project1_Circuit1D_Action

Open the Serial Monitor. The value being read by the light sensor should be printed several times a second. When you turn out the lights or cover the sensor, the LED will shine whatever color your programmed in your color function. Next to the light value, you’ll see the potentiometer value print out as well.

Note: If the room you are in is very bright or dark, you may have to change the value of the “threshold” variable in the code to make your night-light turn on and off. See the Troubleshooting section for instructions.

Program Overview

  1. Store the light level from pin A0 in the variable photoresistor.
  2. Store the potentiometer value from pin A1 in the variable potentiometer.
  3. If the light level variable is above the threshold, call the function that turns the RGB LED off.
  4. If the light level variable is below the threshold, call one of the color functions to turn the RGB LED on.
  5. If potentiometer is between 0 and 150, turn the RGB LED on red.
  6. If potentiometer is between 151 and 300, turn the RGB LED on orange.
  7. If potentiometer is between 301 and 450, turn the RGB LED on yellow.
  8. If potentiometer is between 451 and 600, turn the RGB LED on green.
  9. If potentiometer is between 601 and 750, turn the RGB LED on cyan.
  10. If potentiometer is between 751 and 900, turn the RGB LED on blue.
  11. If potentiometer is greater than 900, turn the RGB LED on magenta.

Code to Note

CodeDescription
Analog Output (PWM):
analogWrite(RedPin, 100);
The analogWrite() function outputs a voltage between 0 and 5V on a pin. The function breaks the range between 0 and 5V into 255 little steps. Note that we are not turning the LED on to full brightness (255) in this code so that the night-light is not too bright. Feel free to change these values and see what happens.
Nested if Statements:
if(logic statement) {
if(logic statement) {
code to be run if the logic statement is true}
if(logic statement) {
code to be run if the logic statement is true}
}
A nested if statement is one or more if statements "nested" inside of another if statement. If the parent if statement is true, then the code looks at each of the nested if statements and executes any that are true. If the parent if statement is false, then none of the nested statements will execute.
More Logical Operators:
if(potentiometer > 0 && potentiometer
These if statements are checking for two conditions by using the AND (&&) operator. In this line, the if statement will only be true if the value of the variable potentiometer is greater than 0 AND if the value is less than or equal to 150. By using &&, the program allows the LED to have many color states.
Defining a Function:
void function_name () {
code to run inside function }
This simple version of a function executes the code inside the curly brackets whenever the name is written in the main program.
Calling a Function:
function_name();
Calls a function that you have created. In a later circuit, you will learn how to make more complicated functions that take data from the main program (these pieces of data are called parameters).

Coding Challenges

ChallengeDescription
Add more colorsYou can create many more colors with the RGB LED. Use the analogWrite() function to blend different values of red, green and blue together to make even more colors. You can divide the potentiometer value up more and make more nested if statements so that you can have more colors as you twist the knob.
Multi color blinkTry using delays and multiple color functions to have your RGB LED change between multiple colors.
Change the thresholdTry setting your threshold variable by reading the value of a potentiometer with analogRead(). By turning the potentiometer, you can then change the threshold level and adjust your night-light for different rooms.
Fading the LEDTry using a loop with the analogWrite() to get your LED to pulse gently or smoothly transition between colors.

Troubleshooting

ProblemSolution
The LED never turns on or offOpen the Serial Monitor in Arduino and make sure that your photoresistor is returning values between 0 and 1023. Try covering the photoresistor; the values should change. If they do not change, check the wiring of the photoresistor.
If your photoresistor is working correctly, make sure that your threshold variable sits in between the value that the photoresistor reads when it is bright and the value that the photoresistor reads when it is dark (e.g., bright = 850, dark = 600, threshold = 700).
My LED doesn’t show the colors that I expectMake sure that all three of the pins driving your RGB LED are set to OUTPUT, using the pinMode() command in the setup section of the code. Then make sure that each LED is wired properly.
Nothing is printing in the Serial MonitorTry unplugging your USB cable and plugging it back in. In the Arduino IDE, go to Tools > Port, and make sure that you select the right port.

Project 2: Sound

In Project 2, you will venture into the world of buttons and buzzers while building your own Simon Says game! Simon Says is a game in which the LEDs flash a pattern of red, green, yellow and blue blinks, and the user must recreate the pattern using color-coded buttons before the timer runs out.

Project 2

New Components Introduced in This Project

Each of the components listed below will be described in more detail as you progress through each circuit.

  • Buzzer
  • Buttons

New Concepts Introduced in This Project

Each of the concepts listed below will be described in more detail as you progress through each circuit.

  • Arrays
  • Binary
  • Digital Inputs
  • Pull-up Resistors
  • For Loops
  • Measuring Elapsed Time

You Will Learn

  • How to make tones with a buzzer
  • How to read a button using digital inputs
  • How to program a game

Circuit 2A: Buzzer

In this circuit, you’ll use the RedBoard and a small buzzer to make music, and you’ll learn how to program your own songs using arrays.

Project2_Circuit2A_Hero

Parts Needed

Grab the following quantities of each part listed to build this circuit:

parts

New Components

Buzzer

The buzzer uses a small magnetic coil to vibrate a metal disc inside a plastic housing. By pulsing electricity through the coil at different rates, different frequencies (pitches) of sound can be produced. Attaching a potentiometer to the output allows you to limit the amount of current moving through the buzzer and lower its volume.

buzzer

New Concepts

Reset Button

The RedBoard has a built-in reset button. This button will reset the board and start the code over from the beginning, running what is in setup() and then loop().

reset button

Tone Function

To control the buzzer, you will use the tone function. This function is similar to PWM in that it generates a wave that is of a certain frequency on the specified pin. The frequency and duration can both be passed to the tone() function when calling it. To turn the tone off, you need to call noTone() or pass a duration of time for it to play and then stop. Unlike PWM, tone() can be used on any digital pin.

Arrays

Arrays are used like variables, but they can store multiple values. The simplest array is just a list. Imagine that you want to store the frequency for each note of the C major scale. We could make seven variables and assign a frequency to each one, or we could use an array and store all seven in the same array, as shown below. To refer to a specific value in the array, an index number is used. Arrays are indexed from 0. For example, to call the first element in the array, use array_name[0];; to call the second element, use array_name[1]; and so on.

Musical NoteFrequency (Hz)Using VariablesUsing an Array
A220aFrequencyfrequency[0]
B247bFrequencyfrequency[1]
C261cFrequencyfrequency[2]
D294dFrequencyfrequency[3]
E330eFrequencyfrequency[4]
F349fFrequencyfrequency[5]
G392gFrequencyfrequency[6]

Hardware Hookup

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.

The buzzer is polarized. To see which leg is positive and which is negative, flip the buzzer over and look at the markings underneath. Keep track of which pin is where, as they will be hard to see once inserted into the breadboard. There is also text on the positive side of the buzzer, along with a tiny (+) symbol.

Volume Knob

All of the circuits in Project 2 make use of a potentiometer as a rudimentary volume knob. Notice that only two of the potentiometer’s legs are used in these circuits. In these instances, the potentiometer is acting as a variable resistor, limiting the amount of current flowing to the speaker and thus affecting the volume as you turn the knob. This is similar to the current-limiting resistor used to limit current to the LED in circuit 1A — only this time the resistance is variable.

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

Circuit Diagram

Circuit_2A_buzzer

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

ComponentRedBoardBreadboardBreadboardBreadboard
J1 (Buzzer + )J3 (Buzzer - )
PotentiometerB1B2B3
Jumper WireGNDGND Rail ( - )
Jumper WireDigital Pin 10F1
Jumper WireE2GND Rail ( - )
Jumper WireE1F3

In the table, polarized components are shown with a warning triangle and the whole row highlighted yellow.

Open the Sketch

To open the code, go to: File > Examples > SIK_Guide_Code-V_4 > SIK_Circuit_2A-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
Circuit 2A - Buzzer

Play notes using a buzzer connected to pin 10

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v40
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
*/


int speakerPin = 10;               //the pin that buzzer is connected to

void setup()
{
  pinMode(speakerPin, OUTPUT);    //set the output pin for the speaker
}

void loop()
{

  play('g', 2);       //ha
  play('g', 1);       //ppy
  play('a', 4);       //birth
  play('g', 4);       //day
  play('C', 4);       //to
  play('b', 4);       //you

  play(' ', 2);       //pause for 2 beats

  play('g', 2);       //ha
  play('g', 1);       //ppy
  play('a', 4);       //birth
  play('g', 4);       //day
  play('D', 4);       //to
  play('C', 4);       //you

  play(' ', 2);       //pause for 2 beats

  play('g', 2);       //ha
  play('g', 1);       //ppy
  play('G', 4);       //birth
  play('E', 4);       //day
  play('C', 4);       //dear
  play('b', 4);       //your
  play('a', 6);       //name

  play(' ', 2);       //pause for 2 beats

  play('F', 2);       //ha
  play('F', 1);       //ppy
  play('E', 4);       //birth
  play('C', 4);       //day
  play('D', 4);       //to
  play('C', 6);       //you

  while(true){}       //get stuck in this loop forever so that the song only plays once
}


void play( char note, int beats)
{
  int numNotes = 14;  // number of notes in our note and frequency array (there are 15 values, but arrays start at 0)

  //Note: these notes are C major (there are no sharps or flats)

  //this array is used to look up the notes
  char notes[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C', 'D', 'E', 'F', 'G', 'A', 'B', ' '};
  //this array matches frequencies with each letter (e.g. the 4th note is 'f', the 4th frequency is 175)
  int frequencies[] = {131, 147, 165, 175, 196, 220, 247, 262, 294, 330, 349, 392, 440, 494, 0};

  int currentFrequency = 0;    //the frequency that we find when we look up a frequency in the arrays
  int beatLength = 150;   //the length of one beat (changing this will speed up or slow down the tempo of the song)

  //look up the frequency that corresponds to the note
  for (int i = 0; i < numNotes; i++)  // check each value in notes from 0 to 14
  {
    if (notes[i] == note)             // does the letter passed to the play function match the letter in the array?
    {
      currentFrequency = frequencies[i];   // Yes! Set the current frequency to match that note
    }
  }

  //play the frequency that matched our letter for the number of beats passed to the play function
  tone(speakerPin, currentFrequency, beats * beatLength);
  delay(beats* beatLength);   //wait for the length of the tone so that it has time to play
  delay(50);                  //a little delay between the notes makes the song sound more natural

}

/* CHART OF FREQUENCIES FOR NOTES IN C MAJOR
Note      Frequency (Hz)
c        131
d        147
e        165
f        175
g        196
a        220
b        247
C        262
D        294
E        330
F        349
G        392
A        440
B        494
*/

What You Should See

When the program begins, a song will play from the buzzer once. To replay the song, press the reset button on the RedBoard. Use the potentiometer to adjust the volume.

Project2_Circuit2A_Action

Program Overview

Inside the main loop:

  1. Play the first note for x number of beats using the play function.
    1. (Inside the play function:) Take the note passed to the play function and compare it to each letter in the notes array. When you find a note that matches, remember the index position of that note (e.g., 6th entry in the notes array).
    2. Get a frequency from the frequency array that has the same index as the note that matched (e.g., the 6th frequency).
    3. Play that frequency for the number of beats passed to the play function.
  2. Play the second note using the play function
    …and so on.

Code to Note

CodeDescription
Character Variables:
void play( char note, int beats)
The char, or character, variable to store character values. For example, in this sketch, the play() function gets passed two variables, a character variable that represents the mucial note we want to play and an integer variable that represents how long to play that note. A second array takes the character variable and associates a frequency value to it. This makes programming a song easier as you can just reference the character and not the exact frequency.
Tone Function:
tone(pin, frequency, duration);
The tone() function will pulse power to a pin at a specific frequency. The duration controls how long the sound will play. Tone can be used on any digital pin.
Declaring an Array:
arrray_name[array_size]; or arrray_name[] = {array elements};
To declare an array, you must give it a name, then either tell Arduino how many positions the array will have or assign a list of values to the array.
Calling an Array:
array_name[index #];
To call one of the values in an array, simply type the name of the array and the index of the value. You can use a variable instead of a number in between the square brackets. Don't forget the index starts at 0, not 1, so to call the first element, use array_name[0];.

Coding Challenges

ChallengeDescription
Change the tempo of the songExperiment with the beatLength; variable to change the tempo of the song.
Make your own songTry changing the notes to make a different song. Spaces "" can be used for rests in the song.

Troubleshooting

ProblemSolution
The song is too quiet or too loudTurn the potentiometer to adjust the volume.
No sound is playingTry pressing the reset button on the RedBoard. If that doesn’t work, check your wiring of the buzzer. It's easy to misalign a pin with a jumper wire.

Circuit 2B: Digital Trumpet

Learn about digital inputs and buttons as you build your own digital trumpet!

Project2_Circuit2B_Hero

Parts Needed

Grab the following quantities of each part listed to build this circuit:

parts

New Components

Buttons

Buttons, also known as momentary switches, are switches that only remain in their on state as long as they’re being actuated, or pressed. Most often momentary switches are best used for intermittent user-input cases: reset button and keypad buttons. These switches have a nice, tactile, “clicky” feedback when you press them.

multicolored buttons

Note that the different colors are just aesthetic. All of the buttons included behave the same no matter their color.

New Concepts

Binary Number System

Number systems are the methods we use to represent numbers. We’ve all been mostly operating within the comfy confines of a base-10 number system, but there are many others. The base-2 system, otherwise known as binary, is common when dealing with computers and electronics. There are really only two ways to represent the state of anything: ON or OFF, HIGH or LOW, 1 or 0. And so, almost all electronics rely on a base-2 number system to store and manipulate numbers. The heavy reliance electronics places on binary numbers means it’s important to know how the base-2 number system works.

Digital Input

In circuit 1A, you worked with digital outputs. This circuit focuses on digital inputs. Digital inputs only care if something is in one of two states: TRUE or FALSE, HIGH or LOW, ON or OFF. Digital inputs are great for determining if a button has been pressed or if a switch has been flipped.

Pull-up Resistors

A pull-up resistor is a small circuit that holds the voltage HIGH (5V) on a pin until a button is pressed, pulling the voltage LOW (0V). The most common place you will see a pull-up resistor is when working with buttons. A pull-up resistor keeps the button in one state until it is pressed. The RedBoard has built-in pull-up resistors, but they can also be added to a circuit externally. This circuit uses the internal pull-up resistors, covered in more detail in the Code to Note section.

Hardware Hookup

Buttons are not polarized. However, they do merit a closer look. Buttons make momentary contact from one connection to another, so why are there four legs on each button? The answer is to provide more stability and support to the buttons in your breadboard circuit. Each row of legs is connected internally. When the button is pressed, one row connects to the other, making a connection between all four pins.

button pins explained

If the button’s legs don’t line up with the slots on the breadboard, rotate it 90 degrees.

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

Circuit Diagram

Circuit_2B_trumpet

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

ComponentRedBoardBreadboardBreadboardBreadboard
J1 (Buzzer + )J3 (Buzzer - )
PotentiometerB1B2B3
Jumper WireGNDGND Rail ( - )
Jumper WireDigital Pin 10F1
Jumper WireE2GND Rail ( - )
Jumper WireE1F3
Push ButtonD16/D18G16/G18
Push ButtonD22/D24G22/G24
Push ButtonD28/D30G28/G30
Jumper WireDigital Pin 4J18
Jumper WireDigital Pin 3J24
Jumper WireDigital Pin 2J30
Jumper WireJ16GND Rail ( - )
Jumper WireJ22GND Rail ( - )
Jumper WireJ28GND Rail ( - )

In the table, polarized components are shown with a warning triangle and the whole row highlighted yellow.

Open the Sketch

To open the code, go to: File > Examples > SIK_Guide_Code-V_4 > SIK_Circuit_2B-ButtonTrumpet

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
Circuit 2B-DigitalTrumpet

Use 3 buttons plugged to play musical notes on a buzzer.

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v40
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
*/

//set the pins for the button and buzzer
int firstKeyPin = 2;
int secondKeyPin = 3;
int thirdKeyPin = 4;

int buzzerPin = 10;


void setup() {
  //set the button pins as inputs
  pinMode(firstKeyPin, INPUT_PULLUP);
  pinMode(secondKeyPin, INPUT_PULLUP);
  pinMode(thirdKeyPin, INPUT_PULLUP);

  //set the buzzer pin as an output
  pinMode(buzzerPin, OUTPUT);
}

void loop() {

  if(digitalRead(firstKeyPin) == LOW){        //if the first key is pressed
    tone(buzzerPin, 262);                     //play the frequency for c
  }
  else if(digitalRead(secondKeyPin) == LOW){  //if the second key is pressed
    tone(buzzerPin, 330);                     //play the frequency for e
  }
  else if(digitalRead(thirdKeyPin) == LOW){   //if the third key is pressed
    tone(buzzerPin, 392);                     //play the frequency for g
  }
  else{
    noTone(buzzerPin);                        //if no key is pressed turn the buzzer off
  }
}

  /*
  note  frequency
  c     262 Hz
  d     294 Hz
  e     330 Hz
  f     349 Hz
  g     392 Hz
  a     440 Hz
  b     494 Hz
  C     523 Hz
  */

What You Should See

Different tones will play when you press different keys. Turning the potentiometer will adjust the volume.

Project2_Circuit2B_Action

Program Overview

  1. Check to see if the first button is pressed.
    1. If it is, play the frequency for c.
    2. If it isn’t, skip to the next else if statement.
  2. Check to see if the second button is pressed.
    1. If it is, play the frequency for e.
    2. If it isn’t, skip to the next else if statement.
  3. Check to see if the second button is pressed.
    1. If it is, play the frequency for g.
    2. If it isn’t, skip to the next else if statement.
  4. If none of the if statements are true
    1. Turn the buzzer off.

Code to Note

CodeDescription
Internal Pull-Up Resistor:
pinMode(firstKeyPin, INPUT_PULLUP);
To declare a standard input, use the line pinMode(pin_name, INPUT). If you would like to use one of the RedBoard's built-in pull-up 20k&ohm; resistors, it would look like this: pinMode(firstKeyPin, INPUT_PULLUP);. The advantage of external pull-ups is being able to choose a more exact value for the resistor.
Digital Input:
digitalRead(pin);
Check to see if an input pin is reading HIGH (5V) or LOW (0V). Returns TRUE (1) or FALSE (0) depending on the reading.
Is Equal to:
if(digitalRead(firstKeyPin) == LOW)
This is another logical operator. The 'is equal to' symbol (==) can be confusing. Two equals signs are equivalent to asking, "Are these two values equal to one another?" On the other hand, one equals sign in code is assigning a particular variable to a value. Don't forget to add the second equals sign if you are comparing two values.

Coding Challenges

ChallengeDescription
Change the key of each buttonUse the frequency table in the comment section at the end of the code to change the notes that each button plays.
Play more than three notes with if statementsBy using combinations of buttons, you can play up to seven notes of the scale. You can do this in a few ways. To get more practice with if statements, try adding seven if statements and using the Boolean AND (&&) operator to represent all of the combinations of keys.
Play more than three notes with binary mathYou can use a clever math equation to play more than three notes with your three keys. By multiplying each key by a different number, then adding up all of these numbers, you can make a math equation that produces a different number for each combination of keys.

Troubleshooting

ProblemSolution
The buzzer is too loud or too quietTurn the potentiometer to adjust the volume.
The RedBoard thinks one key is always pressedCheck your wiring. You may have ground and 5V backward if one or more buttons behave as though they're pressed all the time.
The buttons are not workingFirst, make sure that the wiring is correct. It is easy to misalign a wire with a button leg. Second, make sure that you have declared your buttons as inputs and have enabled the internal pull-up resistors with INPUT_PULLUP.

Circuit 2C: Simon Says Game

The Simon Says game uses LEDs to flash a pattern, which the player must remember and repeat using four buttons. The classic Simon game has been a hit since the 1980s. Now you can build your own!

Project2_Circuit2C_Hero

Parts Needed

Grab the following quantities of each part listed to build this circuit:

parts

New Concepts

For Loops

For loops repeat a section of code a set number of times. The loop works by using a counter (usually programmers use the letter “i” for this variable) that increases each loop until it reaches a stop value. Here’s an example of a simple for loop:

language:c
for (int i = 0; i < 5; i++){
    Serial.print(i);
}

The for loop takes three parameters in the brackets, separated by semicolons. The first parameter is the start value. In this case, integer i starts at 0. The second value is the stop condition. In this case, we stop the loop when i is no longer less than 5 (i < 5 is no longer true). The final parameter is an increment value. i++ is shorthand for increase i by 1 each time, but you could also increase i by different amounts. This loop would repeat five times. Each time it would run the code in between the brackets, which prints the value of i to the serial monitor.

Measuring Durations of Time With millis()

The RedBoard has a built-in clock that keeps accurate time. You can use the millis() command to see how many milliseconds have passed since the RedBoard was last powered. By storing the time when an event happens and then subtracting the current time, you can measure the number of milliseconds (and thus seconds) that have passed. This sketch uses this function to set a time limit for repeating the pattern.

Custom Functions

This sketch uses several user-defined functions. These functions perform operations that are needed many times in the program (for example, reading which button is currently pressed or turning all of the LEDs off). Functions are essential to make more complex programs readable and compact.

Hardware Hookup

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

Circuit Diagram

Circuit_2C_SimonSays

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

ComponentRedBoardBreadboardBreadboardBreadboard
J1 (Buzzer + )J3 (Buzzer - )
PotentiometerB1B2B3
Jumper WireGNDGND Rail ( - )
Jumper WireDigital Pin 10F1
Jumper WireE2GND Rail ( - )
Jumper WireE1F3
Push ButtonD10/D12G10/G12
Push ButtonD16/D18G16/G18
Push ButtonD22/D24G22/G24
Push ButtonD28/D30G28/G30
Jumper WireDigital Pin 8J12
Jumper WireDigital Pin 6J18
Jumper WireDigital Pin 4J24
Jumper WireDigital Pin 2J30
Jumper WireJ10GND Rail ( - )
Jumper WireJ16GND Rail ( - )
Jumper WireJ22GND Rail ( - )
Jumper WireJ28GND Rail ( - )
H7 LED ( + )H8 LED ( - )
H13 LED ( + )H14 LED ( - )
H19 LED ( + )H20 LED ( - )
H25 LED ( + )H26 LED ( - )
Jumper WireDigital Pin 9J7
Jumper WireDigital Pin 7J13
Jumper WireDigital Pin 5J19
Jumper WireDigital Pin 3J25
330Ω Resistor
(orange, orange, brown)
J8GND Rail ( - )
330Ω Resistor
(orange, orange, brown)
J14GND Rail ( - )
330Ω Resistor
(orange, orange, brown)
j20GND Rail ( - )
330Ω Resistor
(orange, orange, brown)
J26GND Rail ( - )

In the table, polarized components are shown with a warning triangle and the whole row highlighted yellow.

Open the Sketch

To open the code, go to: File > Examples > SIK_Guide_Code-V_4 > SIK_Circuit_2C-SimonSays

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
Circuit 2C-Simon Says

The Simon Says game flashes a pattern using LED lights, then the player must repeat the pattern.

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v40
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
*/

//set the pins where the butons, LEDs and buzzer connect
int button[] = {2,4,6,8};     //red is button[0], yellow is button[1], green is button[2], blue is button[3]
int led[] = {3,5,7,9};        //red is led[0], yellow is led[1], green is led[2], blue is led[3]
int tones[] = {262, 330, 392, 494};   //tones to play with each button (c, e, g, b)

int roundsToWin = 10;         //number of rounds the player has to play before they win the game (the array can only hold up to 16 rounds)
int buttonSequence[16];       //make an array of numbers that will be the sequence that the player needs to remember

int buzzerPin = 10;           //pin that the buzzer is connected to

int pressedButton = 4;        //a variable to remember which button is being pressed. 4 is the value if no button is being pressed.
int roundCounter = 1;         //keeps track of what round the player is on


long startTime = 0;           //timer variable for time limit on button press
long timeLimit = 2000;        //time limit to hit a button

boolean gameStarted = false;      //variable to tell the game whether or not to play the start sequence

void setup(){

  //set all of the button pins to input_pullup (use the builtin pullup resistors)
  pinMode(button[0], INPUT_PULLUP);
  pinMode(button[1], INPUT_PULLUP);
  pinMode(button[2], INPUT_PULLUP);
  pinMode(button[3], INPUT_PULLUP);

  //set all of the LED pins to output
  pinMode(led[0], OUTPUT);
  pinMode(led[1], OUTPUT);
  pinMode(led[2], OUTPUT);
  pinMode(led[3], OUTPUT);

  pinMode(buzzerPin, OUTPUT);   //set the buzzer pin to output
}

void loop(){

if (gameStarted == false){    //if the game hasn't started yet
  startSequence();            //flash the start sequence
  roundCounter = 0;           //reset the round counter
  delay(1500);                //wait a second and a half
  gameStarted = true;         //set gameStarted to true so that this sequence doesn't start again
}

//each round, start by flashing out the sequence to be repeated
for(int i=0; i <= roundCounter; i++){   //go through the array up to the current round number
  flashLED(buttonSequence[i]);          //turn on the LED for that array position and play the sound
  delay(200);                           //wait
  allLEDoff();                          //turn all of the LEDs off
  delay(200);
}

//then start going through the sequence one at a time and see if the user presses the correct button
for(int i=0; i <= roundCounter; i++){   //for each button to be pressed in the sequence

  startTime = millis();                 //record the start time

  while(true){  //loop until the player presses a button or the time limit is up (the time limit check is in an if statement)

    pressedButton = buttonCheck();      //every loop check to see which button is pressed

    if (pressedButton < 4){             //if a button is pressed... (4 means that no button is pressed)

      flashLED(pressedButton);          //flash the LED for the button that was pressed

      if(pressedButton == buttonSequence[i]){   //if the button matches the button in the sequence
          delay(250);                   //leave the LED light on for a moment
          allLEDoff();                  //then turn off all of the lights and
          break;                        //end the while loop (this will go to the next number in the for loop)

      } else{                           //if the button doesn't match the button in the sequence
          loseSequence();               //play the lose sequence (the loose sequence stops the program)
          break;                        //when the program gets back from the lose sequence, break the while loop so that the game can start over
      }

    } else {                            //if no button is pressed
      allLEDoff();                      //turn all the LEDs off
    }

    //check to see if the time limit is up
    if(millis() - startTime > timeLimit){   //if the time limit is up
      loseSequence();                       //play the lose sequence
      break;                                //when the program gets back from the lose sequence, break the while loop so that the game can start over
    }
  }
}

  roundCounter = roundCounter + 1;      //increase the round number by 1

  if (roundCounter >= roundsToWin){               //if the player has gotten to the 16th round
    winSequence();                      //play the winning song
  }

  delay(500);                           //wait for half a second between rounds


}

//----------FUNCTIONS------------

//FLASH LED
void flashLED (int ledNumber){
  digitalWrite(led[ledNumber], HIGH);
  tone(buzzerPin, tones[ledNumber]);
}

//TURN ALL LEDS OFF
void allLEDoff (){
  //turn all the LEDs off
  digitalWrite(led[0],LOW);
  digitalWrite(led[1],LOW);
  digitalWrite(led[2],LOW);
  digitalWrite(led[3],LOW);
  //turn the buzzer off
  noTone(buzzerPin);
}

//CHECK WHICH BUTTON IS PRESSED
int buttonCheck(){
  //check if any buttons are being pressed
  if(digitalRead(button[0]) == LOW){
    return 0;
  }else if(digitalRead(button[1]) == LOW){
    return 1;
  }else if(digitalRead(button[2]) == LOW){
    return 2;
  }else if(digitalRead(button[3]) == LOW){
    return 3;
  }else{
    return 4; //this will be the value for no button being pressed
  }
}

//START SEQUENCE
void startSequence(){

  randomSeed(analogRead(A0));   //make sure the random numbers are really random

  //populate the buttonSequence array with random numbers from 0 to 3
  for (int i=0;i<=roundsToWin;i++){
    buttonSequence[i] = round(random(0,4));
  }

  //flash all of the LEDs when the game starts
  for(int i=0; i<=3; i++){

    tone(buzzerPin, tones[i], 200); //play one of the 4 tones

    //turn all of the leds on
    digitalWrite(led[0],HIGH);
    digitalWrite(led[1],HIGH);
    digitalWrite(led[2],HIGH);
    digitalWrite(led[3],HIGH);

    delay(100);         //wait for a moment

    //turn all of the leds off
    digitalWrite(led[0],LOW);
    digitalWrite(led[1],LOW);
    digitalWrite(led[2],LOW);
    digitalWrite(led[3],LOW);

    delay(100);   //wait for a moment

  } //this will repeat 4 times
}

//WIN SEQUENCE
void winSequence(){

  //turn all the LEDs on
  for(int j=0; j<=3; j++){
    digitalWrite(led[j], HIGH);
  }

  //play the 1Up noise
  tone(buzzerPin, 1318, 150);   //E6
  delay(175);
  tone(buzzerPin, 1567, 150);   //G6
  delay(175);
  tone(buzzerPin, 2637, 150);   //E7
  delay(175);
  tone(buzzerPin, 2093, 150);   //C7
  delay(175);
  tone(buzzerPin, 2349, 150);   //D7
  delay(175);
  tone(buzzerPin, 3135, 500);   //G7
  delay(500);

  //wait until a button is pressed
  do {
    pressedButton = buttonCheck();
  } while(pressedButton > 3);
  delay(100);

  gameStarted = false;   //reset the game so that the start sequence will play again.

}

//LOSE SEQUENCE
void loseSequence(){

  //turn all the LEDs on
  for(int j=0; j<=3; j++){
    digitalWrite(led[j], HIGH);
  }

  //play the 1Up noise
  tone(buzzerPin, 130, 250);   //E6
  delay(275);
  tone(buzzerPin, 73, 250);   //G6
  delay(275);
  tone(buzzerPin, 65, 150);   //E7
  delay(175);
  tone(buzzerPin, 98, 500);   //C7
  delay(500);

  //wait until a button is pressed
  do {
    pressedButton = buttonCheck();
  } while(pressedButton > 3);
  delay(200);

  gameStarted = false;   //reset the game so that the start sequence will play again.
}

What You Should See

The circuit will flash all of the LEDs and play a melody. After a few seconds, it will flash the first light in the pattern. If you repeat the pattern correctly by pressing the corresponding colored button, then the game will move to the next round and add another color to the pattern sequence. If you make a mistake, the loss melody will play. If you get to round 10, the win melody will play. Press any button to start a new game.

Project2_Circuit2C_Action

Program Overview

  1. Check if a new game is starting. If it is, play the start sequence. Reset the counter that keeps track of rounds, and randomly generate a sequence of numbers from 0 to 3 that control which LEDs the user will have to remember.
  2. The game works in rounds that progress from 0 to 10. Each round the game will flash LEDs in a pattern, then the player has to recreate the pattern by pressing the button(s) that match the LED(s). In the first round, one LED will flash, and the player will have to press one button. In the eighth round, eight LEDs will flash, and the player will have to press eight buttons.
  3. Use a loop to flash LEDs from the sequence until you have flashed the number of LEDs that matches the round number (1 for round 1, 2 for round 2, etc).
  4. Start a timer, and wait for the player to press a button. The player has 1.5 seconds to press the correct button.
    1. If the time limit runs out before a button is pressed, the player loses.
    2. If the player presses the wrong button, the player loses.
    3. If the player presses the right button, move on to the next number in the sequence.
    4. Repeat this process until the player has lost or correctly repeated the sequence for this round.
  5. If the player repeats the entire sequence for that round. Increase the round number by one (this will add one extra item to the end of the pattern). Then go back to step 3.
  6. Keep incrementing the round until the player loses or the player finishes 10 rounds. If the player finishes 10 rounds, play the winning sequence.

Code to Note

CodeDescription
Elapsed Time:
millis();
The millis function returns the number of milliseconds that have passed since the RedBoard was last turned on.
Boolean Variables:
boolean variable_name;
The name for these variables comes from Boolean logic. The Boolean variable type only has two values: 1 or 0, HIGH or LOW, TRUE or FALSE. Using Boolean variables helps save memory on your microcontroller if you only need to know if something is true or false. Space in your microcontroller's memory is reserved when a variable is declared. How much memory is reserved depends on the type of variable.
Storing pin numbers in Arrays:
int led[] = {3,5,7,9};
Sometimes you will want to cycle through all of the LEDs or buttons connected to a project. You can do this by storing a sequence of pin numbers in an array. The advantage of having pins in an array instead of a sequence of variables is that you can use a loop to easily cycle through each pin.
User Functions Description
flashLED(# for LED to flash);This turns one of the four LEDs on and plays the tone associated with it.
0 = Red, 1 = Yellow, 2 = Green, 3 = Blue.
allLEDoff();Turns all four LEDs off.
buttonCheck();Uses digitalRead() to check which button is pressed. Returns 0, 1, 2 or 3 if one of the buttons is pressed. Returns 4 if no button is pressed.
startSequence();Flashes the LEDs and plays tones in a sequence. Resets the round counter and generates a new random sequence for the user to remember.
winSequence();Plays a sequence of tones, turns all of the LEDs on, then waits for the player to press a button. If a button is pressed, restarts the game.
loseSequence();Plays a sequence of tones, turns all of the LEDs on, then waits for the player to press a button. If a button is pressed, restarts the game.

Coding Challenges

ChallengeDescription
Change the difficulty of the gameChange the difficulty of the game by changing how fast the player has to press each button or by increasing or decreasing the number of rounds needed to win. Note that if you increase the number of rounds to be larger than 16, you will need to change the size of the “buttonSequence” array (it is set at the top of the code in a line that looks like this: int buttonSequence[16];.
Change the sound effectsTry changing the sequence of notes that play when you start, win or lose the game.
2-Player modeReady for a real coding challenge? Try changing the code so that two players can play head-to-head.

Troubleshooting

ProblemSolution
One of the LEDs isn’t lighting upMake sure your LED is flipped around in the right direction. If the LED still doesn’t work, try wiggling the resistor and the wires that connect to the LED.
The buzzer is too loud or too quietTurn the potentiometer to adjust the volume
One of the buttons isn’t workingCarefully check your wiring for each button. One leg of the button should connect to a pin on the RedBoard; the other leg should connect to the ground rail on the breadboard.
None of the buttons or LEDs is workingMake sure you don't have 5V and GND mixed up. Double check that you have a GND connection from the RedBoard to the GND rail on the breadboard.
Still not working?Jumper wires unfortunately can go "bad" from getting bent too much. The copper wire inside can break, leaving an open connection in your circuit. If you are certain that your circuit is wired correctly and that your code is error-free and uploaded, but you are still encountering issues, try replacing one or more of the jumper wires for the component that is not working.

Project 3: Motion

Tired of your cat walking all over the kitchen counter? How about the dog getting into the garbage? Need a way to stop your little brother from sneaking into your bedroom? Learn how to protect against all of these annoyances as you build a multipurpose alarm. The alarm detects distance and motion using an ultrasonic distance sensor, and creates motion using a servo motor.

Project 3

New Components Introduced in This Project

Each of the components listed below will be described in more detail as you progress through each circuit.

  • Servo Motor
  • Ultrasonic Distance Sensor

New Concepts Introduced in This Project

Each of the concepts listed below will be described in more detail as you progress through each circuit.

  • PWM Duty Cycle
  • Arduino Libraries
  • Objects and Methods
  • Datasheets
  • Digital Sensors
  • Servo Mechanisms

You Will Learn

  • How to control a servo motor
  • How to use an ultrasonic distance sensor
  • How to move objects using servo mechanisms

Circuit 3A: Servo Motors

In this circuit, you will learn how to wire a servo and control it with code. Servo motors can be told to move to a specific position and stay there. Low-cost servo motors were originally used to steer remote-controlled airplanes and cars, but they have become popular for any project where precise movement is needed.

Project3_Circuit3A_Hero

Parts Needed

Grab the following quantities of each part listed to build this circuit:

parts

Additional Materials

  • Scissors (NOT INCLUDED)

New Components

Servo Motors

Regular DC motors have two wires. When you hook the wires up to power, the motor spins around and around. Servo motors, on the other hand, have three wires: one for power, one for ground and one for signal. When you send the right signal through the signal wire, the servo will move to a specific angle and stay there. Common servos rotate over a range of 0° to 180°. The signal that is sent is a PWM signal, the same used to control the RGB LED in Project 1.

servo motor

New Concepts

Duty Cycle

The Pulse Width Modulation (PWM) hardware available on a microcontroller is a great way to generate servo control signals. When talking about how long a PWM signal is on, this is referred to as duty cycle. Duty cycle is measured in percentage. The percentage of duty cycle specifically describes the percentage of time a digital signal is on over an interval or period of time. The variation in the duty cycle tells the servo which position to go to in its rotation.

Duty Cycle Percentage reflects percentage of 'on' time per interval

50%, 75% and 25% duty cycle examples

Arduino Libraries

Writing code that sends precise PWM signals to the servo would be time consuming and would require a lot more knowledge about the servo. Luckily, the Arduino IDE has hundreds of built-in and user-submitted containers of code that are called libraries. One of the built-in libraries, the Servo Library, allows us to control a servo with just a few lines of code!

To use one of the built-in Arduino libraries, all you have to do is “include” a link to its header file. A header file is a smaller code file that contains definitions for all the functions used in that library. By adding a link to the header file in your code, you are enabling your code to use all of those library functions. To use the Servo Library, you would add the following line to the top of your sketch.

language:cpp
#include <Servo.h>

Objects and Methods

To use the Servo Library, you will have to start by creating a servo object, like this:

language:cpp
Servo myServo;

Objects look a lot like variables, but they can do much more. Objects can store values, and they can have their own functions, which are called methods.

The most used method that a servo object has is .write().

language:cpp
myServo.write(90);

The write method takes one parameter, a number from 0 to 180, and moves the servo arm to the specified position (in this case, degree 90).

Why would we want to go to the trouble of making an object and a method instead of just sending a servo control signal directly over a pin? First, the servo object does the work of translating our desired position into a signal that the servo can read. Second, using objects makes it easy for us to add and control more than one servo.

Hardware Hookup

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.

Servo motor connectors are polarized, but there is no place to attach them directly. Instead, connect three jumper wires to the female 3-pin header on the servo. This will make it so you can connect the servo to the breadboard.

Servo Jumpers

The servo wires are color coded to make hookup simple. The pin-out is as follows:

PinDescription
WhiteSignal - PWM In
RedPower (5V)
BlackGround (GND)

Included with your servo motor you will find a variety of motor mounts that connect to the shaft of your servo. You may choose to attach any mount you wish for this circuit. It will serve as a visual aid, making it easier to see the servo spin. The mounts will also come in handy at the end of this project.

motor mounts

The various motor mounts included with your servo motor

Affix the Servo (optional)

Included in your SIK is a strip of Dual Lock™. Cut a piece off the strip that is about &frac58; inch or 1.6cm. Then cut that strip in half to get two pieces that are roughly &frac58; inch x ½ inch or 1.6cm x 1.3cm.

Dual_Lock_Cutting

Peel off the adhesive backing, and stick one half on the bottom of the servo motor.

Dual_Lock_Servo

Stick the other half anywhere on the breadboard baseplate you want. Firmly press the bottom of the servo to the baseplate to temporarily adhere the two pieces of Dual Lock together. This will help stabilize the servo motor as it moves about.

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

Circuit Diagram

Circuit_3A

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

ComponentRedBoardBreadboardBreadboardBreadboardServo
PotentiometerB1B2B3
Jumper WireAnalog Pin 0E2
Jumper WireE15V Rail ( + )
Jumper WireE3GND Rail ( - )
Jumper Wire5V5V Rail ( + )
Jumper WireGNDGND Rail ( - )
Jumper WireDigital Pin 9White Servo Pin
Jumper Wire5V Rail ( + )Red Servo Pin
Jumper WireGND Rail ( - )Black Servo Pin

In the table, polarized components are shown with a warning triangle and the whole column highlighted yellow.

Open the Sketch

To open the code, go to: File > Examples > SIK_Guide_Code-V_4 > SIK_Circuit_3A-Servo.

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
Circuit 3A-Servo

Move a servo attached to pin 9 so that it's angle matches a potentitometer attached to A0.

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v40
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
 */

#include <Servo.h>          //include the servo library

int potPosition;           //this variable will store the position of the potentiometer
int servoPosition;         //the servo will move to this position

Servo myservo;              //create a servo object

void setup() {

  myservo.attach(9);        //tell the servo object that its servo is plugged into pin 9

}

void loop() {



  potPosition = analogRead(A0);                     //use analog read to measure the position of the potentiometer (0-1023)

  servoPosition = map(potPosition, 0,1023,20,160);  //convert the potentiometer number to a servo position from 20-160
                                                    //Note: its best to avoid driving the little SIK servos all the
                                                    //way to 0 or 180 degrees it can cause the motor to jitter, which is bad for the servo.

  myservo.write(servoPosition);                      //move the servo to the 10 degree position
}

What You Should See

Turning the potentiometer will cause the servo to turn.

Project3_Circuit3A_Action

Program Overview

  1. Read the value of the potentiometer.
  2. Convert the potentiometer value (0–1023) to an angle (20–160).
  3. Tell the servo to go to this angle.

Code to Note

CodeDescription
Including Libraries:
#include <Servo.h>
The #include command adds a library to your Arduino program. After you include a library, you can use the commands in the library in your program. This line adds the Servo library.
Creating Servo Objects:
Servo myServo;
The Servo command creates a new servo object and assigns a name to it, myServo in this case. If you make more than one servo object, you will need to give them different names.
Servo Attach:
myServo.attach(9);
The .attach() method tells the servo object to which pin the signal wire of its servo is attached. It will send position signals to this pin. In this sketch, pin 9 is used. Remember to only use digital pins that are capable of PWM.
Range Mapping:
map(potPosition, 0,1023,20,160);
As shown in previous circuits, the analog pin values on your microcontroller vary from 0-1023. However, what if we want those values to control a servo motor that only accepts a value from 0-180? The answer is to use the map function. The map() function takes a range of values and outputs a different range of values that can contain more or less values than the original. In this case, we are taking the range 0-1023 and mapping it to the range 20-160.
Servo Write:
myServo.write(90);
The .write() method moves the servo to a specified angle. In this example, the servo is being told to go to angle 90.

Coding Challenges

ChallengeDescription
Reverse the directionTry making the servo move in the opposite direction to the potentiometer.
Change the rangeTry altering the map function so that moving the potentiometer a lot only moves the servo a little.
Swap in a different sensorTry swapping a light sensor in for the potentiometer. You have just made a dial that reads how much light is present!

Troubleshooting

ProblemSolution
The servo doesn’t moveCheck the wiring on your servo. Make sure that the red wire on the servo cord is connected to 5V, the black wire is connected to GND and the white signal wire is connected to pin 9.
The servo is twitchingAlthough these servos are supposed to move from 0 to 180 degrees, sometimes sending them to the extremes of their range causes them to twitch (the servo is trying to move farther than it can). Make sure that you aren’t telling the servo to move outside of the 20-160 degree range.

Circuit 3B: Distance Sensor

Distance sensors are amazing tools with all kinds of uses. They can sense the presence of an object, they can be used in experiments to calculate speed and acceleration, and they can be used in robotics to avoid obstacles. This circuit will walk you through the basics of using an ultrasonic distance sensor, which measures distance using sound waves!

Project3_Circuit3B_Hero

Parts Needed

Grab the following quantities of each part listed to build this circuit:

parts

Need Ultrasonic Distance Sensor image for parts list

New Components

Ultrasonic Distance Sensor

Distance sensors work by sending pulses of light or sound out from a transmitter, then timing how long it takes for the signals to bounce off an object and return to a receiver (just like sonar). Some sensors use infrared light, some use lasers, and some, like the HC-SR04 included in your kit, use ultrasonic sound (sound so high-pitched that you can’t hear it).

distance sensor

New Concepts

Datasheets

When working with electronics, datasheets are your best friend. Datasheets contain all the relevant information needed to get you up and running with a part. In this circuit, we are calculating distance based on the time it takes sound waves to be transmitted, bounce off an object and then be received. But, how can we tell distance from that information? The answer lies in the datasheet for the distance sensor. In it, you can find the equation the program needs to interpret distance from the time it takes the sound wave to travel.

Else If Statement

In the night-light circuit, you used an if/else statement to run one set of code when a logic statement was true, and a different set of code when it was false. What if you wanted to have more than two options? Else if statements let you run as many logical tests as you want in one if statement. For example, in the code for this circuit, there is an if statement that flows like this:

  1. If the distance is less than 10, make the RGB LED red.
  2. Else if the distance is more than 10 but less than 20, make the RGB LED yellow.
  3. Else make the RGB LED green.

If you wanted to have four or five colors for different distances, you could add more else if statements.

Else if statements are different from nested if statements in that only one of the statements above can be true, whereas you could have multiple nested if statements that could true.

Hardware Hookup

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.

The distance sensor is polarized. Take note of the pin labels when connecting your circuit.

distance sensor pinout

The following table describes the function of each pin on the distance sensor:

PinDescription
VCCPower (5V)
TrigTrigger Pulse Input: Sends bursts of ultrasound at 40kHz.
EchoEcho Pulse Output: Receives echo signal. Range is calculated by the proportion of trigger signal sent and echo signal received.
GNDGround (0V)

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

Circuit Diagram

Circuit_3B

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

ComponentRedBoardBreadboardBreadboardBreadboardBreadboard
Jumper Wire5V5V Rail ( + )
Jumper WireGNDGND Rail ( - )
A25 (RED)A24 (GND)A23 (GREEN)A22 (BLUE)
330Ω Resistor
(orange, orange, brown)
E22F22
330Ω Resistor
(orange, orange, brown)
E23F23
330Ω Resistor
(orange, orange, brown)
E25F25
Jumper WireE24GND Rail ( - )
Jumper WireDigital Pin 3J25
Jumper WireDigital Pin 5J23
Jumper WireDigital Pin 6J22
A3 (Vcc)A4 (Trig)A5 (Echo)A6 (GND)
Jumper WireDigital Pin 11E4 (Trig)
Jumper WireDigital Pin 12E5 (Echo)
Jumper WireE35V Rail ( + )
Jumper WireE6GND Rail ( - )

In the table, polarized components are shown with a warning triangle and the whole row highlighted yellow.

Open the Sketch

To open the code, go to: File > Examples > SIK_Guide_Code-V_4 > SIK_Circuit_3B-DistanceSensor

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
Circuit 3B-Distance Sensor

Control the color of an RGB LED using an ultrasonic distance sensor.

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v40
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
*/

const int trigPin = 11;           //connects to the echo pin on the distance sensor
const int echoPin = 12;           //connects to the trigger pin on the distance sensor

const int redPin = 3;             //pin to control the red LED inside the RGB LED
const int greenPin = 5;           //pin to control the green LED inside the RGB LED
const int bluePin = 6;            //pin to control the blue LED inside the RGB LED

float distance = 0;               //stores the distance measured by the distance sensor

void setup()
{
  Serial.begin (9600);        //set up a serial connection with the computer

  pinMode(trigPin, OUTPUT);   //the trigger pin will output pulses of electricity
  pinMode(echoPin, INPUT);    //the echo pin will measure the duration of pulses coming back from the distance sensor

  //set the RGB LED pins to output
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
}

void loop() {
  distance = getDistance();   //variable to store the distance measured by the sensor

  Serial.print(distance);     //print the distance that was measured
  Serial.println(" in");      //print units after the distance

  if(distance <= 10){                         //if the object is close

    //make the RGB LED red
    analogWrite(redPin, 255);
    analogWrite(greenPin, 0);
    analogWrite(bluePin, 0);

  } else if(10 < distance && distance < 20){  //if the object is a medium distance

    //make the RGB LED yellow
    analogWrite(redPin, 255);
    analogWrite(greenPin, 50);
    analogWrite(bluePin, 0);

  } else{                                     //if the object is far away

    //make the RGB LED green
    analogWrite(redPin, 0);
    analogWrite(greenPin, 255);
    analogWrite(bluePin, 0);
  }

  delay(50);      //delay 50ms between each reading
}

//------------------FUNCTIONS-------------------------------

//RETURNS THE DISTANCE MEASURED BY THE HC-SR04 DISTANCE SENSOR
float getDistance()
{
  float echoTime;                   //variable to store the time it takes for a ping to bounce off an object
  float calcualtedDistance;         //variable to store the distance calculated from the echo time

  //send out an ultrasonic pulse that's 10ms long
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  echoTime = pulseIn(echoPin, HIGH);      //use the pulsein command to see how long it takes for the
                                          //pulse to bounce back to the sensor

  calcualtedDistance = echoTime / 148.0;  //calculate the distance of the object that reflected the pulse (half the bounce time multiplied by the speed of sound)

  return calcualtedDistance;              //send back the distance that was calculated
}

What You Should See

Move your hand or a large, flat object closer and farther away from the distance sensor. As the object approaches, the light will change from green to yellow to red.

Project3_Circuit3B_Action

Open the Serial Monitor, and you should see the distance printed to the window.

Troubleshooting Warning: HVAC systems in offices and schools have been known to interfere with the performance of the ultrasonic distance sensor. If you are experiencing sporadic behavior from your circuit, check your surroundings. If there are numerous air ducts in the room you are using, try moving to a different room that does not have ducts. The airflow from these ducts can interfere with the waves sent from the sensor, creating noise and resulting in bad readings.

Program Overview

  1. Check what distance the sensor is reading.
    1. If the distance is less than 10 inches, make the RGB LED red.
    2. If the distance is between 10 and 20 inches, make the RGB LED yellow.
    3. If the distance value is not equal to the fist two conditions, make the RGB LED green.

Code to Note

CodeDescription
Float Variables:
float echoTime;
The float variable, short for floating-point number, is similar to an integer except it can represent numbers that contain a decimal point. Floats are good for representing values that need to be more precise than an int. Floats allow us to measure precise distances such as 9.33 inches instead of just 9 inches.
Else if Statement:
if(logic statement){
code to run if logic statement
is true }
else if(second logic statement){
code to run if the second logic
statement is true }

else(default logic statement){
code to run if neither of the first
two statements are true }
Else if statements let you combine more than one logic statement. Arduino will test each logic statement in order; if one is true it will run the code in that section and then skip all of the other sections of code in the if statement.
User-Defined Function:
getDistance();
This function tells the distance sensor to send out an ultrasonic wave form, measures the time it takes to bounce back to the sensor, then calculates the distance based on the speed of sound. This calculation is based off information found in the distance sensor's datasheet.

Coding Challenges

ChallengeDescription
Change the limits of the distance sensorTry editing the values in the logic statements so that the RGB LED changes color at different distances.
Change the units of the distance sensorTry editing the code so that the distance sensor outputs a different unit of length, such as centimeters or feet.
Add a fourth colorTry adding another else if statement so that there are four different colors instead of three.

Troubleshooting

ProblemSolution
The RGB LED colors aren't working or a color is missingCheck the connection for the wire and resistor connected to each leg of the LED. Ensure the RGB LED is inserted in the correct orientation.
The distance sensor doesn’t seem to workOpen up the serial monitor on your computer. You should see a stream of distances being printed in the monitor. If they are all reading 0 or jump around, then check the wiring on your sensor.
The distance sensor still doesn’t workUltrasonic noise pollution will interfere with your distance sensor readings. If you aim two distance sensors at each other, they will confuse each other. Some air-conditioning systems may also emit noises in the ultrasonic range. Try pointing your sensor away from the other distance sensors or changing to a different location.

Circuit 3C: Motion Alarm

Time to take your distance sensor project to the next level. Let’s imagine that you want to stop your cat from prowling around your countertop. This circuit will use light, sound and motion to scare away your cat when it is detected by the distance sensor. Using a servo motor, you can add a moving pop-up to animate your alarm.

Don’t have a cat? No problem! This circuit can be adapted for a variety of projects such as a room alarm, an automated pop-up story, an automatic treat dispenser and so much more. Let your imagination run wild with this project.

Project3_Circuit3C

Parts Needed

Grab the following quantities of each part listed to build this circuit:

parts

Need Ultrasonic Distance Sensor image for parts list

Additional Materials (NOT INCLUDED)

The following materials are optional. The circuit can be completed without these items.

  • Paper
  • Scissors
  • Scotch™ Tape
  • Markers/Pen
  • Paper Clip
  • Needle-Nose Pliers

New Concepts

Getting Creative With Mechanisms

This circuit gets really fun when you start to use your servo to animate the world around you. To do this, you’ll need to connect your servo to some physical mechanisms. Tape and hot glue are easy ways to connect things to your servo. You can also loop a paper clip through the small holes in the servo arm to serve as a linkage. See the Hardware Hookup section below for more information.

RC Airplane servo

Linkage rods are found on many RC airplanes, which use servo motors to control the ailerons, elevators and rudder.

Hardware Hookup

If you have opted for the extra materials, use the following instructions to create the moving pop-up for your cat alarm.

To begin, attach your servo to the baseplate using Dual Lock, as described in Circuit 3A.

Attach the servo mount of your choice. It is recommended you wait until after you have uploaded your code to ensure the mount is in the best position before screwing on the mount. The screw is optional, but it will make for a more robust mechanism.

Servo mount

Next, use needle-nose pliers to bend the paper clip straight. Imagine a 3D space. The straight clip is the X-axis. Bend one end of the paper clip 90 degrees along the Y-axis. The bent segment should be about 1 inch or 2.5cm long. Then bend the other end along the Z-axis. This bend should be about 1/8 inch or 3mm long. Repeat this bend once more back toward the X-axis, making a hook shape. You should now have a linkage rod that looks something like this:

paper clip

Attach the hook end of the linkage rod to the end hole on your servo mount.

servo linkage

Cut out the pop-up image of your choice. We chose this public domain menacing cat image (http://bit.ly/2vinyE1). The image you choose should be about 2.5 inches x 2.5 inches and can be drawn or printed. Leave a rectangular strip of paper under the image that is about 2 inches long. Fold along the bottom of the image. Tape the pop-up to the underside of the breadbaord baseplate on the same side to which the servo is connected.

tape underneath

Last, tape the free end of the rod to the back of your pop-up image.

pop up taped

Once you have the rest of the circuit built and the code uploaded, you can fine-tune your moving pop-up and make any necessary adjustments. Remember to wait until these adjustments have been made before you screw the servo mount onto the motor.

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

Circuit Diagram

Circuit_3C

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

ComponentRedBoardBreadboardBreadboardBreadboardBreadboardServo
Jumper Wire5V5V Rail ( + )
Jumper WireGNDGND Rail
( - )
A25 (RED)A24 (GND)A23 (GREEN)A22 (BLUE)
330Ω Resistor
(orange, orange, brown)
E22F22
330Ω Resistor
(orange, orange, brown)
E23F23
330Ω Resistor
(orange, orange, brown)
E25F25
Jumper WireE24GND Rail
( - )
Jumper WireDigital Pin 3J25
Jumper WireDigital Pin 5J23
Jumper WireDigital Pin 6J22
A3 (Vcc)A4 (Trig)A5 (Echo)A6 (GND)
Jumper WireDigital Pin 11E4 (Trig)
Jumper WireDigital Pin 12E5 (Echo)
Jumper WireE35V Rail ( + )
Jumper WireE6GND Rail
( - )
F14
(Buzzer +)
F16
(Buzzer -)
Jumper WireDigital Pin 10J14
Jumper WireJ16GND Rail
( - )
Jumper WireDigital Pin 9White Servo Pin
Jumper Wire5V Rail ( + )Red Servo Pin
Jumper WireGND Rail
( - )
Black Servo Pin

In the table, polarized components are shown with a warning triangle and the whole row or whole column highlighted yellow.

Open the Sketch

To open the code, go to: File > Examples > SIK_Guide_Code-V_4 > SIK_Circuit_3C-CatAlarm

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
Circuit 3C-Motion Alarm

Control the color of an RGB LED using an ultrasonic distance sensor. When an object is close to the sensor, buzz the buzzer and wiggle the servo motor.

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v40
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
*/

#include <Servo.h>                //include the servo library

const int trigPin = 11;           //connects to the echo pin on the distance sensor
const int echoPin = 12;           //connects to the trigger pin on the distance sensor

const int redPin = 3;             //pin to control the red LED inside the RGB LED
const int greenPin = 5;           //pin to control the green LED inside the RGB LED
const int bluePin = 6;            //pin to control the blue LED inside the RGB LED

const int buzzerPin = 10;         //pin that will drive the buzzer

float distance = 0;               //stores the distance measured by the distance sensor

Servo myservo;                    //create a servo object

void setup()
{
  Serial.begin (9600);        //set up a serial connection with the computer

  pinMode(trigPin, OUTPUT);   //the trigger pin will output pulses of electricity
  pinMode(echoPin, INPUT);    //the echo pin will measure the duration of pulses coming back from the distance sensor

  //set the RGB LED pins to output
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);

  pinMode(buzzerPin, OUTPUT);   //set the buzzer pin to output

  myservo.attach(9);            //use pin 9 to control the servo

}

void loop() {
  distance = getDistance();   //variable to store the distance measured by the sensor

  Serial.print(distance);     //print the distance that was measured
  Serial.println(" in");      //print units after the distance

  if(distance <= 10){                         //if the object is close

    //make the RGB LED red
    analogWrite(redPin, 255);
    analogWrite(greenPin, 0);
    analogWrite(bluePin, 0);

    //this code wiggles the servo and beeps the buzzer
    tone(buzzerPin, 272);         //buzz the buzzer pin
    myservo.write(45);            //move the servo to 45 degrees
    delay(100);                   //wait 100 milliseconds

    noTone(buzzerPin);            //turn the buzzer off
    myservo.write(135);           //move the servo to 135 degrees
    delay(100);                   //wait 100 milliseconds


  } else if(10 < distance && distance < 20){  //if the object is a medium distance

    //make the RGB LED yellow
    analogWrite(redPin, 255);
    analogWrite(greenPin, 50);
    analogWrite(bluePin, 0);

  } else{                                     //if the object is far away

    //make the RGB LED green
    analogWrite(redPin, 0);
    analogWrite(greenPin, 255);
    analogWrite(bluePin, 0);
  }

  delay(50);      //delay 50ms between each reading
}

//------------------FUNCTIONS-------------------------------

//RETURNS THE DISTANCE MEASURED BY THE HC-SR04 DISTANCE SENSOR
float getDistance()
{
  float echoTime;                   //variable to store the time it takes for a ping to bounce off an object
  float calcualtedDistance;         //variable to store the distance calculated from the echo time

  //send out an ultrasonic pulse that's 10ms long
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  echoTime = pulseIn(echoPin, HIGH);      //use the pulsein command to see how long it takes for the
                                          //pulse to bounce back to the sensor

  calcualtedDistance = echoTime / 148.0;  //calculate the distance of the object that reflected the pulse (half the bounce time multiplied by the speed of sound)

  return calcualtedDistance;              //send back the distance that was calculated
}

What You Should See

The RGB LED will behave as in your last circuit. It will be green when objects are far, yellow when they are midrange and red when they are close. When an object is close the buzzer will also beep, and the servo will rotate back and forth.

Project3_Circuit3C_Action

Troubleshooting Warning: HVAC systems in offices and schools have been known to interfere with the performance of the ultrasonic distance sensor. If you are experiencing sporadic behavior from your circuit, check your surroundings. If there are numerous air ducts in the room you are using, try moving to a different room that does not have ducts. The airflow from these ducts can interfere with the waves sent from the sensor, creating noise and resulting in bad readings.

Program Overview

  1. Check what distance the sensor is reading.
    1. If the distance is less than 10 inches, make the RGB LED red. Then make the servo rotate back and forth and make the buzzer beep.
    2. If the distance is between 10 and 20 inches, make the RGB LED yellow.
    3. If the distance value is not equal to the fist two conditions, make the RGB LED green.

Code to Note

CodeDescription
Constants: const int trigPin = 11; Constants are variables that have been marked as "read-only" and cannot have their value changed as the program progresses. Constants are great for declaring pin number variables that will not change throughout the program.
No Tone Function:
noTone(pin_number);
In circuit 2A you made songs using a buzzer and the tone function, but you gave the tone function three parameters: a pin number, a frequency and a duration. You can leave out the third parameter, and the tone will play until you change it or turn it off. noTone() turns off a pin that has been activated with the tone command.

Coding Challenges

ChallengeDescription
Change the servo behaviorTry changing the way that your servo behaves when the distance sensor is triggered.
Change the alarm settingsTry altering the code so the alarm goes off from much farther or closer distances.
Create a different mechanismTry your hand at making different objects move with your servo motor. Make an interactive pop-up story. Make an automatic fish feeder. Time to use your imagination!

Troubleshooting

ProblemSolution
The RGB LED colors aren't working or a color is missingCheck the connection for the wire and resistor connected to each leg of the LED. Ensure the RGB LED is inserted in the correct orientation.
The distance sensor doesn’t seem to workOpen up the Serial Monitor on your computer. You should see a stream of distances being printed in the monitor. If they are all reading 0 or jumping around, then check the wiring on your sensor.
The distance sensor still doesn’t workUltrasonic noise pollution will interfere with your distance sensor readings. If you aim two distance sensors at each other, they will confuse each other. Some air conditioning systems may also emit noises in the ultrasonic range. Try pointing your sensor away from the other distance sensors or changing to a different location.
The servo doesn’t workMake sure all of your servo wires are connected. Be sure that the black wire is connected to the negative rail and the red wire is connected to the positive rail. Make sure you are using a digital pin that is capable of PWM.
The pop-up is moving too much or not enoughThe two lines of code that pass angles to the servo motor are myservo.write(45); and myservo.write(135);. Try changing these angle values to fine-tune your mechanism.

Project 4: Display

Printing data to the Arduino Serial Monitor is a great way to see data from the RedBoard. But, what if you want to make your project mobile and see sensor values away from your computer? This project will show you how to do exactly that. You’ll learn about liquid crystal displays (LCDs) and how to print things like sensor data and strings of words to the display.

Project 4

New Components Introduced in This Project

Each of the components listed below will be described in more detail as you progress through each circuit.

  • Liquid Crystal Display (LCD)
  • TMP36 Digital Temperature Sensor
  • 4xAA Battery Holder

New Concepts Introduced in This Project

Each of the concepts listed below will be described in more detail as you progress through each circuit.

  • Contrast
  • Pixels
  • Algorithms
  • Button Debouncing
  • Strings
  • Pointers

You Will Learn

  • How to print simple messages to an LCD
  • How to use a temperature sensor
  • How to print sensor data to an LCD
  • How to make an interactive game that incorporates the LCD

Circuit 4A: LCD "Hello, World!"

Printing “Hello, world!” is usually the first thing that programming tutorials will have you do in a new language. This guide starts by blinking an LED, but now we’re going to print out real text using a Liquid Crystal Display (LCD).

Project4_Circuit4A

Parts Needed

Grab the following quantities of each part listed to build this circuit:

parts

New Components

Character Liquid Crystal Display (LCD)

Character LCDs are designed to show a grid of letters, numbers and a few special characters. This makes them great for printing data and showing values. When current is applied to this special kind of crystal, it turns opaque. This is used in a lot of calculators, watches and simple displays. Adding an LCD to your project will make it super portable and allow you to integrate up to 32 characters (16 x 2) of information.

LCD

New Concepts

Contrast

Pin 3 on the LCD controls the contrast and brightness of the LCD. Using a simple voltage divider with a potentiometer, the contrast can be adjusted. As you rotate the knob on the potentiometer, you should notice that the screen will get brighter or darker and that the characters become more visible or less visible. The contrast of LCDs is highly dependent on factors such as temperature and the voltage used to power it. Thus, external contrast knobs are needed for displays that cannot automatically account for temperature and voltage changes.

Pixels

If you look closely at the characters on the LCD, you will notice that they are actually made up of lots of little squares. These little squares are called pixels. The size of displays is often represented in pixels. Pixels make up character space, which is the number of pixels in which a character can exist.

pixel B

Here is a capital letter B as created in pixels. The character space in this example is 6 pixels x 8 pixels.

Hardware Hookup

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.

The LCD has 16 pins, and it is polarized. The pins are numbered from left to right, 1 through 16. The LCD utilizes an extremely common parallel interface LCD driver chip from Hitachi called the HD44780. Thankfully, the Arduino community has developed a library to handle a great deal of the software-to-hardware interface. Below is a list of each of the pins on the LCD.

LCD_pins

Click on the image for a closer look.

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

Circuit Diagram

Circuit_4A

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

ComponentRedBoardBreadboardBreadboardBreadboard
Jumper Wire5V5V Rail ( + )
Jumper WireGNDGND Rail ( - )
A15-A30 (Pin 1 on A15)
Jumper WireE30GND Rail ( - )
Jumper WireE295V Rail ( + )
Jumper WireDigital Pin 8E28
Jumper WireDigital Pin 9E27
Jumper WireDigital Pin 10E26
Jumper WireDigital Pin 11E25
Jumper WireDigital Pin 12E20
Jumper WireE19GND Rail ( - )
Jumper WireDigital Pin 13E18
Jumper WireE165V Rail ( + )
Jumper WireE15GND Rail ( - )
PotentiometerA8A9A10
Jumper WireE9E17
Jumper WireE8GND Rail ( - )
Jumper WireE105V Rail ( + )

In the table, polarized components are shown with a warning triangle and the whole row highlighted yellow.

Open the Sketch

To open the code, go to: File > Examples > SIK_Guide_Code-V_4 > SIK_Circuit_4A-LCDHelloWorld

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
Circuit 4A-HelloWorld

The LCD will display the words "Hello World" and show how many seconds have passed since
the RedBoard was last reset.

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v40
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
*/

#include <LiquidCrystal.h>          //the liquid crystal libarry contains commands for printing to the display

LiquidCrystal lcd(13, 12, 11, 10, 9, 8);   // tell the RedBoard what pins are connected to the display

void setup() {

  lcd.begin(16, 2);                 //tell the lcd library that we are using a display that is 16 characters wide and 2 characters high
  lcd.clear();                      //clear the display
}

void loop() {

  lcd.setCursor(0,0);               //set the cursor to the 0,0 position (top left corner)
  lcd.print("Hello, world!");       //print hello, world! starting at that position

  lcd.setCursor(0,1);               //mvoe the cursor to the first space of the bottom row
  lcd.print(millis()/1000);         //print the number of seconds that have passed since the last reset
}

What You Should See

The LCD screen will show “Hello, world!” On the row below, a counter will count every second that passes.

Project4_Circuit4A_Action

Contrast Adjust

If you are not seeing any characters, are seeing barely visible characters, or see just white rectangles, then you need to adjust the contrast. Twist the potentiometer very slowly until you can clearly read the display. If you reach the end of the potentiometer’s rotation, try twisting in the opposite direction.

Contrast

A display that needs the contrast adjusted. Note the white rectangles.

Program Overview

  1. Import the LCD library.
  2. Make an LCD object called “lcd” that will be controlled using pins 8, 9, 10, 11, 12 and 13.
  3. “Begin” the LCD. This sets the dimensions of the LCD that you are working with (16 x 2). It needs to be called before any other commands from the LCD library are used.
  4. Clear the display.
  5. Set the cursor to the top left corner lcd.setCursor(0,0);, then print “Hello, world!"
  6. Move the cursor to the first space of the lower line lcd.setCursor(0,1);, then print the number of seconds that have passed since the RedBoard was last reset.

Code to Note

CodeDescription
LCD Library:
#include <LiquidCrystal.h>
Includes the liquid crystal library into your program.
LCD Library Instance:
LiquidCrystal LCD_name(RS_pin, enable_pin, d4, d5, d6, d7);
As with servos, you need to create an LCD object and give it a name (you can make more than one). The numbers in the brackets are pins on the RedBoard that connect to specific pins on the LCD.
LCD Begin:
lcd.begin(16, 2);
This line initializes the LCD object and tells the program the LCD's dimensions. In this case it is 16 characters by 2 characters.
LCD Clear:
lcd.clear();
This method clears the pixels on the display.
LCD Cursor:
lcd.setCursor(0,0);
Move the cursor to a point on the 16x2 grid of characters. Text that you write to the LCD will start from the cursor. This line is starting back at position (0,0).
LCD Print :
lcd.print("Hello, world!");
Prints a string of characters to the LCD starting at the cursor position.

Coding Challenges

ChallengeDescription
Change the messageTry changing the code to display another message.
Show hours, minutes and secondsTry adding some code so that the display shows the hours, minutes and seconds that have passed since the RedBoard was last reset.
Count button pressesBy adding a button to the circuit, you can count the number of times the button was pressed or have the button change what the LCD is displaying. There could be many pages of information.

Troubleshooting

ProblemSolution
The screen is blank or flickeringAdjust the contrast by twisting the potentiometer. If it’s incorrectly adjusted, you won’t be able to read the text. Also, check the potentiometer, and make sure it's connected correctly.
Not working at allDouble check the circuit's wiring. There are a lot of wires in this circuit, and it's easy to mix up one or two.
Rectangles in first rowIf you see 16 rectangles (like “█”) on the first row, it may be due to the jumper wires being loose on the breadboard. This is normal and can happen with other LCDs wired in parallel with a microcontroller. Make sure that the wires are fully inserted into the breadboard, then try pressing the reset button and adjusting the contrast using the potentiometer.
Still not working?Jumper wires unfortunately can go "bad" from getting bent too much. The copper wire inside can break, leaving an open connection in your circuit. If you are certain that your circuit is wired correctly and that your code is error-free and uploaded but you are still encountering issues, try replacing one or more of the jumper wires for the component that is not working.

Circuit 4B: Temperature Sensor

Want to create a DIY environmental monitor or weather station? You can use a small, low-cost sensor like the TMP36 to make devices that track and respond to temperature. In this activity you will also use the LCD screen to display sensor readings, a common use for LCDs in electronics projects.

Project4_Circuit4B

Parts Needed

Grab the following quantities of each part listed to build this circuit:

parts

New Components

TMP36 Temperature Sensor

This temperature sensor has three legs. One connects to 5V, one to ground, and the voltage output from the third leg varies proportionally to changes in temperature. By doing some simple math with this voltage we can measure temperature in degrees Celsius or Fahrenheit.

TMP36 Temperature sensor

New Concepts

Algorithms

An algorithm is a process used in order to achieve a desired result. Often, the information needed to create an algorithm lives in the part’s datasheet. This sketch uses a few formulas to turn a voltage value into a temperature value, making them all part of the larger temperature-retrieving algorithm. The first formula takes the voltage read on analog pin 0 and multiplies it to get a voltage value from 0V–5V:

language:c
voltage = analogRead(A0) * 0.004882814;

The number we are multiplying by comes from dividing 5V by the number of samples the analog pin can read (1024), so we get: 5 / 1024 = 0.004882814.

The second formula takes that 0–5V value and calculates degrees Centigrade:

language:c
degreesC = (voltage - 0.5) * 100.0;

The reason 0.5V is subtracted from the calculated voltage is because there is a 0.5V offset, mentioned on page 8 of the TMP36 datasheet. It’s then multiplied by 100 to get a value that matches temperature.

The last formula takes the Centigrade temperature and converts it to a Fahrenheit temperature using the standard conversion formula:

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

Together, these three formulas make up the algorithm that converts voltage to degrees Fahrenheit.

Hardware Hookup

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.

The temperature sensor is polarized and can only be inserted in one direction. See below for the pin outs of the temperature sensor. Pay very close attention to the markings on each side as you insert it into your circuit.

Temperature Sensor

Heads up! Double check the polarity of the TMP36 temperature sensor before powering the RedBoard. It can become very hot if it is inserted backward!

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

Circuit Diagram

Circuit_4B

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

ComponentRedBoardBreadboardBreadboardBreadboard
Jumper Wire5V5V Rail ( + )
Jumper WireGNDGND Rail ( - )
A15-A30 (Pin 1 on A15)
Jumper WireE30GND Rail ( - )
Jumper WireE295V Rail ( + )
Jumper WireDigital Pin 8E28
Jumper WireDigital Pin 9E27
Jumper WireDigital Pin 10E26
Jumper WireDigital Pin 11E25
Jumper WireDigital Pin 12E20
Jumper WireE19GND Rail ( - )
Jumper WireDigital Pin 13E18
Jumper WireE165V Rail ( + )
Jumper WireE15GND Rail ( - )
PotentiometerA8A9A10
Jumper WireE9E17
Jumper WireE8GND Rail ( - )
Jumper WireE105V Rail ( + )
A1 (GND)A2 (Singnal)A3 (V+)
Jumper WireE1GND Rail ( - )
Jumper WireAnalog Pin 0 (A0)E2
Jumper WireE35V Rail ( + )

In the table, polarized components are shown with a warning triangle and the whole row highlighted yellow.

Open the Sketch

To open the code, go to: File > Examples > SIK_Guide_Code-V_4 > SIK_Circuit_4B-TemperatureSensor

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
Circuit 4B - Temperature Sensor

The LCD will display readings from a temperature sensor in degrees Celsius and Fahrenheit.

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v40
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
*/

#include <LiquidCrystal.h>                  //the liquid crystal libarry contains commands for printing to the display
LiquidCrystal lcd(13, 12, 11, 10, 9, 8);    // tell the RedBoard what pins are connected to the display

float voltage = 0;                          //the voltage measured from the TMP36
float degreesC = 0;                         //the temperature in Celsius, calcuated from the voltage
float degreesF = 0;                         //the temperature in Farenheit, calcuated from the voltage

void setup() {

  lcd.begin(16, 2);                         //tell the lcd library that we are using a display that is 16 characters wide and 2 characters high
  lcd.clear();                              //clear the display
}

void loop() {

  voltage = analogRead(A0) * 0.004882814;   //convert the analog reading, which varies from 0 to 1023, back to a voltage value from 0-5 volts
  degreesC = (voltage - 0.5) * 100.0;       //convert the voltage to a temperature in degrees Celsius
  degreesF = degreesC * (9.0/5.0) + 32.0;   //convert the voltage to a temperature in dgrees Fahrenheit

  lcd.clear();                              //clear the LCD

  lcd.setCursor(0,0);                       //set the cursor to the top left position
  lcd.print("Degrees C: ");                 //print a label for the data
  lcd.print(degreesC);                      //print the degrees Celsius

  lcd.setCursor(0,1);                       //set the cursor to the lower left position
  lcd.print("Degrees F: ");                 //print a label for the data
  lcd.print(degreesF);                      //print the degrees Fahreheit

  delay(1000);                              //delay for 1 second between each reading (this makes the display less noisy)
}

What You Should See

The LCD will show the temperature in Celsius and Fahrenheit. The temperature readings will update every second. An easy way to see the temperature change is to press your finger to the sensor.

Project4_Circuit4B_Action

Program Overview

  1. Get the analog value from the TMP36 and convert it back to a voltage between 0 and 5V.
  2. Calculate the degrees Celsius from this voltage.
  3. Calculate the degrees Fahrenheit from this voltage.
  4. Clear the LCD.
  5. Print the Degrees C with a label on the first row.
  6. Print the Degrees F with a label on the second row.
  7. Wait for a second before taking the next reading.

Code to Note

CodeDescription
Voltage Conversion AlgorithmsMany of the sensors that you will use with your microcontroller work by changing a voltage in some predictable way in response to a property of the world (like temperature, light or magnetic fields). Often, you will need to build an algorithm that converts these voltages to the desired value and units. The temperature sensor is a great example of this code. We use three equations to convert a voltage value into degrees in C and F.

voltage = analogRead(A0) * 0.004882814;
degreesC = (voltage - 0.5) * 100.0;
degreesF = degreesC * (9.0/5.0) + 32.0;

Coding Challenges

ChallengeDescription
Display the temperature in degrees KelvinTry adding an equation so that the temperature is displayed in degrees Kelvin (you will have to look up the formula for converting from degrees Celsius or Fahrenheit to Kelvin)
Display a bar graphBy changing the code you can display the temperature as a bar graph instead of a number.
Display values from another sensorYou can swap out the TMP36 for a potentiometer, photoresistor or other sensor and display the new set of values.
Add an RGB LEDAdd an RGB LED that changes color based on the temperature.

Troubleshooting

ProblemSolution
Sensor is warm or hot to the touchMake sure that you wired the temperature sensor correctly. The temperature sensor can get warm to the touch if it is wired incorrectly. Disconnect your microcontroller, rewire the circuit, and connect it back to your computer.
Temperature value is unchangingTry 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.
Values not printing to screenIf you see text but no temperature values, there could be an error in your code. If you see no text at all, adjust the LCD contrast.

Circuit 4C: DIY Who Am I? Game

“DIY Who Am I?” is based on the popular Hedbanz game or HeadsUp! app. It’s a fun party game in which a player holds an LCD screen to his/her forehead so that the player can’t see the word(s) that appear on the screen. Other players have to give hints, act out charades or make noises that will make the player with the LCD guess the word(s).

Project4_Circuit4C

Parts Needed

Grab the following quantities of each part listed to build this circuit:

parts

Need Battery holder image for parts list

New Components

4xAA Battery Holder

Included in your kit is a 4-cell AA battery holder. The 5-inch cable is terminated with a standard barrel jack connector. The connector mates with the barrel jack on the RedBoard, allowing you to easily make your project battery powered.

4xAA Battery Holder

New Concepts

Button Debounce

When working with momentary buttons, it is usually necessary to add button debouncing to your code. This is because the code that is meant to execute when the button is pressed may execute faster than you can press and release the button (microcontrollers are fast!). The simplest way to debounce a button is to add a small delay to the end of your code. This sketch adds a 500 millisecond delay at the end of loop() to account for this. This simple addition will prevent a word from getting skipped when you press the button for the game.

For a more complex example of button debouncing, in the Arduino IDE click File > Examples > 02.Digital > Debounce.

Strings

Strings are used to print words and even sentences to an LCD or the Serial Monitor. Strings are actually just an array of characters with a null character at the end to let the program know where the end of the string is.

Arrays of Strings

In circuit 2A you used an array of characters to represent musical notes. In this program, you’ll want to make an array of strings. Strings use multiple characters to make words, so you’ll need to use a little trick to put them in an array. The trick is to use a pointer. When you declare your array, you’ll use an asterisk after the char data type, as follows:

language:c
const char* arrayOfStrings = {“Feynman” “Sagan”, “Tyson”, “Nye”};

Pointers

Pointers are an advanced programming topic. They can be difficult to understand the first time you’re introduced to them. For now, think of pointers as a variable that “points” to the value contained in a certain address in memory. In this sketch, the char* variable points to arrayOfStrings address and returns the character values to create a list of strings.

Hardware Hookup

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.

Batteries are polarized. They have a positive end and a negative end. The battery holder has images indicating which end goes in which orientation for each cell.

4xAA Battery Holder

Ensure all the batteries are inserted correctly before plugging the battery holder into the RedBoard.

Battery Holder Attachment

To attach the battery holder to the breadboard baseplate, first cut two strips of Dual Lock that are roughly 1 inch x 1 inch each, or 2.5cm x 2.5cm. Remove the adhesive backing and attach one piece to the back of the battery holder.

Battery Holder Dual Lock

Adhere the second piece to the bottom of the breadboard baseplate (directly in the middle is recommended, as this will come into play in Project 5).

Baseplate Dual Lock

Last, press the battery holder to the baseplate so that the two pieces of Dual Lock snap together. Insert the batteries into the holder if you have not done so already. Remember that batteries are polarized and can only go in one way.

Batteries connected

Batteries connected

Remove the battery pack while building your circuit.

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

Circuit Diagram

Circuit_4C

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

ComponentRedBoardBreadboardBreadboardBreadboard
Jumper Wire5V5V Rail ( + )
Jumper WireGNDGND Rail ( - )
A15-A30 (Pin 1 on A15)
Jumper WireE30GND Rail ( - )
Jumper WireE295V Rail ( + )
Jumper WireDigital Pin 8E28
Jumper WireDigital Pin 9E27
Jumper WireDigital Pin 10E26
Jumper WireDigital Pin 11E25
Jumper WireDigital Pin 12E20
Jumper WireE19GND Rail ( - )
Jumper WireDigital Pin 13E18
Jumper WireE165V Rail ( + )
Jumper WireE15GND Rail ( - )
PotentiometerA8A9A10
Jumper WireE9E17
Jumper WireE8GND Rail ( - )
Jumper WireE105V Rail ( + )
G6
(Buzzer +)
G8
(Buzzer -)
Jumper WireDigital Pin 6J5
Jumper WireJ7GND Rail
( - )
Push ButtonD1/D3G1/G3
Jumper WireDigital Pin 2J1
Jumper WireJ3GND Rail ( - )

In the table, polarized components are shown with a warning triangle and the whole row highlighted yellow.

Open the Sketch

To open the code, go to: File > Examples > SIK_Guide_Code-V_4 > SIK_Circuit_4C-DIYWhoAmI

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
Circuit 4C - Heads Up Game

This is a DIY version of the popular Heads Up party game. To play, one person resets the RedBoard and holds the LCD
facing away from them so that they cannot see it (usually on their forehead). The display will show a short countdown
then display random words. The other player(s) who can see the screen must yell out clues until time runs out or the player
guesses what word is on the screen. If they guess correctly, they can press the button on the breadboard and another word
will be displayed.

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v40
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
*/


#include <LiquidCrystal.h>            //the liquid crystal libarry contains commands for printing to the display
LiquidCrystal lcd(13, 12, 11, 10, 9, 8);     // tell the RedBoard what pins are connected to the display

int buttonPin = 2;                    //pin that the button is connected to
int buzzerPin = 6;                    //pin for driving the buzzer
int buttonPressTime = 0;              //variable to show how much time the player has left to guess the word (and press the button)

long timeLimit = 15000;               //time limit for the playe to guess each word
long startTime = 0;                   //used to measure time that has passed for each word
int roundNumber = 0;                        //keeps track of the roundNumber so that it can be displayed at the end of the game
const int arraySize = 25;

const char* words[arraySize] = {"moose", "beaver", "bear", "goose", "dog", "cat", "squirrel", "bird", "elephant", "horse","bull", "giraffe", "seal", "bat", "skunk", "turtle", "whale", "rhino", "lion", "monkey","frog", "alligator", "kangaroo", "hippo", "rabbit"};

int sequence[] = {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};     //start with an array full of 0s

void setup() {

  pinMode(buttonPin, INPUT_PULLUP);       //set the button pin as an input

  lcd.begin(16, 2);                       //tell the LCD library the size of the screen

  generateRandomOrder();                  //generate an array of random numbers from 1-25 that will determine which order the words are shown in

  showStartSequence();                    //print the start sequence text

}

void loop() {

  for(int i=0; i<arraySize; i++){                //for each of the 25 words in the sequence

      lcd.clear();                        //clear off the array

      roundNumber = i+1;                      //the array starts at 0, but the roundNumber will start counting from 1
      lcd.print(roundNumber);                 //print the roundNumber (this is the current round number)
      lcd.print(": ");                        //spacer between the number and the word
      lcd.print(words[sequence[i]]);        //print a random word from the word array

      startTime = millis();  //record the time that this round started

      while(digitalRead(buttonPin) == HIGH){           //do this until the button is pressed...

        int roundedTime = round((timeLimit - (millis() - startTime))/1000);   //calculate the time left in the round (dividing by 1000 converts the number to seconds
        lcd.setCursor(14,1);                                                  //set the cursor in the lower right corner of the screen
        lcd.print("");
        lcd.setCursor(14,1);                                                  //set the cursor in the lower right corner of the screen
        lcd.print(roundedTime);                                               //print the time left in the time limit
        delay(15);

        if(millis() - startTime > timeLimit){         //if the time limit is up before the button is pressed
          gameOver();                                 //end the game
        }

        if(digitalRead(buttonPin) == LOW){
            tone(buzzerPin, 272, 1);
        }

      }                       //exit this loop when the button is pressed

      delay(500);             //delay for a moment before giong on to the next ruond, so that the button press doesn't get registered twice

    }
  //if you finish all 25 words
  winner();   //show the you win message
}


//--------------FUNCTIONS------------------------------

//DISPLAYS A COUNTDOWN TO START THE GAME
void showStartSequence(){

  lcd.clear();                  //clear the screen

  lcd.setCursor(0,0);           //move the cursor to the top left corner
  lcd.print("Category:");       //print "Category:"

  lcd.setCursor(0,1);           //move the cursor to the bottom left corner
  lcd.print("Animals");         //print "Animals:"

  delay(2000);                  //Wait 2 seconds

  lcd.clear();                  //clear the screen
  lcd.print("Get ready!");      //print "Get ready!"
  delay(1000);                  //wait 1 second

  lcd.clear();                  //clear the screen
  lcd.print("3");               //print "3"
  delay(1000);                  //wait 1 second

  lcd.clear();                  //clear the screen
  lcd.print("2");               //print "3"
  delay(1000);                  //wait 1 second

  lcd.clear();                  //clear the screen
  lcd.print("1");               //print "3"
  delay(1000);                  //wait 1 second
}

//GENERATES A RANDOM ORDER FOR THE WORDS TO BE DISPLAYED
void generateRandomOrder(){

  randomSeed(analogRead(0));            //reset the random seed (Arduino needs this to generate truely random numbers

  for (int i = 0; i < 24; i++){         //do this until all 25 positions are filled

    int currentNumber = 0;              //variable to hold the current number
    boolean match = false;              //does the currentNumber match any of the previous numbers?

    //generate random numbers until you've generated one that doesn't match any of the other numbers in the arary
    do {
      currentNumber = random(0,arraySize);             //generate a random number from 1-25
      match = false;                            //we haven't checked for matches yet, so start by assuming that it doesn't match
      for (int i = 0; i < arraySize; i++){             //for all 25 numbers in the array
        if (currentNumber == sequence[i]){      //does the currentNumber match any of the numbers?
          match = true;                         //if so, set the match variable to true
        }
      }
    } while(match == true);                     //if the match variable is true, generate another random number and try again
    sequence[i] = currentNumber;                //if the match variable is false (the new number is unique) then add it to the sequence
  }
}

//GAME OVER
void gameOver(){
  lcd.clear();                    //clear the screen

  lcd.setCursor(0,0);             //move the cursor the top left corner
  lcd.print("Game Over");         //print "Game Over"

  lcd.setCursor(0,1);             //move to the bottom row
  lcd.print("Score: ");           //print a label for the score
  lcd.print(roundNumber);         //print the score (the round number is the same as the score)

  //play the losing fog horn
  tone(buzzerPin, 130, 250);      //E6
  delay(275);
  tone(buzzerPin, 73, 250);       //G6
  delay(275);
  tone(buzzerPin, 65, 150);       //E7
  delay(175);
  tone(buzzerPin, 98, 500);       //C7
  delay(500);

  while(true){}                   //get stuck in this loop forever
}

//WINNER
void winner(){
  lcd.clear();                    //clear the screen

  lcd.setCursor(7,0);             //move the cursor to the top center of the screen
  lcd.print("YOU");               //print "You"

  lcd.setCursor(7,1);             //move the cursor to the bottom center of the screen
  lcd.print("WIN!");              //print "WIN!"

  //play the 1Up noise
  tone(buzzerPin, 1318, 150);     //E6
  delay(175);
  tone(buzzerPin, 1567, 150);     //G6
  delay(175);
  tone(buzzerPin, 2637, 150);     //E7
  delay(175);
  tone(buzzerPin, 2093, 150);     //C7
  delay(175);
  tone(buzzerPin, 2349, 150);     //D7
  delay(175);
  tone(buzzerPin, 3135, 500);     //G7
  delay(500);

  while(true){}                   //get stuck in this loop forever
}

What You Should See

The game will begin with a prompt telling you the category of words. Then it will run through a short countdown. When the first round starts, the word to be guessed will be displayed in the top left, and a countdown will be displayed in the bottom right of the LCD screen. Each time the button is pressed (before the timer expires) a new word will be displayed. If you win or lose, a short song will play and text will be displayed.

Project4_Circuit4C_Action

Program Overview

  1. Generate a random order for the words to be displayed.
  2. Show the starting countdown on the LCD.
  3. Start a loop that will run 25 times (there are 25 words total). For each round:
    1. Print the round number and the word to be guessed.
    2. Display a countdown timer in the lower right-hand corner of the screen that counts down the time limit for each round.
    3. If the time limit runs out, play the losing song, print “Game Over” and show the player’s final score.
    4. If the player presses the button before the time limit is up, advance to the next word.
  4. If the player gets through all 25 words, play the winning song and print “YOU WIN!”

Code to Note

CodeDescription
Array of Strings:
const char* array_name [array_length] =
{“string1”, “string2”...}
Makes an array of strings. The strings are stored as constants, so they can’t be changed once the program starts.
Rounding function:
round(value_to_round);
This math function rounds a number up or down to the nearest whole number.
Random Function:
random(min, max);
The random function takes a set of numbers and generates a pseudo-random number from that set.
Button Debounce:
delay(500);
This 500 millisecond delay at the end of the loop adds button debounce so that erroneous button presses are not detected by the RedBoard.
User Functions Description
generateRandomOrder();Makes an array that is a random ordering of the numbers from 1-25. This is used to display words for the game in a random order.
showStartSequence();Shows the category of words on the LCD, then displays a countdown before the game starts.
gameOver();Plays a sound and shows the text “Game Over” along with the player’s final score.
winner();Shows the text “YOU WIN!” and plays a winning sound.

Coding Challenges

ChallengeDescription
Change the time limitChanging the time limit variable will change the difficulty of the game.
Change the words in the word listTry changing the categories and words. The number of words in your words array must match the value of the variable “arraySize”.
Change the winning and losing songsBy changing the tones in the winner() and gameover() functions you can change which song plays at the end of the game.

Troubleshooting

ProblemSolution
The screen is blank or flickeringAdjust the contrast by twisting the potentiometer. If it’s incorrectly adjusted, you won’t be able to read the text. Also, check the potentiometer to make sure it's connected correctly.
No sound is coming from the buzzerCheck the wiring from the buzzer. Make sure you are using the correct pin as defined in your code. You may add a potentiometer volume knob if you desire.
The button doesn't work or words are getting skipped before they are guessedIf the button isn't working, check your wiring. If words are being skipped when the button is pressed, increase the debounce delay found at the end of the loop. It should be 500 milliseconds by default. Increasing this number by tiny increments will help with this problem.

Project 5: Robot

Ah, robots. One of the most iconic and exciting electronics applications. In this project you will learn all about DC motors and motor drivers by building your own robot! You’ll learn how to control a tethered robot first by sending it commands over serial. Then you will unleash your robot by removing the tether and making it autonomous.

SIK_Project5_Circuit5C_Action1

New Components Introduced in This Project

Each of the components listed below will be described in more detail as you progress through each circuit.

  • TB6612FNG Motor Driver
  • Switch
  • DC Gearmotor
  • Wheel

New Concepts Introduced in This Project

Each of the concepts listed below will be described in more detail as you progress through each circuit.

  • Input Voltage
  • Integrated Circuits
  • H-Bridge Motor Driver
  • ASCII Characters
  • Converting Strings
  • Autonomous Vehicles

You Will Learn

  • How to control two motors using a motor driver
  • How to send serial commands to create a remote-controlled robot
  • How to build a robot that uses sensors to react to its environment

Circuit 5A: Motor Basics

In this circuit you will learn the basic concepts behind motor control. Motors require a lot of current, so you can’t drive them directly from a digital pin on the RedBoard. Instead, you’ll use what is known as a motor controller or motor driver board to power and spin the motor accordingly.

SIK_Project5_Circuit5A_Hero

Parts Needed

Grab the following quantities of each part listed to build this circuit:

parts

Need parts images for motor driver, switch, motors and wheels.

New Components

Switch

A switch is a component that controls the open-ness or closed-ness of an electric circuit. Just like the momentary buttons used in earlier circuits, a switch can only exist in one of two states: open or closed. However, a switch is different in that it will stay in the position it was last in until it is switched again.

Switch

DC Gearmotors

The motors in your Inventor’s Kit have two main parts: a small DC motor that spins quickly and a plastic gearbox that gears down that output from the hobby motor so that it is slower but stronger, allowing it to move your robot. The motors have a clever design so that you can attach things that you want to spin fast (like a small fan or flag) to the hobby motor, and things that you want to be strong (like a wheel) to the plastic axle sticking out the side of the motor. The included wheels just so happen to fit on the plastic axles.

Inside the hobby motor are coils of wire that generate magnetic fields when electricity flows through them. When power is supplied to these electromagnets, they spin the drive shaft of the motor.

TB6612FNG Motor Driver

If you switch the direction of current through a motor by swapping the positive and negative leads, the motor will spin in the opposite direction. Motor controllers contain a set of switches (called an H-bridge) that let you easily control the direction of one or more motors. The TB6612FNG Motor Driver takes commands for each motor over three wires (two wires control direction, and one controls speed), then uses these signals to control the current through two wires attached to your motor.

MotorDriver

New Concepts

Voltage In (VIN)

This circuit utilizes the VIN pin found with the other power pins. The VIN pin outputs a voltage that varies based on whatever voltage the RedBoard is powered with. If the RedBoard is powered through the USB port, then the voltage on VIN will be about 4.6–5V. However, if you power the RedBoard through the barrel jack (highlighted in the picture below), the VIN pin will reflect that voltage. For example, if you were to power the barrel jack with 9V, the voltage out on VIN would also be 9V.

VIN Pin

Integrated Circuits (ICs) and Breakout Boards

An Integrated Circuit (IC) is a collection of electronic components — resistors, transistors, capacitors, etc. — all stuffed into a tiny chip and connected together to achieve a common goal. They come in all sorts of flavors, shapes and sizes. The chip that powers the RedBoard, the ATMega328, is an IC. The chip on the motor driver, the TB6612FNG, is another IC, one designed to control motors, referred to as an H-bridge.

Internal view of an IC

The guts of an integrated circuit, visible after removing the top.

Integrated circuits are often too small to work with by hand. To make working with ICs easier and to make them breadboard-compatible, they are often added to a breakout board, which is a printed circuit board that connects all the IC’s tiny legs to larger ones that fit in a breadboard. The motor driver board in your kit is an example of a breakout board.

Hardware Hookup

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.

Most ICs have polarity and usually have a polarity marking in one of the corners. The motor driver is no exception. Be sure to insert the motor driver as indicated in the circuit diagrams. The motor driver pins are shown in the image below.

MotorDriver

Each pin and its function is covered in the table below.

Pin LabelFunctionPower/Input/Output
Notes
VMMotor VoltagePowerThis is where you provide power for the motors (2.2V to 13.5V)
VCCLogic VoltagePowerThis is the voltage to power the chip and talk to the microcontroller (2.7V to 5.5V)
GNDGroundPowerCommon Ground for both motor voltage and logic voltage (all GND pins are connected)
STBYStandbyInputAllows the H-bridges to work when high (has a pulldown resistor so it must actively be pulled high)
AIN1/BIN1Input 1 for channels A/BInputOne of the two inputs that determines the direction
AIN2/BIN2Input 2 for channels A/BInputOne of the two inputs that determines the direction
PWMA/PWMBPWM input for channels A/BInputPWM input that controls the speed
A01/B01Output 1 for channels A/BOutputOne of the two outputs to connect the motor
A02/B02Output 2 for channels A/BOutputOne of the two outputs to connect the motor

When you’re finished with Project 5, removing the motor driver from the breadboard can be difficult due to its numerous legs. To make this easier, use the included screwdriver as a lever to gently pry it out. Be careful not to bend the legs as you remove it.

MotorDriver3

The motors are also polarized. However, motors are unique in that they will still work when the two connections are reversed. They will just spin in the opposite direction when hooked up backward. To keep things simple, always think of the red wire as positive ( + ) and the black wire as negative ( - ).

motor Polarity) <-

Last, the switch is not polarized. It works the same no matter its orientation.

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

Circuit Diagram

Circuit_5A

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

ComponentRedBoardBreadboardBreadboardBreadboard
Jumper Wire5V5V Rail ( + )
Jumper WireGNDGND Rail ( - )
Jumper Wire5V Rail ( + )5V Rail ( + )
Jumper WireGND Rail ( - )GND Rail ( - )
Jumper WireVINA1
C1-C8 (VM on C1)G1-G8 (PWMA on G1)
Jumper WireA25V Rail ( + )
Jumper WireA3GND Rail ( - )
Jumper WireDigital Pin 8J7
Jumper WireDigital Pin 9J6
Jumper WireDigital Pin 10J5
Jumper WireJ45V Rail ( + )
Jumper WireDigital Pin 11J3
Jumper WireDigital Pin 12J2
Jumper WireDigital Pin 13J1
A4 (Red +)A5 (Black -)
SwitchF25F26F27
Jumper WireI26GND Rail ( - )
Jumper WireDigital Pin 7I27

In the table, polarized components are shown with a warning triangle and the whole row highlighted yellow.

Open the Sketch

To open the code, go to: File > Examples > SIK_Guide_Code-V_4 > SIK_Circuit_5A-MotorBasics.

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
Circuit 5A - Motor Basics

Learn how to control one motor with the motor driver.

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v40
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
*/

//PIN VARIABLES
//the motor will be controlled by the motor A pins on the motor driver
const int AIN1 = 11;           //control pin 1 on the motor driver for the right motor
const int AIN2 = 12;            //control pin 2 on the motor driver for the right motor
const int PWMA = 13;            //speed control pin on the motor driver for the right motor

int switchPin = 7;             //switch to turn the robot on and off

//VARIABLES
int motorSpeed = 0;       //starting speed for the motor

void setup() {
  pinMode(switchPin, INPUT_PULLUP);   //set this as a pullup to sense whether the switch is flipped

  //set the motor contro pins as outputs
  pinMode(AIN1, OUTPUT);
  pinMode(AIN2, OUTPUT);
  pinMode(PWMA, OUTPUT);

  Serial.begin(9600);                       //begin serial communication with the computer

  Serial.println("Enter motor speed (255, 0, or -255)... ");    //Prompt to get input in the serial monitor.
}

void loop() {

  if (Serial.available() > 0){          //if the user has entered something in the serial monitor
    motorSpeed = Serial.parseInt();     //set the motor speed equal to the number in the serial message

    Serial.print("Motor Speed: ");      //print the speed that the motor is set to run at
    Serial.println(motorSpeed);
  }

  if(digitalRead(7) == LOW){            //if the switch is on...
      spinMotor(motorSpeed);
  } else{                               //if the switch is off...
      spinMotor(0);                   //turn the motor off
  }


}

/********************************************************************************/
void spinMotor(int motorSpeed)                       //function for driving the right motor
{
  if (motorSpeed > 0)                                 //if the motor should drive forward (positive speed)
  {
    digitalWrite(AIN1, HIGH);                         //set pin 1 to high
    digitalWrite(AIN2, LOW);                          //set pin 2 to low
  }
  else if (motorSpeed < 0)                            //if the motor should drive backwar (negative speed)
  {
    digitalWrite(AIN1, LOW);                          //set pin 1 to low
    digitalWrite(AIN2, HIGH);                         //set pin 2 to high
  }
  else                                                //if the motor should stop
  {
    digitalWrite(AIN1, LOW);                          //set pin 1 to low
    digitalWrite(AIN2, LOW);                          //set pin 2 to low
  }
  analogWrite(PWMA, abs(motorSpeed));                 //now that the motor direction is set, drive it at the entered speed
}

What You Should See

When you flip the switch, the motor will turn on and spin at the speed set by the motor speed variable (default is 0). By opening the serial monitor and sending numbers, you can change the speed of the motor. Any number from about 130 to 255 or -130 to -255 will work, though changes in the speed will be hard to notice. Send the number 0 to stop the motor. Adding a piece of tape to the motor shaft makes it easier to see it spinning.

SIK_Project5_Circuit5A_Action

Program Overview

  1. Check to see if a command has been sent through the Serial Monitor. If a command has been sent, then set the motor speed to the number that was sent over the Serial Monitor.
  2. Check to see if the switch is ON or OFF.
    1. If the switch is ON, drive the motor at the motor speed.
    2. If the switch is OFF, stop the motor.

Code to Note

https://www.arduino.cc/en/Serial/Available
CodeDescription
Parsing Integers:
Serial.parseInt();
parseInt() receives integer numbers from the serial monitor. It returns the value of the number that it receives, so you can use it like a variable.
Serial Available:
Serial.available();
Serial.available() checks how many bytes of data are being sent to the RedBoard. If it is greater than 0, then a message has been sent. It can be used in an if statement to run code only when a command has been received.

Coding Challenges

ChallengeDescription
Make the switch change directionsChange the code so that the position of the switch changes the direction of the motor instead of turning it on and off.
Replace the switch with a buttonTry wiring a button into the circuit instead of the sliding switch. Now the motor only turns on when you push the button.
Replace the switch with a sensorTry changing the code so that the motor is activated by another sensor, like the photoresistor.

Troubleshooting

ProblemSolution
Motor not spinningCheck the wiring to the motor driver. There are a lot of connections, and it’s easy to mix one of them up with another. If it is still not working, you can test the B channel by moving you motor. (Black wire to A6, Red wire to A7). You’ll need to change the code as well.
Switch not workingMake sure that you are hooked up to the middle pin and one side pin on the switch.
Still not working?Jumper wires unfortunately can go "bad" from getting bent too much. The copper wire inside can break, leaving an open connection in your circuit. If you are certain that your circuit is wired correctly and that your code is error-free and uploaded but you are still encountering issues, try replacing one or more of the jumper wires for the component that is not working.

Circuit 5B: Remote-Controlled Robot

It’s remote control time! In this circuit, you’ll use a motor driver to control the speed and direction of two motors. You will also learn how to read multiple pieces of information from one serial command so that you can use the Serial Monitor to tell the robot what direction to move in and how far to move.

SIK_Project5_Circuit5B_Hero

Parts Needed

Grab the following quantities of each part listed to build this circuit:

parts

Need parts images for motor driver, switch, motors and wheels.

Additional Materials

  • Scissors

New Concepts

ASCII Characters

ASCII is a standard formalized in the 1960s that assigns numbers to characters. This is a method of character encoding. When typing on a computer keyboard, each character you type has a number associated with it. This is what allows computers to know whether you are typing a lowercase “a,” an uppercase “A” or a random character such as ampersand (&). In this experiment, you will be sending characters to the Serial Monitor to move your remote control robot. When you send a character, the microcontroller is actually interpreting that as a specific number. There are tons of ASCII tables available online. These tables make it easier to know which character is represented by which number.

Converting Strings to Integers

String variables hold words like “dog” or “Robert Smith” that are made up of multiple characters. Arduino has a set of special built-in methods for string variables that you can call by putting a period after the variable name, as follows:

string_variable_name. toInt();

The .toInt() method converts the string to a number, and there are a dozen other methods that can do things like tell you the length of a word or change all of the characters in a string to uppercase or lowercase.

Hardware Hookup

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.

Before you build this circuit, you’ll need to make a few modifications to the breadboard baseplate to make it more robot-like!

Assembling the Robot

Using scissors, cut two strips of Dual Lock that are 1.25 inches (3.175cm) long and 1 inch (2.5cm) wide. Remove the adhesive backing, and attach the two pieces to the very corners of the baseplate on the side located under the breadboard.

RobotAssembly1

Note: You will likely have a piece of Dual Lock in the center of your baseplate from Project 4. Leave it if so. It will be used in the next circuit.

Cut two more strips that are 1.25 inches (3.175cm) long and ¾ inch (1.9cm) wide. Remove the adhesive backing, and attach the strips to the two motors. Be sure that your motors are mirror images of each other when you attach the Dual Lock.

RobotAssembly2

Press the motors to the baseplate, connecting the two Dual Lock surfaces. Try to get the motors as straight as possible so your robot will drive straight.

RobotAssembly3

The bottom of your baseplate should look like the image below. Remember that the two motors should be mirror images of each other.

RobotAssembly4

Note: The direction in which the motor wires face is arbitrary. Having them face out makes the circuit easier to build. Having them face in makes the circuit more robust against wires getting ripped out.

Attach the wheels by sliding them onto the plastic shafts on the gearmotor. The shaft is flat on one side, as is the wheel coupler. Align the two, and then press to fit the wheel onto the shaft.

RobotAssembly5

Last, clip the binder clip onto the back end of the robot. This will act as a caster as the robot drives around.

RobotAssembly7

Once you’re finished, it’s time to build the circuit. You may choose to remove the motors or leave them on while you build the circuit.

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

Circuit Diagram

Circuit_5B

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

ComponentRedBoardBreadboardBreadboardBreadboard
Jumper Wire5V5V Rail ( + )
Jumper WireGNDGND Rail ( - )
Jumper Wire5V Rail ( + )5V Rail ( + )
Jumper WireGND Rail ( - )GND Rail ( - )
Jumper WireVINA1
C1-C8 (VM on C1)G1-G8 (PWMA on G1)
Jumper WireA25V Rail ( + )
Jumper WireA3GND Rail ( - )
Jumper WireDigital Pin 8J7
Jumper WireDigital Pin 9J6
Jumper WireDigital Pin 10J5
Jumper WireJ45V Rail ( + )
Jumper WireDigital Pin 11J3
Jumper WireDigital Pin 12J2
Jumper WireDigital Pin 13J1
A4 (Red +)A5 (Black -)
A6 (Black -)A7 (Red +)
SwitchF25F26F27
Jumper WireI26GND Rail ( - )
Jumper WireDigital Pin 7I27

In the table, polarized components are shown with a warning triangle and the whole row highlighted yellow.

Open the Sketch

To open the code, go to: File > Examples > SIK_Guide_Code-V_4 > SIK_Circuit_5B-RemoteControlRobot

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
Circuit 5B - Remote Control Robot

Control a two wheeled robot by sending direction commands through the serial monitor.
This sketch was adapted from one of the activities in the SparkFun Guide to Arduino.
Check out the rest of the book at
https://www.sparkfun.com/products/14326

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v40
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
*/

//the left motor will be controlled by the motor B pins on the motor driver
const int PWMB = 13;           //speed control pin on the motor driver for the left motor
const int BIN2 = 12;           //control pin 2 on the motor driver for the left motor
const int BIN1 = 11;           //control pin 1 on the motor driver for the left motor

//the right motor will be controlled by the motor A pins on the motor driver
const int AIN1 = 10;           //control pin 1 on the motor driver for the right motor
const int AIN2 = 9;            //control pin 2 on the motor driver for the right motor
const int PWMA = 8;            //speed control pin on the motor driver for the right motor

const int driveTime = 20;      //this is the number of milliseconds that it takes the robot to drive 1 inch
                               //it is set so that if you tell the robot to drive forward 25 units, the robot drives about 25 inches

const int turnTime = 8;        //this is the number of milliseconds that it takes to turn the robot 1 degree
                               //it is set so that if you tell the robot to turn right 90 units, the robot turns about 90 degrees

                               //Note: these numbers will vary a little bit based on how you mount your motors, the friction of the
                               //surface that your driving on, and fluctuations in the power to the motors.
                               //You can change the driveTime and turnTime to make them more accurate

String botDirection;           //the direction that the roobt will drive in (this change which direction the two motors spin in)
String distance;               //the distance to travel in each direction

/********************************************************************************/
void setup()
{
  //set the motor contro pins as outputs
  pinMode(AIN1, OUTPUT);
  pinMode(AIN2, OUTPUT);
  pinMode(PWMA, OUTPUT);

  pinMode(BIN1, OUTPUT);
  pinMode(BIN2, OUTPUT);
  pinMode(PWMB, OUTPUT);

  Serial.begin(9600);           //begin serial communication with the computer

  //prompt the user to enter a command
  Serial.println("Enter a diretion followed by a distance.");
  Serial.println("f = forward, b = backward, r = turn right, l = turn left");
  Serial.println("Example command: f 50");
}

/********************************************************************************/
void loop()
{
  if (Serial.available() > 0)                         //if the user has sent a command to the RedBoard
  {
    botDirection = Serial.readStringUntil(' ');       //read the characters in the command until you reach the first space
    distance = Serial.readStringUntil(' ');           //read the characters in the command until yuo reach the second space

    //print the command that was just received in the serial monitor
    Serial.print(botDirection);
    Serial.print("");
    Serial.println(distance.toInt());

    if(botDirection == "f")                          //if the entered direction is forward
    {
      rightMotor(200);                                //drive the right wheel forward
      leftMotor(200);                                 //drive the left wheel forward
      delay(driveTime * distance.toInt());            //drive the motors long enough travel the entered distance
      rightMotor(0);                                  //turn the right motor off
      leftMotor(0);                                   //turn the left motor off
    }
    else if(botDirection == "b")                     //if the entered direction is backward
    {
      rightMotor(-200);                               //drive the right wheel forward
      leftMotor(-200);                                //drive the left wheel forward
      delay(driveTime * distance.toInt());            //drive the motors long enough travel the entered distance
      rightMotor(0);                                  //turn the right motor off
      leftMotor(0);                                   //turn the left motor off
    }
    else if(botDirection == "l")                      //if the entered direction is right
    {
      rightMotor(-200);                               //drive the right wheel forward
      leftMotor(255);                                 //drive the left wheel forward
      delay(turnTime * distance.toInt());             //drive the motors long enough turn the entered distance
      rightMotor(0);                                  //turn the right motor off
      leftMotor(0);                                   //turn the left motor off
    }
    else if(botDirection == "r")                    //if the entered direction is left
    {
      rightMotor(255);                                //drive the right wheel forward
      leftMotor(-200);                                //drive the left wheel forward
      delay(turnTime * distance.toInt());             //drive the motors long enough turn the entered distance
      rightMotor(0);                                  //turn the right motor off
      leftMotor(0);                                   //turn the left motor off
    }
  }
}
/********************************************************************************/
void rightMotor(int motorSpeed)                       //function for driving the right motor
{
  if (motorSpeed > 0)                                 //if the motor should drive forward (positive speed)
  {
    digitalWrite(AIN1, HIGH);                         //set pin 1 to high
    digitalWrite(AIN2, LOW);                          //set pin 2 to low
  }
  else if (motorSpeed < 0)                            //if the motor should drive backwar (negative speed)
  {
    digitalWrite(AIN1, LOW);                          //set pin 1 to low
    digitalWrite(AIN2, HIGH);                         //set pin 2 to high
  }
  else                                                //if the motor should stop
  {
    digitalWrite(AIN1, LOW);                          //set pin 1 to low
    digitalWrite(AIN2, LOW);                          //set pin 2 to low
  }
  analogWrite(PWMA, abs(motorSpeed));                 //now that the motor direction is set, drive it at the entered speed
}

/********************************************************************************/
void leftMotor(int motorSpeed)                        //function for driving the left motor
{
  if (motorSpeed > 0)                                 //if the motor should drive forward (positive speed)
  {
    digitalWrite(BIN1, HIGH);                         //set pin 1 to high
    digitalWrite(BIN2, LOW);                          //set pin 2 to low
  }
  else if (motorSpeed < 0)                            //if the motor should drive backwar (negative speed)
  {
    digitalWrite(BIN1, LOW);                          //set pin 1 to low
    digitalWrite(BIN2, HIGH);                         //set pin 2 to high
  }
  else                                                //if the motor should stop
  {
    digitalWrite(BIN1, LOW);                          //set pin 1 to low
    digitalWrite(BIN2, LOW);                          //set pin 2 to low
  }
  analogWrite(PWMB, abs(motorSpeed));                 //now that the motor direction is set, drive it at the entered speed
}

What You Should See

Open the Serial Monitor. It should prompt you to enter a command that contains a direction and distance. When you type a direction and distance into the serial monitor the robot will move or turn.

SIK_Project5_Circuit5B_Action

Program Overview

  1. Prompt the user to enter a command and list the shortcuts for the directions.
  2. Wait for a serial command.
  3. Read the first part of the serial command and set that as the direction. Then read the second part of the command and set it as the distance:
    1. If the direction is “f”, drive both motors forward for the distance.
    2. If the direction is “b”, drive both motors backward for the distance.
    3. If the direction is “r”, drive the right motor backward and the left motor forward.
    4. If the direction is “l”, drive the left motor backward and the right motor forward.

Code to Note

CodeDescription
Parsing Strings:
Serial.readStringUntil(‘ ‘);
Reads a serial message until the first space and saves it as a string.
String to Int:
string_name.toInt();
If a number is stored in a string variable, this will convert it to an integer, which can be used in math equations.
User Functions Description
rightMotor(motor_distance);Drive the right motor long enough to travel the specified distance.
leftMotor(motor_distance);Drive the left motor long enough to travel the specified distance.

Coding Challenges

ChallengeDescription
Replace the switch with a buttonTry wiring a button into the circuit instead of the sliding switch. Now the motor only turns on when you push the button!
Replace the switch with a sensorTry changing the code so that the motor is activated by another sensor, like the photoresistor.

Troubleshooting

ProblemSolution
Motor not spinningCheck the wiring to the motor driver. There are a lot of connections, and it’s easy to mix one of them up with another. If only one motor is working, check the wires coming from the non-working motor. Make sure they have not come loose from the motor.
Switch not workingMake sure that you are hooked up to the middle pin and one side pin on the switch.
Still not working?Jumper wires unfortunately can go "bad" from getting bent too much. The copper wire inside can break, leaving an open connection in your circuit. If you are certain that your circuit is wired correctly and that your code is error-free and uploaded but you are still encountering issues, try replacing one or more of the jumper wires for the component that is not working.

Circuit 5C: Autonomous Robot

Free the robots! In this circuit, you’ll unplug your robot and program it to navigate the world on its own. When the robot senses an object using the distance sensor, it will back up and change course.

SIK_Project5_Circuit5C_Hero

Parts Needed

Grab the following quantities of each part listed to build this circuit:

parts

Additional Materials

  • Scissors (NOT INCLUDED)
  • 4x AA Batteries (NOT INCLUDED)

New Concepts

Autonomous Vehicles

The robot that you will build uses a simple sensor to avoid obstacles. This kind of system is used in Mars rovers, autonomous cars and the bots built for all kinds of robotics competitions. Understanding this example code will set you on the path to building bigger and better autonomous vehicles!

Hardware Hookup

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.

Keep in mind that the ultrasonic distance sensor needs a clear path to avoid unwanted interruptions in your robot’s movements. Keep the distance sensor clear of any wires from your circuit.

RobotAssembySensor

Battery Holder Attachment

It’s time to make this robot mobile by adding the battery pack.

If you did not attach the battery pack in Project 4, cut two pieces of Dual Lock that are about 1 inch x 1 inch (2.5cm x 2.5cm) each. Remove the adhesive backing and attach one piece to the back of the battery holder.

Battery Holder Dual Lock

Adhere the second piece to the bottom of the baseplate, directly in the middle.

RobotAssembly4

Press the battery holder to the baseplate so that the two pieces of Dual Lock snap together. Insert the batteries into the holder if you have not done so already. Remember that batteries are polarized and can only go in one way.

RobotAssembly6

Clip the binder clip back on, and you are ready to roll!

You can choose to remove the motors and battery pack while you build the circuit or leave them on. The choice is yours.

Circuit Diagram

Circuit_5C

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

ComponentRedBoardBreadboardBreadboardBreadboardBreadboard
Jumper Wire5V5V Rail ( + )
Jumper WireGNDGND Rail ( - )
Jumper Wire5V Rail ( + )5V Rail ( + )
Jumper WireGND Rail ( - )GND Rail ( - )
Jumper WireVINA1
C1-C8
(VM on C1)
G1-G8
(PWMA on G1)
Jumper WireA25V Rail ( + )
Jumper WireA3GND Rail ( - )
Jumper WireDigital Pin 8J7
Jumper WireDigital Pin 9J6
Jumper WireDigital Pin 10J5
Jumper WireJ45V Rail ( + )
Jumper WireDigital Pin 11J3
Jumper WireDigital Pin 12J2
Jumper WireDigital Pin 13J1
A4 (Red +)A5 (Black -)
A6 (Black -)A7 (Red +)
SwitchF25F26F27
Jumper WireI26GND Rail ( - )
Jumper WireDigital Pin 7I27
A14 (Vcc)A15 (Trig)A16 (Echo)A17 (GND)
Jumper WireDigital Pin 6E15 (Trig)
Jumper WireDigital Pin 5E16 (Echo)
Jumper WireE145V Rail ( + )
Jumper WireE17GND Rail ( - )

In the table, polarized components are shown with a warning triangle and the whole row highlighted yellow.

Open the Sketch

Heads up! Make sure your switch is in the OFF position. As soon as the code is finished uploading, your robot will begin driving. Make sure it cannot drive off a table or other high surface and injure itself.

To open the code, go to: File > Examples > SIK_Guide_Code-V_4 > SIK_Circuit_5C-AutonomousRobot

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
Circuit 5C - Autonomous Robot

This robot will drive around on its own and react to obstacles by backing up and turning to a new direction.
This sketch was adapted from one of the activities in the SparkFun Guide to Arduino.
Check out the rest of the book at
https://www.sparkfun.com/products/14326

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v40
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
*/

//distance variables

const int trigPin = 6;
const int echoPin = 5;


//the left motor will be controlled by the motor B pins on the motor driver
const int PWMB = 8;           //speed control pin on the motor driver for the left motor
const int BIN2 = 9;           //control pin 2 on the motor driver for the left motor
const int BIN1 = 10;           //control pin 1 on the motor driver for the left motor

//the right motor will be controlled by the motor A pins on the motor driver
const int AIN1 = 11;           //control pin 1 on the motor driver for the right motor
const int AIN2 = 12;            //control pin 2 on the motor driver for the right motor
const int PWMA = 13;            //speed control pin on the motor driver for the right motor



int switchPin = 7;             //switch to turn the robot on and off

float distance = 0;            //variable to store the distance measured by the distance sensor

//robot behavior variables
int backupTime = 300;           //amount of time that the robot will back up when it senses an object
int turnTime = 200;             //amount that the robot will turn once it has backed up

/********************************************************************************/
void setup()
{
  pinMode(trigPin, OUTPUT);       //this pin will send ultrasonic pulses out from the distance sensor
  pinMode(echoPin, INPUT);        //this pin will sense when the pulses reflect back to the distance sensor

  pinMode(switchPin, INPUT_PULLUP);   //set this as a pullup to sense whether the switch is flipped


  //set the motor contro pins as outputs
  pinMode(AIN1, OUTPUT);
  pinMode(AIN2, OUTPUT);
  pinMode(PWMA, OUTPUT);

  pinMode(BIN1, OUTPUT);
  pinMode(BIN2, OUTPUT);
  pinMode(PWMB, OUTPUT);

  Serial.begin(9600);                       //begin serial communication with the computer
  Serial.print("To infinity and beyond!");  //test the serial connection
}

/********************************************************************************/
void loop()
{
  //DETECT THE DISTANCE READ BY THE DISTANCE SENSOR
  distance = getDistance();

  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" in");              // print the units

  if(digitalRead(switchPin) == LOW){  //if the on switch is flipped

    if(distance < 10){                //if an object is detected
      //back up and turn
      Serial.print("");
      Serial.print("BACK!");

      //stop for a moment
      rightMotor(0);
      leftMotor(0);
      delay(200);

      //back up
      rightMotor(-255);
      leftMotor(-255);
      delay(backupTime);

      //turn to the right
      rightMotor(-255);
      leftMotor(255);
      delay(turnTime);

    }else{                         //if no obstacle is detected drive forward
      Serial.print("");
      Serial.print("Moving...");


      rightMotor(255);
      leftMotor(255);
    }
  } else{                         //if the switch is off then stop

      //stop the motors
      rightMotor(0);
      leftMotor(0);
  }

  delay(50);                      //wait 50 milliseconds between readings
}

/********************************************************************************/
void rightMotor(int motorSpeed)                       //function for driving the right motor
{
  if (motorSpeed > 0)                                 //if the motor should drive forward (positive speed)
  {
    digitalWrite(AIN1, HIGH);                         //set pin 1 to high
    digitalWrite(AIN2, LOW);                          //set pin 2 to low
  }
  else if (motorSpeed < 0)                            //if the motor should drive backwar (negative speed)
  {
    digitalWrite(AIN1, LOW);                          //set pin 1 to low
    digitalWrite(AIN2, HIGH);                         //set pin 2 to high
  }
  else                                                //if the motor should stop
  {
    digitalWrite(AIN1, LOW);                          //set pin 1 to low
    digitalWrite(AIN2, LOW);                          //set pin 2 to low
  }
  analogWrite(PWMA, abs(motorSpeed));                 //now that the motor direction is set, drive it at the entered speed
}

/********************************************************************************/
void leftMotor(int motorSpeed)                        //function for driving the left motor
{
  if (motorSpeed > 0)                                 //if the motor should drive forward (positive speed)
  {
    digitalWrite(BIN1, HIGH);                         //set pin 1 to high
    digitalWrite(BIN2, LOW);                          //set pin 2 to low
  }
  else if (motorSpeed < 0)                            //if the motor should drive backwar (negative speed)
  {
    digitalWrite(BIN1, LOW);                          //set pin 1 to low
    digitalWrite(BIN2, HIGH);                         //set pin 2 to high
  }
  else                                                //if the motor should stop
  {
    digitalWrite(BIN1, LOW);                          //set pin 1 to low
    digitalWrite(BIN2, LOW);                          //set pin 2 to low
  }
  analogWrite(PWMB, abs(motorSpeed));                 //now that the motor direction is set, drive it at the entered speed
}

/********************************************************************************/
//RETURNS THE DISTANCE MEASURED BY THE HC-SR04 DISTANCE SENSOR
float getDistance()
{
  float echoTime;                   //variable to store the time it takes for a ping to bounce off an object
  float calcualtedDistance;         //variable to store the distance calculated from the echo time

  //send out an ultrasonic pulse that's 10ms long
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  echoTime = pulseIn(echoPin, HIGH);      //use the pulsein command to see how long it takes for the
                                          //pulse to bounce back to the sensor

  calcualted Distance = echoTime / 148.0;  //calculate the distance of the object that reflected the pulse (half the bounce time multiplied by the speed of sound)

  return calcualtedDistance;              //send back the distance that was calculated
}

What You Should See:

When the switch is turned off, the robot will sit still. When the switch is turned on, the robot will drive forward until it senses an object.

SIK_Project5_Circuit5C_Action 1

When it does, it will stop, back up and turn to the right before driving forward again.

SIK_Project5_Circuit5C_Action 2

Troubleshooting Warning: HVAC systems in offices and schools have been known to interfere with the performance of the ultrasonic distance sensor. If you are experiencing sporadic behavior from your circuit, check your surroundings. If there are numerous air ducts in the room you are using, try moving to a different room that does not have ducts. The airflow from these ducts can interfere with the waves sent from the sensor, creating noise and resulting in bad readings.

Program Overview

  1. If the switch is turned on,
  2. Then start sensing the distance.
    1. If no obstacle is detected, then drive forward.
    2. If an obstacle is detected, stop, back up, and turn right.
    3. If no obstacle is detected, start driving forward again.

Code to Note

This code builds upon all the concepts you’ve learn in all the previous projects. There are no new functions or objects.

Coding Challenges

ChallengeDescription
Change the distance at which your robot reactsTry changing the distance at which your robot stops and turns away from an obstacle.
Change the behavior of the robot when it senses an obstacleTry changing the code so that your robot does something different when it senses an obstacle.

Troubleshooting

ProblemSolution
The robot drives backward and/or turns in the wrong directionCheck the wiring of your motors and the way that they are mounted to the breadboard and Arduino holder. If one of your motors is flipped around, reposition it, or switch its black and red wires on the breadboard (this will reverse the direction that it turns).
The robot runs into obstaclesYou can try gently bending the pins of the distance sensor so that it points farther up, away from the floor. The robot will get stuck if one wheel hits an object that it is driving past (the distance sensor won’t see the obstacle unless it’s in front of the robot).
The robot drives backward and turns when there are no obstaclesMake sure the wires are not in front of the distance sensor. Also make sure you are not in a room with large HVAC vents. As in Project 3, these vents can wreak havoc on the ultrasonic distance sensor.
The robot drives slow or not at all, though the RedBoard is poweredIf your board is powered but the robot is slow, won't move at all, or is behaving sporadically, check the batteries. These behaviors are symptoms of low or dead batteries.
Still not working?Jumper wires unfortunately can go "bad" from getting bent too much. The copper wire inside can break, leaving an open connection in your circuit. If you are certain that your circuit is wired correctly and that your code is error-free and uploaded but you are still encountering issues, try replacing one or more of the jumper wires for the component that is not working.

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 RedBot

ROB-12649
$119.95
22
Raspberry Pi 3 Starter Kit

KIT-13826
$89.95
33
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
$149.95
4
SparkFun Inventor's Kit for Intel® Edison

KIT-13742
$149.95
2
SparkFun Inventor's Kit for LabVIEW

KIT-13271
$149.95
7
SparkFun Inventor's Kit for MicroView

KIT-13205
$74.95$49.95
11

Reference files are available here:

Thanks for following along!


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

Viewing all 1114 articles
Browse latest View live




Latest Images