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

SparkFun gator:soil Hookup Guide

$
0
0

SparkFun gator:soil Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Do you have a science experiment involving plant growth?

SparkFun gator:soil - micro:bit Accessory Board

SparkFun gator:soil - micro:bit Accessory Board

SEN-15272
$5.95

The gator:soil is the perfect tool to monitor the moisture content of the soil of your test subjects. This tutorial will show you how to get started using this soil moisture sensor with the gator:bit (v2) in the micro:bit development environment.

Required Materials

To get started, you'll need a micro:bit to control everything.

SparkFun Inventor's Kit for micro:bit

SparkFun Inventor's Kit for micro:bit

KIT-14542
5
micro:bit Go Bundle

micro:bit Go Bundle

DEV-14336
$16.50
16
micro:bit Board

micro:bit Board

DEV-14208
$14.95
7

To easily use the gator board ecosystem, one of the gator:bit boards will help breakout the necessary pins. You will also need alligator cables to connect the gator:bit to the gator:soil.

SparkFun gator:bit v2.0 - micro:bit Carrier Board

SparkFun gator:bit v2.0 - micro:bit Carrier Board

DEV-15162
$19.95
Alligator Test Leads - Multicolored (10 Pack)

Alligator Test Leads - Multicolored (10 Pack)

PRT-12978
$3.25
4
SparkFun gator:bit

SparkFun gator:bit

DEV-14484
$20.95

Suggested Reading

There isn't much to learning how to use the gator:soil (moisture sensor). However, you may find the following concepts useful along the way.

Voltage, Current, Resistance, and Ohm's Law

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

Analog to Digital Conversion

The world is analog. Use analog to digital conversion to help digital devices interpret the world.

Soil Moisture Sensor Hookup Guide

A quick hookup guide and project to get you started with the Soil Moisture Sensor from SparkFun.

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.

If you aren't familiar with the micro:bit, 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.

Getting Started with the micro:bit

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

How to Load MicroPython on a Microcontroller Board

This tutorial will show you how to load the MicroPython interpreter onto a variety of development boards.

SparkFun gator:bit v2 Hookup Guide

The gator:bit v2 is a breakout board for the BBC micro:bit. The gator:bit exposes almost every pin on the micro:bit to clippable pad with circuit protection. It also has as built-in addressable LEDs and a built-in buzzer.

Hardware Overview

The gator:soil consists of two probes and three pads (PWR, GND, and SIG).

Note: For more in-depth information on the circuitry, check out the blog post for the circuit that this sensor is based off.
ContactsDescription
PWR INPUT: Power to the sensor (3.3V - 5V).
SIG OUTPUT: Analog voltage representing the conductivity between the probes.
GND REFERENCE: Ground reference (0V).
Probes Used to sample soil moisture content for sensor.

Power

We recommend powering the gator:soil with between 3.3V - 5V. Please note that the analog value returned will vary depending on what voltage is provided for the sensor.

Power Connections
Power connection pads.

For use with the gator:bit (v2) and micro:bit, you should provide 3.3V through the PWR and GND pads. We recommend not powering the sensor constantly to reduce corrosion of the probes; this can be controlled through one of the digital pins of the gator:bit (v2).

Caution: One commonly known issue with soil moisture senors is their short lifespan due to corrosion of the electrodes from electrolysis. To combat this, we've had the PCB coated in Gold Finishing (Electroless Nickel Immersion Gold), which has a high decomposition potential. However, the life span of the sensor is limited. Applying a higher input voltage, taking frequent readings, and/or leaving the sensor on for extended periods of time will decrease the lifespan. For example, a simple way to extend the lifespan of your sensor is to only power it when you take a reading.

Output Signal

The two probes are used to measure the conductivity of the soil. SIG provides an analog voltage out that can be attached to an ADC pad on the gator:bit (v2).

Analog Connection
Analog signal connection pad.

The value read on SIG is dependent several variables such as soil composition, contact on the probes, soil compaction, amongst other factors. For example, if you have a high alkaline content in your soil, it will be more conducive and give you a high baseline reading. In most cases, you will probably need to calibrate your sensor reading for each soil sample and sensor. Once calibrated, for a fixed sensor, the primary variables to the measure conductivity in the soil will be the power input and moisture content of the soil.

Hardware Assembly

Note: Unfortunately, the design of this sensor isn't intended for long term exposure to outdoor environments. It is primarily intended for the classroom setting. This is due to the limitations in waterproofing the sensor and its connections.

Connecting your gator:soil to the gator:bit (v2) is simple. Connect GND to GND, SIG to an analog pin (P0-P2)1, and PWR to either 3.3V OUT or to a digital pin that is not in use (P0-P2, P8, P16, or P5). This can easily be done with alligator cables.

Hardware Assembly
Example of connections used in example. Click to enlarge.
Application
Example of gator:soil in use application. Click to enlarge.
gator:soilgator:bit (v2)
PWR 3.3V OUT or
Digital Pin: P0 - P2, P8, P16, or P5
SIGAnalog Pin: P0 - P2
GNDGND
Note: If accessible, pins P3, P4, and P10 can be used in addition for ADC measurements.

Adding the MakeCode Extension

Note: This tutorial assumes you are familiar with MakeCode, the gato:bit (v2), and the micro:bit board.

The easiest way to get started using the gator:soil is to use Microsoft MakeCode, a web-based block editor. This tutorial assumes you are familiar with the with MakeCode, the gato:bit (v2), and the micro:bit development board. If this is your first time check out this guides linked in the suggested reading section (above).

Installing Extensions

To get started with using MakeCode with the miccro:bit, head over to the MakeCode for micro:bit website by Microsoft. Then, click the New Project button to start a new project and open the Editor. (*Yes, all you only need to get start coding is a computer with internet access, an up-to-date web browser, and an available USB port!)

MakeCode Website
Click the New Project button to start a new project and open the Editor. Click on image to enlarge.

Once you have the editor up, click on the the Advanced block in the block library to reveal the drop down menu.

Editor
Click on the the Advanced block in the block library to reveal the drop down menu. Click on image to enlarge.

Finally, click on the Extensions block. This should bring up the extensions page. (*Alternatively, you could also click on the extensions link from the settings menu.)

Advanced Block
Click on the the Extensions block to open the extensions page. Click on image to enlarge.

There are two methods for finding the gator:soil extension:

  • Search for the name used on the extension2.
  • Use the link to the GitHub repository for the pxt-package as the search term.

Extensions Page
Use the search bar to find the extension you want to install. Click on image to enlarge.
Note: Unfortunately, it does take time to get an extension approved by the micro:bit Educational Foundation before it can be searchable by name. Part of the requirements for the approval process involves a live product page. Therefore, at the time of the launch of this product, the extension has not been approved yet and the only method of adding the extension is to use the link to the GitHub repository of the pxt-package. We will update this tutorial as soon as the extension has been approved.

Search for the PXT-Package

Search for the gator:soil extension using the GitHub repository link to the pxt-package:

https://github.com/sparkfun/pxt-gator-soil

Search for Extension
Search for Extension. Then, click on the box to add it to the block library. Click on image to enlarge.

Then, click on the box for the extension to add it to the block library. The gator:soil extension should now appear in the block library.

Extension in Block Library
Extension in the block library; click on the block to open menu options. Click on image to enlarge.

To verify that you have added the extension, click on the gator:soil block to make sure that your drop down menu options match the image below.

Menu Options
Available blocks for the gator:soil extension. Click on image to enlarge.

MakeCode Example

Now that you have added the gator:soil extension to the Editor, lets start with some example code. Plug the micro:bit into your computer using an USB micro-B cable after you have assembled your hardware with the instructions from the previous section. The micro:bit should appear on your computer as a removable storage device.

USB Drive
The micro:bit showing up as a USB drive on a Windows computer. Click to enlarge.

To upload new code, this is where you will be copying the downloaded .hex file to later.

Block Function

Get moisture on pin _____ in _____ using power pin _____
This is a value block as indicated by the block's shape. There are three drop down menus with selectable options for how the sensor is wired and the output value of the block. Below is a description of the available menu options (from left to right):

  1. ADC or SIG Read Pin- This pin is used to read the SIG output of the sensor. The pin options are as follows:
    • P0 to P20
      • P5 to P9& P11 to P20: Digital pins that can't be used as indicated with (write only).
      • Pins P0 to P4 and P10: Analog pins that can be used, but the only pins that are available on the gator:bit (v2) are P0, P1, and P2.
  2. Measurement Value
    This designates the output value that is read. There are two options:
    • moisture- A value ranging between 0 and 1.
    • adcvalue- A 10-bit integer value from micro:bit ADC ranging between 0 and 1023.
  3. Power Control Pin
    This pin is used to control when the sensor input power (PWR). The pin options are as follows:
    • P0 to P20
      • Only pins P0 - P2, P5, P8, P11, P13 - P16, and P19 - P20 are available on the gator:bit (v2).
Note: Each measurement is taken with the shortest instance possible so that the power pin doesn't need to be toggled on and off. However, control logic or time delays should be added to reduce the frequency of these measurements. Without such controls, the sensor will be constantly polled in the forever loop, reducing the life span of the probes.

System Calibration

To get any sort of useful data out of your Soil Moisture Sensor, it is advised that you calibrate it to whatever soil you plan to monitor. Different types of soil can affect the sensor, and you may get different readings from one composition to the next. Before you start storing moisture data or triggering events based on that value, you should see what values you are actually getting from your sensor.

Once you have an idea what values your sensor is outputting in completely dry and completely wet situations, it's time to calibrate your sensor for the specific soil you want to monitor. Test your soil when it is as dry as possible, then measure it when the soil is completely saturated with moisture. Getting these values and comparing them to the ones from the previous calibration will give you the best insight into what values mean for your specific plant and soil. This test may take some trial and error and patience. Be careful not to splash water onto the sensor or over-water/under-water your plants during these tests.

Once you have a good handle on the values you can expect, you can map function under the Pins library block to adjust your results.

Basic Read

Below, is a simple example of how to take simple measurements from the sensor. The example uses a extremely short 10 second delay between measurements, primarily for demonstration purposes. To use this example, there are multiple options for accessing the .hex file:

  • Replicate the block functions from the display below to copy the example project. Then download the .hex file.
  • Expand the display widow to pull up the example project. Then download the .hex file.
  • Use this link to pull up the example project. Then download the .hex file.
  • Download the .hex file from the button below or the link on the bottom of the display.

The output is redirected over the serial port to avoid conflicts on pins P0 and P1, which are also used for serial communication. To read the sensor values, pull up your favorite serial terminal emulator. Then, connect to the serial port that the micro:bit is on; the default baud rate is 115200 bps. Below, is an example of the sensor output for the example code.

Sample Readings
Example of readings from the sensor.
Note: In application, to maximize the life of the sensor with daily monitoring, measurements should be limited to less than 3 measurements a day.

Troubleshooting Tips

Here are a few tips for troubleshooting this device.

Sensor Corrosion

A commonly known issue with soil moisture senors is their short lifespan due to corrosion of the electrodes from electrolysis. To combat this, we've had the PCB coated in Gold Finishing (Electroless Nickel Immersion Gold), which has a high decomposition potential. However, the life span of the sensor is limited. Applying a higher input voltage, taking frequent readings, and/or leaving the sensor on for extended periods of time will decrease the lifespan.

A simple way to extend the lifespan of your sensor is to only power it for the short period of a reading.

Waterproofing

A commonly known issue with soil moisture senor is that it may be exposed to water when you water your plants. Unfortunately, water and electronics do not mix. To prevent shorting out your board and sensor, you should always disconnect your cables when watering your plant. (*You can remove the sensor, but then you will need to recalibrate the sensor every time and this will affect the consistency of your readings.)

Calibration

To get any sort of useful data out of your sensor, it is advised that you calibrate it to whatever soil you plan to monitor. Different types of soil have various affects on the sensor; you may get different readings from one soil sample to the next. Before you start storing moisture data or triggering events based on that value, you should see what values you are actually getting from your sensor.

If you still have questions or issues with this product, please create a post on our forum under the Gator Products topic.

Additionally, if you are an educator and you have class or application based questions, please create a post on our forum under the Educational Products topic.

Resources and Going Further

For more product information, check out the resources below:

Interested in the micro:bit? Check out some of these other micro:bit products:

SparkFun Inventor's Kit for micro:bit Lab Pack

SparkFun Inventor's Kit for micro:bit Lab Pack

LAB-15229
$450.00
SparkFun gator:bit v2.0 - micro:bit Carrier Board

SparkFun gator:bit v2.0 - micro:bit Carrier Board

DEV-15162
$19.95
SparkFun Inventor's Kit for micro:bit

SparkFun Inventor's Kit for micro:bit

KIT-15228
$49.95
micro:bit Educator Lab Pack

micro:bit Educator Lab Pack

LAB-15230
$299.95

Need some inspiration for your next project? Check out some of these other micro:bit product tutorials:

micro:bit Breakout Board Hookup Guide

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

How to Load MicroPython on a Microcontroller Board

This tutorial will show you how to load the MicroPython interpreter onto a variety of development boards.

Gator:control ProtoSnap Hookup Guide

Buttons and switches and inputs oh my! Start adding more control to your gator:bit with the SparkFun gator:control.

How to Create a MakeCode Package for Micro:Bit

Learn how to develop code blocks for the Micro:bit in Microsoft MakeCode!

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


SparkFun gator:particle Hookup Guide

$
0
0

SparkFun gator:particle Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Do you have an experiment involving biometrics or particle detection?

SparkFun gator:particle - micro:bit Accessory Board

SparkFun gator:particle - micro:bit Accessory Board

SEN-15271
$10.95

The gator:particle is an amazing tool that uses a high-sensitivity pulse oximeter and heart-rate sensor, the MAX30102. Similar to the SparkFun Particle Sensor, with the MAX30105 high-sensitivity optical sensor, the gator:particle can also be used for particle detection. The primary difference between these boards is that the SparkFun Particle Sensor also uses a green LED that requires more power than the micro:bit can provide. This tutorial will show you how to get started using the gator:particle sensor with the gator:bit (v2) in the micro:bit development environment.

Required Materials

To get started, you'll need a micro:bit to control everything.

SparkFun Inventor's Kit for micro:bit

SparkFun Inventor's Kit for micro:bit

KIT-14542
5
micro:bit Go Bundle

micro:bit Go Bundle

DEV-14336
$16.50
16
micro:bit Board

micro:bit Board

DEV-14208
$14.95
7

To easily use the gator board ecosystem, one of the gator:bit boards will help breakout the necessary pins. You will also need alligator cables to connect the gator:bit to the gator:particle.

SparkFun gator:bit v2.0 - micro:bit Carrier Board

SparkFun gator:bit v2.0 - micro:bit Carrier Board

DEV-15162
$19.95
Alligator Test Leads - Multicolored (10 Pack)

Alligator Test Leads - Multicolored (10 Pack)

PRT-12978
$3.25
4
SparkFun gator:bit

SparkFun gator:bit

DEV-14484
$20.95

Suggested Reading

There isn't much to learning how to use the gator:particle sensor. However, you may find the following concepts useful along the way.

Light

Light is a useful tool for the electrical engineer. Understanding how light relates to electronics is a fundamental skill for many projects.

Logic Levels

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

I2C

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

MAX30105 Particle and Pulse Ox Sensor Hookup Guide

The SparkFun MAX30105 Particle Sensor is a flexible and powerful sensor enabling sensing of distance, heart rate, particle detection, even the blinking of an eye. Get ready. Set. Shine!

If you aren't familiar with the micro:bit, 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.

Getting Started with the micro:bit

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

How to Load MicroPython on a Microcontroller Board

This tutorial will show you how to load the MicroPython interpreter onto a variety of development boards.

SparkFun gator:bit v2 Hookup Guide

The gator:bit v2 is a breakout board for the BBC micro:bit. The gator:bit exposes almost every pin on the micro:bit to clippable pad with circuit protection. It also has as built-in addressable LEDs and a built-in buzzer.

Hardware Overview

The gator:particle consists of 4 pads for power and data.

ContactsDirectionDescription
GNDN/AGround: Reference voltage and ground loop.
3.3VInPower: Provides 3.3V to board.
SDABi-directionalData: Data and commands are transmitted between the sensor and microcontroller.
SCLInClock: The microcontroller provides the timing needed to communicate on the data line.

Power

The specified operating voltage for the MAX30102 is between 1.7V - 2V. For use with the gator:bit (v2) and micro:bit, you should provide 3.3V through the 3V3 and GND pads to keep the logic levels consistent; the 3.3V input is then regulated to 1.8V for the MAX30102.

Power Connections and LED
Power connection pads and power indication LED.

MAX30102

The MAX30102 is a high-sensitivity pulse oximeter and heart-rate sensor that communicates over an I2C bus. The MAX30102 uses both red and IR LEDs along with a very sensitive photodetector for pulse oximetry (SpO2), heart-rate (HR) monitoring, and particle (PM) detection. For the most part, users will only need to know I2C addresses to prevent address conflicts with other devices or sensors.

MAX30102 IC
MAX30102: HR and SpO2 sensor.

Here are some of the characteristics of the MAX30102 sensor from the datasheet:

CharacteristicRange
Operating Voltage1.8V to 2V
Supply Current Heart Rate and SpO2 Mode: 600 to 1200 µA
IR Only Mode: 600 to 1200 µA
Operating Temperature-40°C to 85°C
(ΣΔ) ADC Resolution: 15 to 18-bits (programmable)
Sampling Rate: 50 - 3200 sps (programmable)
IR LED LED Wavelength: 870 to 900 nm (avg. 880 nm)
Forward Voltage: 1.4V
Radiant Power: 6.5 mW
LED Driver Current: 0 to 50 mA (programmable)
Red LED LED Wavelength: 650 to 670 nm (avg. 660 nm)
Forward Voltage: 2.1V
Radiant Power: 9.8 mW
LED Driver Current: 0 to 50 mA (programmable)
Photodetector Spectral Range of Sensitivity: 600 to 900 nm
Radiant Sensitive Area: 1.36 mm2
I2C Address 0xAE - Write Address
0xAF - Read Address

What are Heart-Rate and Oxygen Saturation?

Heart-rate is the speed at which your heart pumps blood through your body. Pulse oximetry is a noninvasive method of determining saturation of oxygen in your blood. However, this is a peripheral measurement is not always a direct reflection of the arterial oxygen saturation (SaO2), but two are correlated enough for clinical purposes. There are a multitude of applications for these measurements; especially, in the medical field.

Here are some examples of studies using HR monitoring and pulse oximetry:

Here are additional resources on how the MAX30102 functions for HR detection and pulse oximetry:

Note: The MAX30102 can be used as a biosensor that for SpO2 and HR measurements on finger tips or earlobes. The sensor does need good contact with constant pressure against the epidermis for accurate results.

What are Particulates?

Particulate matter is the accumulation of matter (solid or liquid) in Earth's atmosphere. These particles vary in size, composition, and distribution. Their effects range from individual health on a microscopic scale to regional climate on a macroscopic scale. Particulate matter is also used in the food industry. Apiarist traditionally use bee smokers when harvesting honey. Smoking is also a method of flavoring and preserving meats and other products.

Here is a link to some experiments involving PM:

For more information on particulate matter and their detection, check out some of these resources:

Note: Particle detection is another application of the MAX30102. The sensor relies on the reflection and scattering of the red and IR light from particles to detect their presence.

I2C Connection

I2C is a communication protocol used to transfer data between master and slave devices. It is a 2-wire connection consisting of SDA (data) and SCL (clock). The protocol is pretty well defined so it can be shared with multiple devices. This is beneficial for daisy chaining multiple devices together on a single bus. The primary thing users will need to watch out for is address conflicts (you can't have devices with the same address).

I2C Connection
I2C connection pads.

Hardware Assembly

Connecting your gator:particle to the gator:bit (v2) is simple. The board can also be daisy-chained with other I2C boards. This can easily be done with alligator cables.

Hardware Assembly
Hardware assembly of connections used in example. Click to enlarge.
Daisy Chain
Example of daisy chaining multiple I2C gator boards. Click to enlarge.
Gator:UVGND3V3SDASCL
Gator:BitGND3.3V OUTP20 (SDA)P19 (SCL)

Adding the MakeCode Extension

Note: This tutorial assumes you are familiar with MakeCode, the gato:bit (v2), and the micro:bit board.

The easiest way to get started using the gator:particle is to use Microsoft MakeCode, a web-based block editor. This tutorial assumes you are familiar with the with MakeCode, the gato:bit (v2), and the micro:bit development board. If this is your first time check out this guides linked in the suggested reading section (above).

Installing Extensions

To get started with using MakeCode with the miccro:bit, head over to the MakeCode for micro:bit website by Microsoft. Then, click the New Project button to start a new project and open the Editor. (*Yes, all you only need to get start coding is a computer with internet access, an up-to-date web browser, and an available USB port!)

MakeCode Website
Click the New Project button to start a new project and open the Editor. Click on image to enlarge.

Once you have the editor up, click on the the Advanced block in the block library to reveal the drop down menu.

Editor
Click on the the Advanced block in the block library to reveal the drop down menu. Click on image to enlarge.

Finally, click on the Extensions block. This should bring up the extensions page. (*Alternatively, you could also click on the extensions link from the settings menu.)

Advanced Block
Click on the the Extensions block to open the extensions page. Click on image to enlarge.

There are two methods for finding the gator:particle extension:

  • Search for the name used on the extension3.
  • Use the link to the GitHub repository for the pxt-package as the search term.

Extensions Page
Use the search bar to find the extension you want to install. Click on image to enlarge.
Note: Unfortunately, it does take time to get an extension approved by the micro:bit Educational Foundation before it can be searchable by name. Part of the requirements for the approval process involves a live product page. Therefore, at the time of the launch of this product, the extension has not been approved yet and the only method of adding the extension is to use the link to the GitHub repository of the pxt-package. We will update this tutorial as soon as the extension has been approved.

Search for the PXT-Package

Search for the gator:particle extension using the GitHub repository link to the pxt-package:

https://github.com/sparkfun/pxt-gator-particle

Search for Extension
Search for Extension. Then, click on the box to add it to the block library. Click on image to enlarge.

Then, click on the box for the extension to add it to the block library. The gator:particle extension should now appear in the block library.

Extension in Block Library
Extension in the block library; click on the block to open menu options. Click on image to enlarge.

To verify that you have added the extension, click on the gator:particle block to make sure that your drop down menu options match the image below.

Menu Options
Available blocks for the gator:particle extension. Click on image to enlarge.

MakeCode Example

Now that you have added the gator:particle extension to the Editor, lets start with some example code. Plug the micro:bit into your computer using an USB micro-B cable after you have assembled your hardware with the instructions from the previous section. The micro:bit should appear on your computer as a removable storage device.

USB Drive
The micro:bit showing up as a USB drive on a Windows computer. Click to enlarge.

To upload new code, this is where you will be copying the downloaded .hex file to later.

Block Functions

initialize gator:particle sensor
This block should be pretty self explanatory, it sets the sensor up to be used. You should use this within the on start block.

get _____ value
This is a value block as indicated by the block's shape. The output is an integer value from 0 to 262,143 for the sensor's detection of the specified wavelength. There is a drop down menu with selectable options for the sensor reading for the block. Below is a description of the available menu options:

  • red- An 18-bit integer value for sensor detection in the IR wavelength (0 and 262,143).
  • infrared- An 18-bit integer value for sensor detection in the IR wavelength (0 and 262,143).
  • With the default LED intensity, I was only able to see a maximum of approximately 120,000. To get higher values, the LED intensity needs to be turned up.

detect heartbeat in _____
This is a value block as indicated by the block's shape. There is a drop down menu with selectable options for the output value of the block. Below is a description of the available menu options:

  • BPM- Outputs a single heart-rate measurement in beats per minute (BPM).
  • AVG- Outputs the average of the last four heart-rate readings in BPM.

Set LED mode to read _____
This block should allows users to designate the LED modes. There are only two opions:

  • red- Only the red LED is used or on.
  • red & infrared- Both the red and IR LEDs are on.
  • There is no option to use only the IR LED.

Change strength of _____ to _____
This block should allows users to control the brightness or intensity of the LEDs.

  1. LED- Users designate which LED to control.
    • red
    • infrared
  2. Strength- Users specify the intensity of the LED. Enter an integer.
    • 0 to 255

Basic Read

Below, is a simple example of how to take simple measurements from the sensor. To use this example, there are multiple options for accessing the .hex file:

  • Replicate the block functions from the display below to copy the example project. Then download the .hex file.
  • Expand the display widow to pull up the example project. Then download the .hex file.
  • Use this link to pull up the example project. Then download the .hex file.
  • Download the .hex file from the button below or the link on the bottom of the display.

The output is redirected over the serial port to avoid conflicts on pins P0 and P1, which are also used for serial communication. To read the sensor values, pull up your favorite serial terminal emulator. Then, connect to the serial port that the micro:bit is on; the default baud rate is 115200 bps. Below, is an example of the sensor output for the example code.

Sample Readings
Example of readings from the sensor.

Troubleshooting Tips

Here are a few tips for troubleshooting this device.

Heart-Rate and SpO2

Make sure that you are making good contact and have constant pressure on the sensor. For the best results, use your finger tip. A special open-source algorithm is used to determine the Heart-Rate and SpO2 measurements. The algorithm is relatively accurate, but is primarily meant for demonstration purposes and should not be used in critical applications for monitoring a person's health.

If you still have questions or issues with this product, please create a post on our forum under the Gator Products topic.

Additionally, if you are an educator and you have class or application based questions, please create a post on our forum under the Educational Products topic.

Resources and Going Further

For more product information, check out the resources below:

Interested in the micro:bit? Check out some of these other micro:bit products:

SparkFun Inventor's Kit for micro:bit Lab Pack

SparkFun Inventor's Kit for micro:bit Lab Pack

LAB-15229
$450.00
SparkFun gator:bit v2.0 - micro:bit Carrier Board

SparkFun gator:bit v2.0 - micro:bit Carrier Board

DEV-15162
$19.95
SparkFun Inventor's Kit for micro:bit

SparkFun Inventor's Kit for micro:bit

KIT-15228
$49.95
micro:bit Educator Lab Pack

micro:bit Educator Lab Pack

LAB-15230
$299.95

Need some inspiration for your next project? Check out some of these other micro:bit product tutorials:

micro:bit Educator Lab Pack Experiment Guide

A quickstart guide for the micro:bit educator lab pack.

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.

Wireless Remote Control with micro:bit

In this tutorial, we will utilize the MakeCode radio blocks to have the one micro:bit transmit a signal to a receiving micro:bit on the same channel. Eventually, we will control a micro:bot wirelessly using parts from the arcade:kit!
New!

SparkFun gator:environment Hookup Guide

The gator:environment combines two I2C sensors for temperature, humidity, pressure, eCO2, and eTVOC values. This tutorial will get you started using the gator:environment with the micro:bit platform.

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

SparkFun gator:microphone Hookup Guide

$
0
0

SparkFun gator:microphone Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Do you have an audio based science experiment?

SparkFun gator:microphone - micro:bit Accessory Board

SparkFun gator:microphone - micro:bit Accessory Board

SEN-15289
$6.95

The gator:microphone is a small board that combines a microphone and some processing circuitry. It provides not only an audio output, but also a binary indication of the presence of sound, and an analog representation of it's amplitude.

Required Materials

To get started, you'll need a micro:bit to control everything.

SparkFun Inventor's Kit for micro:bit

SparkFun Inventor's Kit for micro:bit

KIT-14542
5
micro:bit Go Bundle

micro:bit Go Bundle

DEV-14336
$16.50
16
micro:bit Board

micro:bit Board

DEV-14208
$14.95
7

To easily use the gator board ecosystem, one of the gator:bit boards will help breakout the necessary pins. You will also need alligator cables to connect the gator:bit to the gator:microphone.

SparkFun gator:bit v2.0 - micro:bit Carrier Board

SparkFun gator:bit v2.0 - micro:bit Carrier Board

DEV-15162
$19.95
Alligator Test Leads - Multicolored (10 Pack)

Alligator Test Leads - Multicolored (10 Pack)

PRT-12978
$3.25
4
SparkFun gator:bit

SparkFun gator:bit

DEV-14484
$20.95

Suggested Reading

The gator:microphone is pretty straight forward to use in application. However, you may find the following concepts useful along the way.

Logic Levels

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

I2C

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

Sound Detector Hookup Guide

The Sound Detector is a microphone with a binary output. This guide explains how it works and how you can use it in your projects.

Electret Mic Breakout Board Hookup Guide

An introduction to working with the Electret Mic Breakout Board.
New!

Qwiic 12-Bit ADC Hookup Guide

Need to add more analog inputs for your project? Check out the Qwiic 12-bit ADC.

If you aren't familiar with the micro:bit, 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.

Getting Started with the micro:bit

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

How to Load MicroPython on a Microcontroller Board

This tutorial will show you how to load the MicroPython interpreter onto a variety of development boards.

SparkFun gator:bit v2 Hookup Guide

The gator:bit v2 is a breakout board for the BBC micro:bit. The gator:bit exposes almost every pin on the micro:bit to clippable pad with circuit protection. It also has as built-in addressable LEDs and a built-in buzzer.

Hardware Overview

The gator:microphone consists of 4 pads for power and data. Additionally, there is a switch switch on the board to select different audio amplification levels; however, we will cover that in later.

ContactsDirectionDescription
GNDN/AGround: Reference voltage and ground loop.
3.3VInPower: Provides 3.3V to sensor.
SDABi-directionalData: Data and commands are transmitted between the sensor and microcontroller.
SCLInClock: The microcontroller provides the timing needed to communicate on the data line.

Power

The specified operating voltage for the VEML6070 is between 2.7V - 5.5V. For use with the gator:bit (v2) and micro:bit, you should provide 3.3V through the 3V3 and GND pads to keep the logic levels consistent.

Power Connections and LED
Power connection pads and power indication LED.

Electret Microphone

An electret microphone is a capacitor based microphone similar to the ones found in phones or headsets. For the most part, users will only need to know that this is used to convert sound into an electrical signal (audio signal).

Electret Microphone
Electret microphone.

Here are some of the characteristics of the electret microphone from the datasheet:

CharacteristicRange
Operating Voltage1.5V (Max 10V)
Supply Current0.3 mA (Max)
DirectivityOmnidirectional
Frequency Response20 to 16,000 Hz

What is Sound?

Sound is pretty self explanatory if you can sense it. Physically, sound is most commonly described as a wave of pressure that propagates through a medium (solid, liquid, or gas... sound can't move through a vacuum). The field of science involving the generation, propagation and reception of these waves (and vibrations) is acoustics. There are many characteristics and factors to sound waves along with various applications and methods of manipulation.


Sound frequency and intensity range for the the threshold of human hearing. Click to enlarge. [Source: Elementary Physics I - PY105 Notes: Sound; Boston University]

A graph correlating sound intensity and perceived loudness. Click to enlarge. [Source: The Scientist and Engineer's Guide to Digital Signal Processing]

Humans perceive sound through their ears. The frequency range of human hearing is approximately 20 to 20,000 Hz. Humans can detect sound intensities from 10-12 W/m2 to 1 W/m2; scaled to 0 - 120 in decibels (dB)1. The human threshold for hearing or the smallest discernible sound we can detect, is around 0 phon on the equal-loudness contours (~20 µPa)2.

LMV324

The LMV324 is an operational amplifier (op-amp) configured to process the audio signals from the microphone. Op-amps are versatile and among the most widely used electronic components. For the most part, users will only need to know that the LMV324 is configured to provide for three different outputs: the amplified audio signal, the envelope of the audio signal, and a noise gate indicator.

LMV324
LMV324 operational amplifier.

Here are some of the characteristics of the LMV324 op-amp from the datasheet:

CharacteristicRange
Operating Voltage2.7V to 5.5V
Supply Currentapprox. 300 to 720 µA

Below, is an signal capture of the three different outputs from the Sound Detector to illustrate their relation:

Signal Capture
Green- Amplified Audio Signal. Yellow- Envelope Signal. Red- Gate Signal.
Example of signal capture from the Sound Detector.

What is an Envelope Signal?

An envelope is a curve that essentially outlines the peaks or amplitude of a signal. There are various applications of an envelope in sound engineering. Most commonly this signal is used for preventing audio feedback, synthesizing a sound, or noise reduction in recordings. In the image below, an example of an envelope (yellow trace) of an audio signal as recorded from the Sound Detector, which is operates similarly to the gator:microphone.

Below are some additional resources on the applications of an envelope:

What is a Gate?

A gate is a comparative signal used to detect when the envelope signal passes a certain threshold. A common application is a noise gate, which is used to reduce the static noise of an recording by only passing music if a threshold is exceeded. Additionally, sound effects like the gated reverb, popularized in the 1980s, can also be created using special techniques.

Below are some additional resources on the applications for the gate:

Selectable Gain Switch

This switch is used to select different gains value to amplify the audio signal from the microphone; high, medium, and low. For the most part, users will only need to know that high the higher the amplification (or gain), the more sensitive the gator:microphone will be to audio inputs.

Gain Switch
Gain switch with three levels: high, medium, and low.
Switch LocationResistor ValueGain (Arithmetic)Gain (Decibel)
High1 MΩ100060 dB
Medium100 kΩ10040 dB
Low10 kΩ1020 dB
What is Gain?

Gain is the amplification of an electronic signal. In this instance, this is a voltage gain of the preamplifier from the original microphone electrical signal. In Low, the amplification is 10 times the original microphone voltage. In High, it is 1000 times the original microphone voltage or 100 times the voltage of the Low amplification.

Just like humans, sound can be too loud or soft for the electronics to discern any differences. When the electrical signal is too high, clipping can occur. To fix this the amplification should be lowered to bring the signal under the maximum range that can be measures. A signal is too soft, when the characteristics of the signal are below the resolution that you can measure. To fix this the amplification should be raised to detect those changes.

ADS1015

The ADS1015 is an analog to digital converter (ADC) used for converting analog voltages into a digital values that can be read by a microcontroller. The ADS1015 is used to measure the amplified audio signal, the envelope, and the gate. For the most part, users will only need to know I2C addresses to prevent address conflicts with other devices or sensors.

ADS1015
ADS1015 analog to digital converter.

Here are some of the characteristics of the ADS1015 from the datasheet:

CharacteristicDescription
Operating Voltage (VDD)2.0V to 5.5V
Operating Temperature-40°C to 125°C
Operation ModesSingle-Shot, Continuous-Conversion (Default), and Duty Cycling
Analog Inputs Measurement Type: Single-Ended (Default) or Differential
Input Voltage Range: GND to VDD
Full Scale Range (FSR): ±.256V to ±6.114V (Default: 2.048V)
Resolution 12-bit (Differential) or 11-bit (Single-Ended)
LSB size: 0.125mV - 3mV (Default: 1 mV)
Sample Rate128 Hz to 3.3 kHz (Default: 1600SPS)
Current Consumption (Typical)150μA to 200μA
I2C Address0x48

I2C Connection

I2C is a communication protocol used to transfer data between master and slave devices. It is a 2-wire connection consisting of SDA (data) and SCL (clock). The protocol is pretty well defined so it can be shared with multiple devices. This is beneficial for daisy chaining multiple devices together on a single bus. The primary thing users will need to watch out for is address conflicts (you can't have devices with the same address).

I2C Connection
I2C connection pads.

Hardware Assembly

Connecting your gator:microphone to the gator:bit (v2) is simple. The board can also be daisy-chained with other I2C boards. This can easily be done with alligator cables.

Hardware Assembly
Hardware assembly of connections used in example. Click to enlarge.
Daisy Chain
Example of daisy chaining multiple I2C gator boards. Click to enlarge.
gator:microphoneGND3V3SDASCL
gator:bit (v2)GND3.3V OUTP20 (SDA)P19 (SCL)

Adding the MakeCode Extension

Note: This tutorial assumes you are familiar with MakeCode, the gato:bit (v2), and the micro:bit board.

The easiest way to get started using the gator:microphone is to use Microsoft MakeCode, a web-based block editor. This tutorial assumes you are familiar with the with MakeCode, the gato:bit (v2), and the micro:bit development board. If this is your first time check out this guides linked in the suggested reading section (above).

Installing Extensions

To get started with using MakeCode with the miccro:bit, head over to the MakeCode for micro:bit website by Microsoft. Then, click the New Project button to start a new project and open the Editor. (*Yes, all you only need to get start coding is a computer with internet access, an up-to-date web browser, and an available USB port!)

MakeCode Website
Click the New Project button to start a new project and open the Editor. Click on image to enlarge.

Once you have the editor up, click on the the Advanced block in the block library to reveal the drop down menu.

Editor
Click on the the Advanced block in the block library to reveal the drop down menu. Click on image to enlarge.

Finally, click on the Extensions block. This should bring up the extensions page. (*Alternatively, you could also click on the extensions link from the settings menu.)

Advanced Block
Click on the the Extensions block to open the extensions page. Click on image to enlarge.

There are two methods for finding the gator:microphone extension:

  • Search for the name used on the extension3.
  • Use the link to the GitHub repository for the pxt-package as the search term.

Extensions Page
Use the search bar to find the extension you want to install. Click on image to enlarge.
Note: Unfortunately, it does take time to get an extension approved by the micro:bit Educational Foundation before it can be searchable by name. Part of the requirements for the approval process involves a live product page. Therefore, at the time of the launch of this product, the extension has not been approved yet and the only method of adding the extension is to use the link to the GitHub repository of the pxt-package. We will update this tutorial as soon as the extension has been approved.

Search for the PXT-Package

Search for the gator:microphone extension using the GitHub repository link to the pxt-package:

https://github.com/sparkfun/pxt-gator-microphone

Search for Extension
Search for Extension. Then, click on the box to add it to the block library. Click on image to enlarge.

Then, click on the box for the extension to add it to the block library. The gator:microphone extension should now appear in the block library.

Extension in Block Library
Extension in the block library; click on the block to open menu options. Click on image to enlarge.

To verify that you have added the extension, click on the gator:microphone block to make sure that your drop down menu options match the image below.

Menu Options
Available blocks for the gator:microphone extension. Click on image to enlarge.

MakeCode Examples

Now that you have added the gator:microphone extension to the Editor, lets start with some example code. Plug the micro:bit into your computer using an USB micro-B cable after you have assembled your hardware with the instructions from the previous section. The micro:bit should appear on your computer as a removable storage device.

USB Drive
The micro:bit showing up as a USB drive on a Windows computer. Click to enlarge.

To upload new code, this is where you will be copying the downloaded .hex file to later.

Block Functions

Check for sound block
This is a logic block as indicated by the block's shape. The output is either a 1 or 0 to indicate if the gate threshold has been exceeded.

  • 0- Indicates the threshold has yet to be exceeded.
  • 1- Indicates the threshold has been exceeded.

Get sound intensity
This is a value block as indicated by the block's shape. The output of the block is the envelope of the audio signal.

  • 0 to 2047- An 11-bit value for the envelope of the audio signal from the ADS1015 ADC.

change gain to _____
This is the gain on adc

  • two thirds
  • one
  • two
  • four
  • eight
  • sixteen

Basic Read

Below, is a simple example of how to take simple measurements from the sensor. To use this example, there are multiple options for accessing the .hex file:

  • Replicate the block functions from the display below to copy the example project. Then download the .hex file.
  • Expand the display widow to pull up the example project. Then download the .hex file.
  • Use this link to pull up the example project. Then download the .hex file.
  • Download the .hex file from the button below or the link on the bottom of the display.

The output is redirected over the serial port to avoid conflicts on pins P0 and P1, which are also used for serial communication. To read the sensor values, pull up your favorite serial terminal emulator. Then, connect to the serial port that the micro:bit is on; the default baud rate is 115200 bps. Below, is an example of the sensor output for the example code.

Sample Readings
Example of readings from the sensor.

Plotting Envelope

Below, is an example of how the envelope can be used to spot looped tracks in music. Just as in the previous example, there are multiple ways to access the .hex file.

Again, the output is redirected over the serial port on start up. However, this time, we will be using the the Serial Plotter from the Arduino IDE. Additionally, you also use the log function of TeraTerm to capture data and then use a spreadsheet application to plot the results. Below are a few samples of songs with looped tracks, see if you can spot the repeated patterns in the envelope.

Click to enlarge the images:

Track 1 Part A
Track 1- Part A.

Track 2
Track 2.
Track 1 Part B
Track 1- Part B.

Track 3
Track 3.

Troubleshooting Tips

Here are a few tips for troubleshooting this device.

Noise from Power Supply

If you are experiencing relatively erratic measurements from the gator:microphone, it could be due to noise from your power supply. Double check that the power supply is clean, preferably with an oscilloscope; irregularities on the supply can be passed on to the outputs.

  • Switch-mode power supplies often introduce oscillations in the power rails.

If you still have questions or issues with this product, please create a post on our forum under the Gator Products topic.

Additionally, if you are an educator and you have class or application based questions, please create a post on our forum under the Educational Products topic.

Resources and Going Further

For more product information, check out the resources below:

Interested in the micro:bit? Check out some of these other micro:bit products:

SparkFun Inventor's Kit for micro:bit Lab Pack

SparkFun Inventor's Kit for micro:bit Lab Pack

LAB-15229
$450.00
SparkFun gator:bit v2.0 - micro:bit Carrier Board

SparkFun gator:bit v2.0 - micro:bit Carrier Board

DEV-15162
$19.95
SparkFun Inventor's Kit for micro:bit

SparkFun Inventor's Kit for micro:bit

KIT-15228
$49.95
micro:bit Educator Lab Pack

micro:bit Educator Lab Pack

LAB-15230
$299.95

Need some inspiration for your next project? Check out some of these other micro:bit product tutorials:

micro:bit Educator Lab Pack Experiment Guide

A quickstart guide for the micro:bit educator lab pack.

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.

Wireless Remote Control with micro:bit

In this tutorial, we will utilize the MakeCode radio blocks to have the one micro:bit transmit a signal to a receiving micro:bit on the same channel. Eventually, we will control a micro:bot wirelessly using parts from the arcade:kit!
New!

SparkFun gator:environment Hookup Guide

The gator:environment combines two I2C sensors for temperature, humidity, pressure, eCO2, and eTVOC values. This tutorial will get you started using the gator:environment with the micro:bit platform.

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

Designing with the SparkFun Artemis

$
0
0

Designing with the SparkFun Artemis a learn.sparkfun.com tutorial

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

Introduction

The Artemis module is the world's first open source hardware RF module enabling both voice recognition and BLE. A surprising amount of power can be packed into 10x15mm! This tutorial will walk you through the available features of the SparkFun Artemis module as well as the basics of incorporating the Artemis into your own project!

SparkFun Artemis Module - Engineering Version

SparkFun Artemis Module - Engineering Version

WRL-15376
$8.95

Suggested Reading

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

PCB Basics

What exactly IS a PCB?

Using EAGLE: Board Layout

Part 2 of the Using Eagle tutorials, this one covers how to lay out a board after designing a schematic.

Bluetooth Basics

An overview of the Bluetooth wireless technology.
New!

ARM Programming

How to program SAMD21 or SAMD51 boards (or other ARM processors).

Hardware Overview

This section covers the technical details of the Artemis including the footprint and electrical characteristics. If you’ve already got a dev board with the Artemis module mounted, you can skip this section and head to Unique Features. That said, when was the last time you got to actually see inside one of these modules?

RF shield removed showing the internals of the Artemis module

RF shield removed showing the internals of the Artemis module

Apollo3

The core of the Artemis module is the Apollo3 by Ambiq. This is an ARM Cortex-M4F (F indicates hardware floating point operations) with 1M of flash and 384k of RAM. The datasheet is available here.

Artemis module with Apollo3 highlighted

BLE Antenna

The Apollo3 has a built-in Bluetooth 5.0 radio and the module has a built in 2.4GHz antenna with 2dBi of gain.

2dBi antenna highlighted

Onboard DC Buck

The Apollo3 can operate from 3.6 to 1.8V. To allow for such a large window the Apollo3 has two built in DC buck circuits that regulate the input VCC down to the core voltage with >80% efficiency. The Artemis module includes two inductors to allow for minimum power consumption.

Inductors on the module

Dimensions

The module measures 15.5 x 10.5 x 2.3mm and weighs 0.6 grams.

Artemis on a quarter

Recommended Footprint

The recommended PCB layout for the module is shown here:

Artemis recommended PCB footprint

Recommended SMD footprint for Artemis module. Top view.

Be sure to checkout the Artemis Integration Guide for specific dimensions and considerations. If you design with EAGLE PCB simply clone one of our open source hardware designs that utilize the Artemis (BlackBoard, BlackBoard Nano, and BlackBoard Mega) and begin laying out your board!

Bottom side of SparkFun Artemis module

Rear view of the Artemis module

The Apollo3 is a powerful IC but its 0.5mm BGA package requires a 4 layer PCB with buried and epoxy-filled vias. This makes the PCBs expensive and difficult to produce. We designed Artemis to rid you of these concerns.

Example routing of Artemis

Laying out a PCB with Artemis can be done on a 2-layer PCB with 8mil trace/space. Routing under the module is allowed. Keep all ground pours away from the antenna area. If mechanical exposure allows for it the antenna can be extended over the edge of the PCB for increased reception.

Unique Features

There are a wonderful number of features packed into the Artemis. We’ll give an overview here but be sure to checkout the examples included in the Arduino core as well as the Ambiq SDK to learn more about them.

Pin Flexibility

Gone are the days when pin 12 was for SPI and pin 2 was for interrupts. The Artemis has 48 GPIO which can all be configured in a variety of ways. Up to 6 I2C ports, 6 SPI ports, 2 serial ports, 10 analog pins, numerous PWM pins are all available to you. We’ve setup the Arduino core so that it’s as simple as saying Wire.begin(5, 6) and SPI(13, 15, 21);. Now we can finally stop trying to use software serial and start using dedicated ports.

And that’s far from all. PDM, SSC, and DMA are also available using the HAL. Checkout the pin function map, the Apollo3 datasheet, and the Ambiq SDK/HAL for more information. But don't get overwhelmed, we've got lots of examples showing how to use all the various ports and pins.

Cortex-M4F

The Artemis uses the Apollo3 from Ambiq as its core IC. This IC in turn uses the ARM Cortex-M4F running at 48MHz and an optional 96MHz burst mode. The powerful core can be programmed with GCC as well as Keil, IAR, and debugged with a variety of modern JTAG tools.

BLE

The Artemis has a built-in Bluetooth 5.0 radio capable of transmitting up to 4dBm which should get you about 70m transmission distance. We’ve seen successful RSSI checks at over 200ft.

PWM

With 31 pins out of 48 that are PWM enabled, you should be covered! Be sure to check the graphical datasheet and the pin map to see which pins have PWM capabilities.

Interrupts

Every pin can be configured as an interrupt and wake the processor from deep sleep. Additionally, all pins (except 20) have an internal pull-up that is software enabled.

14-bit ADC

Whereas the original Uno had a 10-bit converter, the Artemis has a 14-bit ADC - meaning the precision of readings goes from 0 to 1023 up to 0 to 16,383. This will enable more precise readings of sensors like analog flex, light, and sound. Note, however, that the ADC is 0V to 2V. So if you have sensor that outputs from 0 to 3.3V, it is safe, but will saturate the ADC over 2V. Use the .setResolution function to change the resolution of readings from the default of 10 to 14 or anywhere in between. Additionally, the ADC is much faster (up to 1.2 MS/s) allowing more data to be aggregated.

Low Power

Ambiq, the manufacturer of the Apollo3, has done years of research into something they call Sub-threshold Power Optimized Technology (SPOT™). This is a fancy description of a power saving technique that works by lowering the logic level voltages necessary to indicate a 1 or a 0. By doing so at the silicon level, Ambiq has managed to eke out a 48MHz processor running at less than half a milliamp. "Always on" monitoring of voice commands, without the need for BLE or a connection to the internet, takes approximately 6μA/MHz.

Burst mode

Sometimes 48MHz is not enough. The processor has the ability to enter a 96MHz burst mode where internal calculations and monitoring can be accomplished in half the time.

JTAG

Modern power calls for modern debugging tools. The Artemis is based on a Cortex-M4F which has a JTAG port dedicated to debugging. With a JTAG debugger you can set break points, inspect registers and see what assembly and C instructions are being executed. It’s a tool that you’ll not often need, but when you need it, it’s a life saver.

PDM

One of the shining uses of the Artemis is for 'always on' voice recognition. Digital MEMS microphones are more sensitive and easier to use than their analog parents. The Artemis has a built-in PDM port allowing for up to 2 MEMS microphones to be used as either dual channel or in beam-forming applications.

Internal Pull Ups

Every pin has an internal weak pull-up that is software enabled. Additionally, the pins configured as I2C ports have software selectable pull-ups (1.5k, 6k, 12k, 24kΩ) eliminating the need for external SDA and SCL pull-ups.

Pin Drive Strength

One of the more unique features of the Artemis is its ability to have selectable drive strength on all GPIO. 2, 4, 8, or 12mA can be selected as the max current on a given pin. Additionally pads 3 and 36 have selectable high side power switch transistors to provide ~1 Ω switches to VDDH. Pads 37 and 41 have a selectable low side power switch transistors to provide ~1Ω switches to VSS.

Security

The Cortex-M4F inside Artemis contains multiple layers of security including Secure Boot, OTA, Keystorage, as well as inline encryption/decryption of external flash (like an SD card).

Programming

Serial port and JTAG port on BlackBoard Artemis

Artemis can be programmed using the standard JTAG interface or with a serial bootloader. You'll find a USB connector for serial bootloading or a JTAG footprint for more advanced programming and debugging, on a variety of dev boards from SparkFun. For more information on ARM programming, including JTAG interfaces, check out our ARM Programming Tutorial.

SparkFun Bootloader

We've designed a baud rate flexible bootloader that is run at each power on reset. What does baud rate flexible mean exactly? The computer and bootloader initiate communication at 9600bps, then agree to go to a faster baud rate to transfer the bulk of the binary data. This enables upload speeds up to 921600bps; significantly reducing upload times. A flexible rate allows computer systems that may have problems at higher rates to select the rate that works best. This bootloader is the preferred method for uploading sketches and user code that needs quick and reliable means of getting new code onto the Artemis.

Just like the classic Arduino Uno, Arduino Mega, etc, the bootloader is activated by resetting the board. A single 0.1uF capacitor between DTR and reset is all that is needed to cause the Artemis to reset and enter bootload mode. If no new firmware is detected within a short amount of time (50ms), user code is run.

If you're into niche electrical engineering discussions on things like bootloaders, you can read more about the Artemis bootloader here.

Factory Bootloader

In addition to the SparkFun Artemis bootloader, we program every Artemis with the Ambiq factory Secure Bootloader (SBL). This bootloader is best used for low-level updates of devices that need to have a secure provenance. The bootloader is activated at reset if pin 47 is high and communicates at 115200. The bootloader will then wait indefinitely for new binary data. We provide a python tool as well as an executable to communicate with this bootloader.

Recommended bootloading circuit for Artemis

This style of bootloading is slightly different from bootloaders that you may be accustomed to. The STK500 bootloader that runs on most ATmega328 based Arduinos is run automatically at reset, then times out and the user’s code is run. The Artemis bootloader is similar but requires an extra pin (the Bootload pin) to be held high. To make using Artemis as cheap and easy as possible we’ve designed a simple RC circuit that can be implemented on your design using USB-to-serial ICs with the bare minimum control pins (the CH340E has only RTS) and still allow for factory bootloader activation. If you suspect you will need to modify the SparkFun Artemis Bootloader (described above) or if you need to use the secure bootload toolchain, the circuit above can be used to bootload using a single pin (DTR or RTS is supported). This single-pin reset and bootload solution is ideal for any USB to serial implementation that has control pins exposed (CH340, CP210x, FT232, etc).

How the Single Pin RC Circuit Works

By pulling DTR (or RTS) low, the module is reset. After 10ms, DTR is pushed high in software. This causes the bootload pin to be high for 100ms allowing the bootloader to run. Opening of a serial port causes DTR to go low causing the module to reset, but because DTR stays low during normal serial operations the module does not enter the SBL and instead proceeds to run the SparkFun Artemis Bootloader.

We have modified the Ambiq python bootload tool so that both DTR and RTS are driven at the same time, and in the same way, so you can use either RTS or DTR to bootload the Artemis. Our Ambiq SBL tools then drive DTR/RTS high to enter the the factory bootloader.

If you prefer, the bootload pin can be broken out to a button. When the user holds the button and resets the board the Artemis will enter bootload mode and stay there until a bootload cycle completes or a reset occurs. This method works well but requires the user’s interaction every time new code needs to be loaded.

Troubleshooting

Resources and Going Further

Here's a list of quick links to the resources provided in this tutorial:

Ready to use Artemis inside Arduino? Checkout the Artemis Development with Arduino tutorial.

Are you more comfortable with a make file and an IDE? Checkout the tutorial on how to setup the Ambiq Apollo3 SDK.

And lastly, Artemis has been designed and proven to work with our entire range of 50+ Qwiic boards. Be sure to check out and get inspired by what's possible by just plugging in the sensors and outputs you need to build something amazing!

Qwiic JST Connector - SMD 4-pin

Qwiic JST Connector - SMD 4-pin

PRT-14417
$0.50
SparkFun RedBoard Edge

SparkFun RedBoard Edge

DEV-14525
$21.95
3
SparkFun GPS-RTK2 Board - ZED-F9P (Qwiic)

SparkFun GPS-RTK2 Board - ZED-F9P (Qwiic)

GPS-15136
$219.95
8
SparkFun Qwiic Scale - NAU7802

SparkFun Qwiic Scale - NAU7802

SEN-15242
$14.95

Check out some of these Artemis/Apollo3 related boards and tutorials:

New!

Artemis Development with Arduino

Get our powerful Artemis based boards (Artemis Nano, BlackBoard Artemis, and BlackBoard Artemis ATP) blinking in less than 5 minutes using the SparkFun Artemis Arduino Core!

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

Artemis Development with Arduino

$
0
0

Artemis Development with Arduino a learn.sparkfun.com tutorial

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

Introduction

The SparkFun Artemis is an amazing module. So much functionality packed into a tiny 10x15mm footprint! But what really makes it powerful is the ability to quickly write sketches and build projects using only Arduino code. Whether you are using one of our boards that has the Artemis module pre-integrated or have your own, this tutorial will show you how to install SparkFun's Apollo3 Arduino core and get you up and blinking in less than 5 minutes!

SparkFun Artemis Module - Engineering Version

SparkFun Artemis Module - Engineering Version

WRL-15376
$8.95

Required Materials

To follow along with this tutorial, you'll need one of the following Artemis carrier boards such as the BlackBoard, BlackBoard Nano, or BlackBoard ATP and a USB C cable.

USB 2.0 Cable A to C - 3 Foot

USB 2.0 Cable A to C - 3 Foot

CAB-15092
$3.95
BlackBoard Artemis

BlackBoard Artemis

SPX-15332
$19.95
BlackBoard Artemis Nano

BlackBoard Artemis Nano

SPX-15411
$14.95
BlackBoard Artemis ATP

BlackBoard Artemis ATP

SPX-15412
$24.95

Suggested Reading

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

Installing an Arduino Library

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

Installing Arduino IDE

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

Designing with the SparkFun Artemis

Let's chat about layout and design considerations when using the Artemis module.

Arduino Installation

With the Arduino Board Manager, installing new board support within your Arduino IDE is a breeze!

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.

Installing the Arduino Core for Apollo3

We've built the Arduino core for Apollo3 from scratch, making it as lightweight and easy to use as possible.

To install the SparkFun Apollo3 Arduino Core:

  • Open the Arduino IDE (must be v1.6.12 or later)
  • Navigate to Preferences
    Arduino Preferences, under File

Having a hard time seeing? Click the image for a closer look.
  • In the "Additional Board Manager URL" box, add

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

Additional Boards Manager URL location in the Preferences Dialog

Having a hard time seeing? Click the image for a closer look.
  • Go to Tools>Board and select the Boards Manager

Arduino Boards Manager Dialog, under Tools

Having a hard time seeing? Click the image for a closer look.
  • Search for "Apollo", and you should find the SparkFun Apollo3 board package.
  • Make sure the latest version is selected and click Install

Board manager showing SparkFun Apollo3 Artemis install

Having a hard time seeing? Click the image for a closer look.

Installation may take a few minutes -- included in the install are all necessary source files for the Arduino core and Apollo3 libraries, plus all of the compiler and software-upload tools you'll need to use the Artemis with Arduino.

Once the board definitions have been installed, you should see a new set of Artemis boards under your Tools > Board menu.

List of Artemis boards

Ahh, the most basic of examples - Blink. Now that you've got your board definitions installed, select your board from the Board Managers pulldown and choose the correct USB port. You can load the blink example by clicking on File->Examples->01.Basics->Blink.

The Blink Sketch is under file->examples->01.Basics->Blink

Hit the upload button and enjoy the blinky goodness!

Beyond Arduino

The SparkFun Apollo3 core supports all the standard Arduino functions. This means you can program digitalWrite I/O, analogRead ADC pins, Serial print to the Serial monitor, interact with hardware serial using Serial1, and even perform more complex I2C or SPI writes with the Wire and SPI libraries. The basics are there, so let's dive in to some more advanced capabilities of the Artemis!

Ambiq has created a software development kit to fully flex the Apollo3. The Ambiq SDK contains a large number of examples and demonstrates all sorts of incredible aspects of the Apollo3. Each example uses various functions that look like this:

Various HAL functions

These long-named-functions are part of what's called a HAL or hardware abstraction layer. We aren't going to go into the specifics of setting up or using the SDK right now, but just know that the the SparkFun Arduino Apollo3 core is built upon this HAL which means you can call HAL functions directly inside the Arduino environment.

language:c
// Clear the RTC alarm interrupt.
am_hal_rtc_int_clear(AM_HAL_RTC_INT_ALM);

Ambiq HAL inside the Arduino IDE

This is a powerful tool for advanced users; you can use the built in Arduino functions such as Serial.begin(9600) and delay(100) while integrating more advanced HAL functions for controlling things like interrupts.

If you do decide to dig into the SDK, head on over to our Using SparkFun Edge Board with Ambiq Apollo3 SDK tutorial for more information!

Using SparkFun Edge Board with Ambiq Apollo3 SDK

March 28, 2019

We will demonstrate how to get started with your SparkFun Edge Board by setting up the toolchain on your computer, examining an example program, and using the serial uploader tool to flash the chip.

Troubleshooting

Resources and Going Further

And lastly, Artemis has been designed and proven to work with our entire range of 50+ Qwiic boards. Be sure to checkout and get inspired by what's possible by just plugging in the sensors and outputs you need to build something amazing!

SparkFun Transparent OLED HUD Breakout (Qwiic)

SparkFun Transparent OLED HUD Breakout (Qwiic)

LCD-15079
$99.95
SparkFun GPS-RTK2 Board - ZED-F9P (Qwiic)

SparkFun GPS-RTK2 Board - ZED-F9P (Qwiic)

GPS-15136
$219.95
8
SparkFun Qwiic OpenLog

SparkFun Qwiic OpenLog

DEV-15164
$16.95
SparkFun Capacitive Touch Slider - CAP1203 (Qwiic)

SparkFun Capacitive Touch Slider - CAP1203 (Qwiic)

SEN-15344
$5.95

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

Hookup Guide for the BlackBoard Artemis

$
0
0

Hookup Guide for the BlackBoard Artemis a learn.sparkfun.com tutorial

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

Introduction

The BlackBoard Artemis encapsulates all the lessons we've learned through the years of improving on the original Arduino Uno while adding in the powerful Artemis module so that you can easily use the Cortex-M4F. Let's dive in!

BlackBoard Artemis

BlackBoard Artemis

SPX-15332
$19.95

Required Materials

You'll need the BlackBoard Artemis and a USB C cable. Any USB C cable should work, including the one that probably came with your phone charger.

BlackBoard Artemis

BlackBoard Artemis

SPX-15332
$19.95
USB 2.0 Cable A to C - 3 Foot

USB 2.0 Cable A to C - 3 Foot

CAB-15092
$3.95

Suggested Reading

If you aren't familiar with the Qwiic system, we recommend reading here for an overview.

Qwiic Connect System
Qwiic Connect System

We also recommend checking out these tutorials before continuing:

I2C

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

RedBoard Qwiic Hookup Guide

This tutorial covers the basic functionality of the RedBoard Qwiic. This tutorial also covers how to get started blinking an LED and using the Qwiic system.

Using SparkFun Edge Board with Ambiq Apollo3 SDK

We will demonstrate how to get started with your SparkFun Edge Board by setting up the toolchain on your computer, examining an example program, and using the serial uploader tool to flash the chip.
New!

Designing with the SparkFun Artemis

Let's chat about layout and design considerations when using the Artemis module.
New!

Artemis Development with Arduino

Get our powerful Artemis based boards (Artemis Nano, BlackBoard Artemis, and BlackBoard Artemis ATP) blinking in less than 5 minutes using the SparkFun Artemis Arduino Core!

Hardware Overview

If you've ever used an Arduino Uno before you should be pretty familiar with the various female headers and the barrel jack power. If you're new to Arduino boards, check out the SparkFun RedBoard Qwiic tutorial for more information on many of the basic board functions you'll see on the Artemis BlackBoard. In this tutorial we'll be covering the unique aspects of the BlackBoard Artemis.

SparkFun BlackBoard Artemis

Serial and JTAG Programming

The BlackBoard Artemis has two methods for programming. The most common is the USB C connector that operates as a USB to serial bridge. By simply pressing 'Upload' in the Arduino IDE or 'make bootload' from the SDK the firmware on Artemis is updated.

We use the CH340C on the BlackBoard Artemis. You shouldn't need to install drivers but if you run into problems head on over to our CH340 hookup guide.

The second method is JTAG programming. An unpopulated JTAG footprint is available for more advanced users who need breakpoint level debugging. We recommend checking out our JTAG section for the compatible male header and a compatible JTAG programmer and debugger.

BlackBoard Artemis USB C and JTAG ports

USB-C and JTAG footprints

Mic and RTC

The Artemis exceeds at low power voice recognition. To enable this we've included a PDM MEMS microphone on the board. Additionally, the Artemis module can operate an RTC given an external 32kHz crystal so we've included that was well.

PDM Microphone and RTC on BlackBoard Artemis

Qwiic and I2C

The I2C pins on the Artemis are labeled SDA and SCL. They are controlled in the Arduino IDE using Wire.begin(), Wire.read(), etc. The same SDA/SCL pins are connected to the Qwiic connector so you can use SparkFun's Qwiic ecosystem (there's over 50 boards and more every week!).

Qwiic connector on BlackBoard Artemis

Serial0, AREF, and USB Pads

On the rear of the BlackBoard are some advanced features. Normally, an AREF pin is located between to the SDA and GND pins. The Artemis module has no equivalent pin so we've converted that pin to GND. If you have a shield that utilizes the AREF pin or just want to free it, you can cut the AREF jumper and the labeled 'GND' located between SDA and GND will be left disconnected.

On Artemis, TX0/RX0 are used for bootloading new code and Serial.println() statements to the computer's terminal window. The CH340C takes care of the serial to USB conversion. However, if you need access to these pins this pins are made available. TX0/RX0 can be used as GPIO as well as special functions, but for most applications these pins are left as Serial for bootloading.

For users who are embedding the BlackBoard Artemis into an enclosure the USB pads are exposed so that an external USB connector can be located at the edge of the enclosure and wired back to the USB pads.

Read of BlackBoard Artemis showing various SMD pads and jumpers

Busmaster Pads

One amazing aspect of the Artemis is the large number of SPI and I2C buses available. We at SparkFun decided that it would be better to have more PWM and ADC pins routed to the female headers on the front of the board, rather than extra I2C and SPI pins. But we just couldn't resist! We've made Wire1/SPI1 and Wire3/SPI3 available to users through the SMD pads on the bottom of the board. These pins can be used as GPIO if needed and pins 28/29 are PWM enabled as well.

Bus master pads on rear of BlackBoard Artemis

Current Measurement Jumper

The Artemis can run as low as 6μA/MHz meaning the module can run at 48MHz at less than half a milliamp. To enable measurements and to isolate the power hungry devices (such as the LM317 voltage regulator) we've added a NC (normally closed) jumper. By cutting the jumper the VDD trace to the module is interrupted. Soldering in a male jumper or wires into the accompanying holes will give you the ability to insert a current meter and precisely monitor how much current your application is consuming.

For the vast majority of projects a wall adapter or USB power can be used. But when properly isolated the Artemis can run on a coincell battery for weeks! So we've designed in a 20mm SMD coin cell footprint so that users can experiment with powering the Artemis from a standard CR2032. You can pickup the compatible coincell holder here.

Current Measurement Jumper

Bypass Jumper

USB C is wonderful. It's reversible and can source up to 2 amps at 5 volts without any power delivery (PD) negotiation. We've included a 2A resettable fuse (often called a PTC) on the Artemis as a safety feature in case your project decides to consume inordinate amounts of power (And possibly begins to spark and set fire. That was fun wasn't it? Get it? SparkFun?). In the event the BlackBoard begins to pull more than 2 amps from the USB source, the resettable fuse will automatically trigger and disconnect the board from the computer or power supply. This should protect your power source and the traces on your BlackBoard.

However, there are plenty of legitimate projects that need more than 2A. We've designed the power traces to withstand up to 2A with a 10C rise in temperature. If your power supply can provide adequate power, and you know what you are doing, you can close the BYP jumper circumventing the resettable fuse.

The bypass jumper on BlackBoard Artemis

Software Setup

The BlackBoard Artemis runs both Arduino and the more advanced Ambiq HAL/SDK. Checkout these tutorials to get you up and blinking in 5 minutes!

New!

Artemis Development with Arduino

June 20, 2019

Get our powerful Artemis based boards (Artemis Nano, BlackBoard Artemis, and BlackBoard Artemis ATP) blinking in less than 5 minutes using the SparkFun Artemis Arduino Core!

Using SparkFun Edge Board with Ambiq Apollo3 SDK

March 28, 2019

We will demonstrate how to get started with your SparkFun Edge Board by setting up the toolchain on your computer, examining an example program, and using the serial uploader tool to flash the chip.

Troubleshooting

Resources and Going Further

Did you know you can use the BlackBoard Artemis as the starting point of your very own Artemis product? Get the design files from our repo here and edit them using Eagle PCB!

For more information on the BlackBoard Artemis and the Artemis module itself, check out the links below:

You've now explored the board, let's get blinking with Arduino! Or perhaps you want to learn a little more about the Artemis module itself. Checkout these tutorials!

New!

Designing with the SparkFun Artemis

Let's chat about layout and design considerations when using the Artemis module.
New!

Artemis Development with Arduino

Get our powerful Artemis based boards (Artemis Nano, BlackBoard Artemis, and BlackBoard Artemis ATP) blinking in less than 5 minutes using the SparkFun Artemis Arduino Core!
New!

Hookup Guide for the BlackBoard Artemis Nano

Get started with the powerful BlackBoard Artemis Nano

Did you know the Artemis is compatible with our Qwiic line? Checkout these products that simply plug in and work!

SparkFun Environmental Combo Breakout - CCS811/BME280 (Qwiic)

SparkFun Environmental Combo Breakout - CCS811/BME280 (Qwiic)

SEN-14348
$35.95
12
SparkFun RedBoard Turbo - SAMD21 Development Board

SparkFun RedBoard Turbo - SAMD21 Development Board

DEV-14812
$24.95
2
SparkFun Qwiic MP3 Trigger

SparkFun Qwiic MP3 Trigger

DEV-15165
$19.95
2
SparkFun Proximity Sensor Breakout - 20cm, VCNL4040 (Qwiic)

SparkFun Proximity Sensor Breakout - 20cm, VCNL4040 (Qwiic)

SEN-15177
$6.95

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

Hookup Guide for the BlackBoard Artemis Nano

$
0
0

Hookup Guide for the BlackBoard Artemis Nano a learn.sparkfun.com tutorial

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

Introduction

We like to joke that the BlackBoard Artemis Nano is a party on the front and all business on the rear! A light weight, 0.8mm thick PCB, with on board lipo-battery charging and a Qwiic connector, this board is easy to implement into very small projects. A dual row of ground connections make it easy to add lots of buttons, LEDs, and anything that requires its own GND connection. At the same time, the board is breadboard compatible if you solder the inner rows of pins. Add into that all the bells and whistles of the Artemis module and you've got one heck of a party going on. Let's check it out!

BlackBoard Artemis Nano

BlackBoard Artemis Nano

SPX-15411
$14.95

Required Materials

You'll need a USB C cable for programming. Any USB C cable should work including the one that probably came with your phone charger. If you don't already have a USB C cable you can pick one up here.

USB 2.0 Cable A to C - 3 Foot

USB 2.0 Cable A to C - 3 Foot

CAB-15092
$3.95
BlackBoard Artemis Nano

BlackBoard Artemis Nano

SPX-15411
$14.95

Suggested Reading

Qwiic Connect System
Qwiic Connect System

We also recommend checking out these tutorials before continuing:

I2C

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

Using SparkFun Edge Board with Ambiq Apollo3 SDK

We will demonstrate how to get started with your SparkFun Edge Board by setting up the toolchain on your computer, examining an example program, and using the serial uploader tool to flash the chip.
New!

Designing with the SparkFun Artemis

Let's chat about layout and design considerations when using the Artemis module.
New!

Artemis Development with Arduino

Get our powerful Artemis based boards (Artemis Nano, BlackBoard Artemis, and BlackBoard Artemis ATP) blinking in less than 5 minutes using the SparkFun Artemis Arduino Core!

Hardware Overview

Power, GPIOs and GND Connections

The Nano breaks out 17 GPIO to PTH holes. Each GPIO is paired with a ground connection. We found the extra grounds immeasurably useful when wiring up projects; you'll often need a separate ground for each LED, button, or sensor. The Nano makes it that much easier to prototype an idea.

Pin Rails on the front and back of the Artemis Nano

Power is automatically selected between USB, LiPo, and Vin (Vin takes precedence). The VIN pin can handle up to 6V and will be regulated down to 3.3V using the AP2112 voltage regulator (600mA max output). The 3.3V pin can be used to power various 3.3V devices up to 600mA.

USB C and Serial Bootloading

We've designed the Nano with a reversible USB C connector and the CH340E USB to serial IC. This is an amazing IC that is small enough to fit under the USB C connector. You should not need drivers but if you do you can get them here. Also be sure to checkout our CH340 hookup guide.

SparkFun Artemis Nano with USB highlighted

The current USB C configuration is with two 5.1k Ohm resistors. This will allow up to 2 amps at 5 volts from your USB source. Nearly all modern computers and battery packs have short circuit protection but just be aware that the Nano does not have any short circuit protection.

Reset and Power Control

The Nano is a great device to embed in a project. But if it's embedded, it is often impossible to access the reset and power switches on a board. We've exposed the reset pin and an I/O pin. This is a perfect place to solder a big external power switch. The I/O pin controls the enable line on the 3.3V regulator. Pull this line low and the board will turn off. Release the I/O line and the board will run normally. The enable line is pulled high with a resistor so if you don't hookup anything the board will operate normally.

SparkFun Artemis reset and power switch

RTC and PDM Microphone

The Artemis has built in RTC capabilities if it is given a 32kHz source so we've added a 32kHz crystal to the Nano. Additionally, one of the main applications of the Artemis is voice recognition so we've added a MEMS digital PDM microphone to the board so that you can capture and analyze audio.

SparkFun Artemis Nano mic and RTC

LiPo Battery and Charging

The Nano has integrated LiPo power and charging. Any one of our LiPo batteries with work great with the Nano. The CHG LED will illuminate while the battery is charging via USB and will turn off when the battery is at peak voltage. Charge rate is set to 500mA. The general rule of thumb is charge no faster than 1C so the minimum recommended battery size is a 500mAh battery, but any of the larger batteries will work just fine.

LiPo Battery and Charging highlighted

Software Setup

The BlackBoard Artemis runs both Arduino and the more advanced Ambiq HAL/SDK. Checkout these tutorials to get you up and blinking in 5 minutes!

New!

Artemis Development with Arduino

June 20, 2019

Get our powerful Artemis based boards (Artemis Nano, BlackBoard Artemis, and BlackBoard Artemis ATP) blinking in less than 5 minutes using the SparkFun Artemis Arduino Core!

Using SparkFun Edge Board with Ambiq Apollo3 SDK

March 28, 2019

We will demonstrate how to get started with your SparkFun Edge Board by setting up the toolchain on your computer, examining an example program, and using the serial uploader tool to flash the chip.

Troubleshooting

My Nano is not showing up as a COM port?!

Most Artemis carrier boards use the CH340C IC which is not affected by this issue. This issue is only for the Nano that uses the much smaller CH340E.

CH340E showing up as weird USB serial device

We've had some issues with the CH340E having an incorrect Vendor ID. If your PC is showing the above as an unknown USB2.0-Serial device you may have this issue.

CH340E showing VID of 0x9986

Device showing Vendor ID of 0x9986 when it should be 0x1A86

For the Nano we needed to use the much smaller CH340E that has only RTS. The CH340E and RTS work fine to reset the Artemis module and activate the SparkFun variable bootloader with one exception: according to the company when the RTS pin has too much load resistance the IC will enumerate incorrectly with VID 0x9986 (correct VID is 0x1A86). It's a very weird failure mode that is not documented. We'll be working closely with the CH340 manufacturer WCH to get this resolved on future Nano boards.

There are two solutions if you experience this:

Option 1: Unplugging and re-plugging USB will cause the IC to properly enumerate under the correct VID/PID and the drivers will work as expected. This works well if you remember to do it but if you're like me, I'll forget two weeks from now and wonder why the COM port isn't coming up.

Option 2: Force Windows to use the correct drivers. WCH (the company behind the CH340) has good drivers but the INF for Windows is expecting the PID of 0x1A86. Here are the steps to make the drivers work even with a VID of 0x9986:

Unknown serial device in windows manager

Step 1: Step 5: Be sure to download and install the Windows driver from the WCH website.

Step 2: Open device manager and locate the problem serial device.

Update CH340 device driver

Step 3: Right click on the device and update driver

Select from available list of drivers

Step 4: Select the driver from the available list of drivers

Select ports

Step 5: Navigate to the Ports.

Select wch.cn from the mfg list

Step 6: Scroll to the bottom of the manufacturer's list and select wch.cn. Select CH340 in the right hand window. If you do not see wch.cn on the list then download and install the Windows driver from the WCH website and repeat the above steps.

Tell windows you are sure

Step 7: Tell Windows you are sure.

COM port is correctly listed

Step 8: Verify the COM port is appearing correctly.

Once you have the driver installed for both VIDs you computer will correctly enumerate a COM port regardless of how cranky the CH340E is feeling that day.

As mentioned above, we'll get this sorted out with WCH soon.

Need more help?

Resources and Going Further

Did you know you can use the BlackBoard Artemis Nano as the starting point of your very own Artemis product? Get the design files from our repo here and edit them using Eagle PCB!

You've now explored the board, let's get blinking with Arduino! Or perhaps you want to learn a little more about the Artemis module itself. Checkout these tutorials!

New!

Designing with the SparkFun Artemis

Let's chat about layout and design considerations when using the Artemis module.
New!

Artemis Development with Arduino

Get our powerful Artemis based boards (Artemis Nano, BlackBoard Artemis, and BlackBoard Artemis ATP) blinking in less than 5 minutes using the SparkFun Artemis Arduino Core!

Did you know the Artemis is compatible with our Qwiic line? Checkout these products that simply plug in and work!

SparkFun Triple Axis Accelerometer Breakout - MMA8452Q (Qwiic)

SparkFun Triple Axis Accelerometer Breakout - MMA8452Q (Qwiic)

SEN-14587
$11.95
1
SparkFun IR Array Breakout - 110 Degree FOV, MLX90640 (Qwiic)

SparkFun IR Array Breakout - 110 Degree FOV, MLX90640 (Qwiic)

SEN-14843
$69.95
SparkFun Pro nRF52840 Mini - Bluetooth Development Board

SparkFun Pro nRF52840 Mini - Bluetooth Development Board

DEV-15025
$29.95
SparkFun RFID Qwiic Kit

SparkFun RFID Qwiic Kit

KIT-15209
$44.95

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

SparkFun 9DoF IMU Breakout Hookup Guide

$
0
0

SparkFun 9DoF IMU Breakout Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The SparkFun 9DoF IMU Breakout incorporates all the amazing features of Invensense's ICM-20948 into a Qwiic-enabled breakout board replete with logic shifting and broken out GPIO pins for all your motion sensing needs. The ICM-20948 itself is an extremely low powered, I2C and SPI enabled 9-axis motion tracking device that is ideally suited for smartphones, tablets, wearable sensors, and IoT applications. Featuring a 3-Axis Gyroscope with four selectable ranges, a 3-Axis Accelerometer, again with four selectable ranges, a 3-axis compass with a wide range to ±4900 µT, and an on-board Digital Motion Processor, this little breakout can even detect the motion of invisibility cloaks. Not really. Just checking to see if you were still with me. But it is pretty amazing. Check it out:

SparkFun 9DoF IMU Breakout - ICM-20948 (Qwiic)

SparkFun 9DoF IMU Breakout - ICM-20948 (Qwiic)

SEN-15335
$16.95

In this hookup guide, we'll connect our sensor up to our Esp32 Thing Plus microcontroller and run a of quick (Qwiic) example to get you up and running with this fantastic board!

Required Materials

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

Tools

If you choose to utilize the broken out GPIO, you will need a soldering iron, solder, and general soldering accessories.

Soldering Iron - 60W (Adjustable Temperature)

Soldering Iron - 60W (Adjustable Temperature)

TOL-14456
$14.95
7
Solder Lead Free - 15-gram Tube

Solder Lead Free - 15-gram Tube

TOL-09163
$3.50
2

Suggested Reading

If you aren't familiar with the Qwiic system, we recommend reading here for an overview.

Qwiic Connect System
Qwiic Connect System

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.

Accelerometer Basics

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

I2C

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

Serial Terminal Basics

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

Hardware Overview

We've put a lot of effort into making this the most useful and versatile breakout for the ICM 20948. Let's take a closer look at all the special parts.

Sensor

At the heart of the board (metaphorically and geometrically) is the ICM 20948 from Invensense. This puppy packs the ability to measure up to 10 unique values (3 axes of acceleration, rotational rate, and magnetic strength data as well as an on-board temperature sensor). The sensor is placed dead-center between the four 4-40 stand-off mounting holes to drastically simplify computation in dynamics.

ICM 20948 Sensor

ICM 20948 Sensor

Level Shifters

The ICM is a fickle fellow - optionally allowing a 3.3V supply voltage but requiring I/O to work at 1.8V. This is just the price we pay for amazing technolojay (hey that rhymes). Since there aren't many popular development boards that run at the voltage of the future we've added high speed level shifting to each and every IO pin. These cool MOSFETS allow for bi-directional voltage translation up to the maximum SPI speed of the ICM - 7MHz - which will allow you to make inertial measurements with fantastic temporal resolution. Feel free to use the ICM IO anywhere from 1.8V to 5.5V!

Mosfets

TXS0108 Modules

Power

Input power on this board should be between 1.8-5.5V. The ICM is riding the wave of 1.8V level devices so we've included a built-in regulator to make it easy to interface with 3.3V or 5V microcontrollers. There is an LED on the front of the board that will light up when the board is powered correctly. You can disable the LED functionality by cutting the LED jumper on the back of the board. This is described in the Jumpers section below.

power LED on the front of the board

Power LED

Qwiic Connectors

There are two Qwiic connectors on the board such that you can daisy-chain the boards should you choose to do so. If you're unfamiliar with our Qwiic system, head on over to our Qwiic page to see the advantages! Of course, if you don't want to use Qwiic we've still broken out every pin on 0.1" spaced plated through-hole headers. You can find more information about these connections in the Headers section.

Qwiic Connectors

Qwiic Connectors

GPIO

For flexibility, we've broken out functional pins for both I2C and SPI. There are no modifications required to switch between I2C mode and SPI out of the box, but if the 'ADR' jumper on the back is closed SPI will be unavailable.

I2C Pin LabelsSPI Pin Labels

Jumpers

Look at all those jumpers on the back of the board! Here's what they do:

Pullup Jumpers

  • I2C Pullup - Does nothing, the pullups are not populated on the board because the TXS0108 has them built-in
  • Aux Pullup - Cut these jumpers to disconnect the pullup resistors from the auxiliary I2C bus

LED Jumper

  • Cutting this jumper allows you to disable the LED functionality on the front of the board.

Address Jumper

  • When open (default) the address of the ICM is 0x69 and it is possible to use SPI communication. When soldered closed the address changes to 0x68. Closing the jumper prevents you from using SPI.
Pullup JumpersLED JumperI2C Address Jumper

Hardware Hookup

One of the many advantages of the Qwiic system is that hooking up your hardware is extremely simple. Simply grab a Qwiic cable and plug your 9DoF in!

Hooking up microcontroller to breakout via qwiic cable

Easy peasy lemon squeezy

If you'd like to use the broken out GPIO pins, things get a bit more complicated. That said, to make life a little easier we've organized them by function, and provided lots of labels. You'll first notice that one side has the text 'I2C' and the other side says 'SPI.' The labels on either side are those that apply to that kind of communication.

I2C Pin LabelsSPI Pin Labels

Next, you'll see that on the left side are the main connections to the host microcontroller. When connecting I2C you'll have a 'No Connect' pin that serves as the chip select when using SPI. As noted before, there are no modifications required to switch between I2C mode and SPI out of the box. However if the 'ADR' jumper is closed SPI will be unavailable.

On the right side are connections to external sensors that can be controlled by the ICM, as well as the 'INT' and 'FSYNC' interrupt pins. The auxiliary I2C bus pins are level shifted to/from the 'VIN' level that you supply.

Breakout Board Pin Functions (SPI)
Breakout Pin Arduino Uno Esp32 Thing Plus Microcontroller Pin Requirements
MOSI1118Data output of chosen SPI port
SCLK135Clock output of chosen SPI port
MISO1219Data input of chosen SPI port
CS22An output pin to select the ICM for SPI
Breakout Board Pin Functions (I2C)
Breakout Pin Arduino Uno Esp32 Thing Plus Microcontroller Pin Requirements
DASDA23Data line of chosen I2C port
CLSCL22Clock line of chosen I2C port
AD0--Optional - use to control I2C address from software
Breakout Board Pin Functions (Auxiliary I2C and Interrupts)
Breakout Pin Arduino Uno Esp32 Thing Plus Microcontroller Pin Requirements
ADA--Data line of auxiliary I2C bus
ACL--Clock line of auxiliary I2C bus
FSYNC--Optional - synchronize measurements with a signal out from the microcontroller
INT--Optional - respond to configurable interrupts in from the ICM

Software Setup and Example Code

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

In this example, we are using the SparkFun Esp32 Thing WROOM Plus. If you have not used this board before, head on over to the ESP32 Thing Plus Hookup Guide for a general overview, as well as information on getting set up with board definitions.

ESP32 Thing Plus Hookup Guide

March 7, 2019

Hookup guide for the ESP32 Thing Plus using the ESP32 WROOM's WiFi/Bluetooth system-on-chip in Arduino.

In order to use the ICM-20948 breakout, you'll need to install the SparkFun ICM-20948 Arduino Library. We recommend you install the library via the Arduino IDE by using the library manager and search for Sparkfun 9DoF IMU Breakout. Or you can download and manually install a zip of the library by clicking on the link below. For those who want to view the code, check out the GitHub repo.

Example 1

In this example, we've hookup up our ICM-20948 to an ESP32 Thing Plus using a short Qwiic cable.

Once you've installed the ICM-20948 library, load the first example sketch from File->Examples->SparkFun 9DoF IMU Breakout - ICM 20948 - Arduino Library->Arduino->Example1_Basics.

Where to find Example 1 in the Arduino IDE

Having a hard time seeing? Click the image for a closer look.

The very first thing you'll see in the code is the #include statement for the library. Alongside that is a convenient link that will help you get the library through the Arduino library manager. Next is a commented out #define statement called 'USE_SPI'. If instead you have chosen to connect your ICM with the SPI pins all you need to do is uncomment that line.

language:c
#include "ICM_20948.h"  // Click here to get the library: http://librarymanager/All#SparkFun_ICM_20948_IMU

//#define USE_SPI       // Uncomment this to use SPI

Up next is a short section where you can configure your particular setup. First of all if you need to change your serial port, e.g. if you're using a SAMD21 board, you can change the 'SERIAL_PORT' define ('SerialUSB' for SAMD21). You can do the same to change your I2C port or SPI port, depending on which you're using. When using I2C you have the ability to change the I2C address of the sensor with the Address 0 bit. By default it is '1' but you could change it to 0 if you've closed the 'ADR' jumper. When using SPI you need to specify a chip select pin - in the example we default to pin 2.

language:c
#define SERIAL_PORT Serial

#define SPI_PORT SPI    // Your desired SPI port.       Used only when "USE_SPI" is defined
#define CS_PIN 2        // Which pin you connect CS to. Used only when "USE_SPI" is defined

#define WIRE_PORT Wire  // Your desired Wire port.      Used when "USE_SPI" is not defined
#define AD0_VAL   1     // The value of the last bit of the I2C address. 
                        // On the SparkFun 9DoF IMU breakout the default is 1, and when 
                        // the ADR jumper is closed the value becomes 0

That's it for stuff you (might) need to do to set up the example! Now we'll just all hop in the bus, take a tour, and I'll point out items on your right and left.

The next little block creates either a ICM_20948_I2C or ICM_20948_SPI object called 'myICM'. Since they have the same name, and they both inherit from the grandaddy ICM_20948 class, we'll be able to use them interchangeably later on in the example.

language:c
#ifdef USE_SPI
  ICM_20948_SPI myICM;  // If using SPI create an ICM_20948_SPI object
#else
  ICM_20948_I2C myICM;  // Otherwise create an ICM_20948_I2C object
#endif

In the setup() function we have your standard Arduino initialization of your serial port, and then we have the last interface-dependent section. There you'll see the 'myICM' object being started up with the appropriate arguments for the chosen interface. This example shows all arguments being explicitly stated, but it is also possible to call the .begin() function with default arguments. The initialization will repeat with a delay until the device is successfully found. If it is not connecting try checking your wiring.

language:c
#ifdef USE_SPI
    SPI_PORT.begin();
    myICM.begin( CS_PIN, SPI_PORT ); 
#else
    WIRE_PORT.begin();
    WIRE_PORT.setClock(400000);
    myICM.begin( WIRE_PORT, AD0_VAL );
#endif

Here's a little trick for debugging the ICM - nearly all operations will update the internal 'myICM.status' value. You can check it directly (0 means all good, anything else is an error) or you can use the statusString() method to get the latest status in human-readable form.

language:c
    SERIAL_PORT.print( F("Initialization of the sensor returned: ") );
    SERIAL_PORT.println( myICM.statusString() );
    if( myICM.status != ICM_20948_Stat_Ok ){
      SERIAL_PORT.println( "Trying again..." );
      delay(500);
    }else{
      initialized = true;
    }

The last part of the sketch is the loop() where the sensor gets polled for new data, and that data gets pushed over the serial port. All the data is contained in the 'AGMT' structure, which stands for Accelerometer, Gyroscope, Magnetometer, and Temperature sensors. For convenience this sketch also includes functions (that are not part of the library) to print the results in a pretty format.

language:c
void loop() {

  if( myICM.dataReady() ){
    myICM.getAGMT();                // The values are only updated when you call 'getAGMT'
//    printRawAGMT( myICM.agmt );     // Uncomment this to see the raw values, taken directly from the agmt structure
    printScaledAGMT( myICM.agmt);   // This function takes into account the sclae settings from when the measurement was made to calculate the values with units
    delay(30);
  }else{
    Serial.println("Waiting for data");
    delay(500);
  }

}

When you open up your Serial Monitor, you should see something like the following:

Serial Output

Having a hard time seeing? Click the image for a closer look.

There ya have it! Now go ahead and hack it up.

Resources and Going Further

For more information on the ICM-20948, check out the links below:

Need more inspiration? Check out these related tutorials!

Experiment Guide for RedBot with Shadow Chassis

This Experiment Guide offers nine experiments to get you started with the SparkFun RedBot. This guide is designed for those who are familiar with our SparkFun Inventor's Kit and want to take their robotics knowledge to the next level.

Electret Mic Breakout Board Hookup Guide

An introduction to working with the Electret Mic Breakout Board.

ADXL345 Hookup Guide

Get started with the ADXL345 Accelerometer.

Qwiic Proximity Sensor (VCNL4040) Hookup Guide

The SparkFun Qwiic Proximity Sensor is a great, qualitative proximity (up to 20 cm) and light sensor. This hookup guide covers a few examples to retrieve basic sensor readings.

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


SparkFun 9DoF IMU (ICM-20948) Breakout Hookup Guide

$
0
0

SparkFun 9DoF IMU (ICM-20948) Breakout Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The SparkFun 9DoF IMU Breakout incorporates all the amazing features of Invensense's ICM-20948 into a Qwiic-enabled breakout board replete with logic shifting and broken out GPIO pins for all your motion sensing needs. The ICM-20948 itself is an extremely low powered, I2C and SPI enabled 9-axis motion tracking device that is ideally suited for smartphones, tablets, wearable sensors, and IoT applications. Featuring a 3-Axis Gyroscope with four selectable ranges, a 3-Axis Accelerometer, again with four selectable ranges, a 3-axis compass with a wide range to ±4900 µT, and an on-board Digital Motion Processor, this little breakout can even detect the motion of invisibility cloaks. Not really. Just checking to see if you were still with me. But it is pretty amazing. Check it out:

SparkFun 9DoF IMU Breakout - ICM-20948 (Qwiic)

SparkFun 9DoF IMU Breakout - ICM-20948 (Qwiic)

SEN-15335
$16.95

In this hookup guide, we'll connect our sensor up to our Esp32 Thing Plus microcontroller and run a of quick (Qwiic) example to get you up and running with this fantastic board!

Required Materials

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

Tools

If you choose to utilize the broken out GPIO, you will need a soldering iron, solder, and general soldering accessories.

Soldering Iron - 60W (Adjustable Temperature)

Soldering Iron - 60W (Adjustable Temperature)

TOL-14456
$14.95
7
Solder Lead Free - 15-gram Tube

Solder Lead Free - 15-gram Tube

TOL-09163
$3.50
2

Suggested Reading

If you aren't familiar with the Qwiic system, we recommend reading here for an overview.

Qwiic Connect System
Qwiic Connect System

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.

Accelerometer Basics

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

I2C

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

Serial Terminal Basics

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

Hardware Overview

We've put a lot of effort into making this the most useful and versatile breakout for the ICM 20948. Let's take a closer look at all the special parts.

Sensor

At the heart of the board (metaphorically and geometrically) is the ICM 20948 from Invensense. This puppy packs the ability to measure up to 10 unique values (3 axes of acceleration, rotational rate, and magnetic strength data as well as an on-board temperature sensor). The sensor is placed dead-center between the four 4-40 stand-off mounting holes to drastically simplify computation in dynamics.

ICM 20948 Sensor

ICM 20948 Sensor

Level Shifters

The ICM is a fickle fellow - optionally allowing a 3.3V supply voltage but requiring I/O to work at 1.8V. This is just the price we pay for amazing technolojay (hey that rhymes). Since there aren't many popular development boards that run at the voltage of the future we've added high speed level shifting to each and every IO pin. These cool MOSFETS allow for bi-directional voltage translation up to the maximum SPI speed of the ICM - 7MHz - which will allow you to make inertial measurements with fantastic temporal resolution. Feel free to use the ICM IO anywhere from 1.8V to 5.5V!

Mosfets

TXS0108 Modules

Power

Input power on this board should be between 1.8-5.5V. The ICM is riding the wave of 1.8V level devices so we've included a built-in regulator to make it easy to interface with 3.3V or 5V microcontrollers. There is an LED on the front of the board that will light up when the board is powered correctly. You can disable the LED functionality by cutting the LED jumper on the back of the board. This is described in the Jumpers section below.

power LED on the front of the board

Power LED

Qwiic Connectors

There are two Qwiic connectors on the board such that you can daisy-chain the boards should you choose to do so. If you're unfamiliar with our Qwiic system, head on over to our Qwiic page to see the advantages! Of course, if you don't want to use Qwiic we've still broken out every pin on 0.1" spaced plated through-hole headers. You can find more information about these connections in the Headers section.

Qwiic Connectors

Qwiic Connectors

GPIO

For flexibility, we've broken out functional pins for both I2C and SPI. There are no modifications required to switch between I2C mode and SPI out of the box, but if the 'ADR' jumper on the back is closed SPI will be unavailable.

I2C Pin LabelsSPI Pin Labels

Jumpers

Look at all those jumpers on the back of the board! Here's what they do:

Pullup Jumpers

  • I2C Pullup - Does nothing, the pullups are not populated on the board because the TXS0108 has them built-in
  • Aux Pullup - Cut these jumpers to disconnect the pullup resistors from the auxiliary I2C bus

LED Jumper

  • Cutting this jumper allows you to disable the LED functionality on the front of the board.

Address Jumper

  • When open (default) the address of the ICM is 0x69 and it is possible to use SPI communication. When soldered closed the address changes to 0x68. Closing the jumper prevents you from using SPI.
Pullup JumpersLED JumperI2C Address Jumper

Hardware Hookup

One of the many advantages of the Qwiic system is that hooking up your hardware is extremely simple. Simply grab a Qwiic cable and plug your 9DoF in!

Hooking up microcontroller to breakout via qwiic cable

Easy peasy lemon squeezy

If you'd like to use the broken out GPIO pins, things get a bit more complicated. That said, to make life a little easier we've organized them by function, and provided lots of labels. You'll first notice that one side has the text 'I2C' and the other side says 'SPI.' The labels on either side are those that apply to that kind of communication.

I2C Pin LabelsSPI Pin Labels

Next, you'll see that on the left side are the main connections to the host microcontroller. When connecting I2C you'll have a 'No Connect' pin that serves as the chip select when using SPI. As noted before, there are no modifications required to switch between I2C mode and SPI out of the box. However if the 'ADR' jumper is closed SPI will be unavailable.

On the right side are connections to external sensors that can be controlled by the ICM, as well as the 'INT' and 'FSYNC' interrupt pins. The auxiliary I2C bus pins are level shifted to/from the 'VIN' level that you supply.

Breakout Board Pin Functions (SPI)
Breakout Pin Arduino Uno Esp32 Thing Plus Microcontroller Pin Requirements
MOSI1118Data output of chosen SPI port
SCLK135Clock output of chosen SPI port
MISO1219Data input of chosen SPI port
CS22An output pin to select the ICM for SPI
Breakout Board Pin Functions (I2C)
Breakout Pin Arduino Uno Esp32 Thing Plus Microcontroller Pin Requirements
DASDA23Data line of chosen I2C port
CLSCL22Clock line of chosen I2C port
AD0--Optional - use to control I2C address from software
Breakout Board Pin Functions (Auxiliary I2C and Interrupts)
Breakout Pin Arduino Uno Esp32 Thing Plus Microcontroller Pin Requirements
ADA--Data line of auxiliary I2C bus
ACL--Clock line of auxiliary I2C bus
FSYNC--Optional - synchronize measurements with a signal out from the microcontroller
INT--Optional - respond to configurable interrupts in from the ICM

Software Setup and Example Code

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

In this example, we are using the SparkFun Esp32 Thing WROOM Plus. If you have not used this board before, head on over to the ESP32 Thing Plus Hookup Guide for a general overview, as well as information on getting set up with board definitions.

ESP32 Thing Plus Hookup Guide

March 7, 2019

Hookup guide for the ESP32 Thing Plus using the ESP32 WROOM's WiFi/Bluetooth system-on-chip in Arduino.

In order to use the ICM-20948 breakout, you'll need to install the SparkFun ICM-20948 Arduino Library. We recommend you install the library via the Arduino IDE by using the library manager and search for Sparkfun 9DoF IMU Breakout. Or you can download and manually install a zip of the library by clicking on the link below. For those who want to view the code, check out the GitHub repo.

Example 1

In this example, we've hookup up our ICM-20948 to an ESP32 Thing Plus using a short Qwiic cable.

Once you've installed the ICM-20948 library, load the first example sketch from File->Examples->SparkFun 9DoF IMU Breakout - ICM 20948 - Arduino Library->Arduino->Example1_Basics.

Where to find Example 1 in the Arduino IDE

Having a hard time seeing? Click the image for a closer look.

The very first thing you'll see in the code is the #include statement for the library. Alongside that is a convenient link that will help you get the library through the Arduino library manager. Next is a commented out #define statement called 'USE_SPI'. If instead you have chosen to connect your ICM with the SPI pins all you need to do is uncomment that line.

language:c
#include "ICM_20948.h"  // Click here to get the library: http://librarymanager/All#SparkFun_ICM_20948_IMU

//#define USE_SPI       // Uncomment this to use SPI

Up next is a short section where you can configure your particular setup. First of all if you need to change your serial port, e.g. if you're using a SAMD21 board, you can change the 'SERIAL_PORT' define ('SerialUSB' for SAMD21). You can do the same to change your I2C port or SPI port, depending on which you're using. When using I2C you have the ability to change the I2C address of the sensor with the Address 0 bit. By default it is '1' but you could change it to 0 if you've closed the 'ADR' jumper. When using SPI you need to specify a chip select pin - in the example we default to pin 2.

language:c
#define SERIAL_PORT Serial

#define SPI_PORT SPI    // Your desired SPI port.       Used only when "USE_SPI" is defined
#define CS_PIN 2        // Which pin you connect CS to. Used only when "USE_SPI" is defined

#define WIRE_PORT Wire  // Your desired Wire port.      Used when "USE_SPI" is not defined
#define AD0_VAL   1     // The value of the last bit of the I2C address. 
                        // On the SparkFun 9DoF IMU breakout the default is 1, and when 
                        // the ADR jumper is closed the value becomes 0

That's it for stuff you (might) need to do to set up the example! Now we'll just all hop in the bus, take a tour, and I'll point out items on your right and left.

The next little block creates either a ICM_20948_I2C or ICM_20948_SPI object called 'myICM'. Since they have the same name, and they both inherit from the grandaddy ICM_20948 class, we'll be able to use them interchangeably later on in the example.

language:c
#ifdef USE_SPI
  ICM_20948_SPI myICM;  // If using SPI create an ICM_20948_SPI object
#else
  ICM_20948_I2C myICM;  // Otherwise create an ICM_20948_I2C object
#endif

In the setup() function we have your standard Arduino initialization of your serial port, and then we have the last interface-dependent section. There you'll see the 'myICM' object being started up with the appropriate arguments for the chosen interface. This example shows all arguments being explicitly stated, but it is also possible to call the .begin() function with default arguments. The initialization will repeat with a delay until the device is successfully found. If it is not connecting try checking your wiring.

language:c
#ifdef USE_SPI
    SPI_PORT.begin();
    myICM.begin( CS_PIN, SPI_PORT ); 
#else
    WIRE_PORT.begin();
    WIRE_PORT.setClock(400000);
    myICM.begin( WIRE_PORT, AD0_VAL );
#endif

Here's a little trick for debugging the ICM - nearly all operations will update the internal 'myICM.status' value. You can check it directly (0 means all good, anything else is an error) or you can use the statusString() method to get the latest status in human-readable form.

language:c
    SERIAL_PORT.print( F("Initialization of the sensor returned: ") );
    SERIAL_PORT.println( myICM.statusString() );
    if( myICM.status != ICM_20948_Stat_Ok ){
      SERIAL_PORT.println( "Trying again..." );
      delay(500);
    }else{
      initialized = true;
    }

The last part of the sketch is the loop() where the sensor gets polled for new data, and that data gets pushed over the serial port. All the data is contained in the 'AGMT' structure, which stands for Accelerometer, Gyroscope, Magnetometer, and Temperature sensors. For convenience this sketch also includes functions (that are not part of the library) to print the results in a pretty format.

language:c
void loop() {

  if( myICM.dataReady() ){
    myICM.getAGMT();                // The values are only updated when you call 'getAGMT'
//    printRawAGMT( myICM.agmt );     // Uncomment this to see the raw values, taken directly from the agmt structure
    printScaledAGMT( myICM.agmt);   // This function takes into account the sclae settings from when the measurement was made to calculate the values with units
    delay(30);
  }else{
    Serial.println("Waiting for data");
    delay(500);
  }

}

When you open up your Serial Monitor, you should see something like the following:

Serial Output

Having a hard time seeing? Click the image for a closer look.

There ya have it! Now go ahead and hack it up.

Resources and Going Further

For more information on the ICM-20948, check out the links below:

Need more inspiration? Check out these related tutorials!

Vernier Photogate

Vernier Photogate Timer -- using the Serial Enabled LCD Kit.

VL6180 Hookup Guide

Get started with your VL6180 based sensor or the VL6180 breakout board.

TB6612FNG Hookup Guide

Basic hookup guide for the TB6612FNG H-bridge motor driver to get your robot to start moving!

Spectacle Inertia Board Hookup Guide

Everything you need to know about using the Spectacle Inertia Board in one place.

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

Qwiic Kit for Raspberry Pi Hookup Guide

$
0
0

Qwiic Kit for Raspberry Pi Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Welcome to the Qwiic Kit for Raspberry Pi hookup guide. Here we are going to get started with some of the basics surrounding I2C and Python on your Raspberry Pi. Don't worry, we've done most of the work with the Python Libraries we've written for the boards in our Qwiic Kit. This kit should help you get started whether you just want to get data and display it on your Pi, display it on our OLED screen, or post it to the Internet.

SparkFun Qwiic Kit for Raspberry Pi

SparkFun Qwiic Kit for Raspberry Pi

KIT-15367
$54.95$46.71

Required Materials

To follow along with this tutorial, you will also need a few pieces of hardware. Single board computers with the Raspberry Pi 40-pin GPIO header will work. We'll be using a Raspberry Pi throughout this tutorial. If you have not worked with a Raspberry Pi, we recommend getting started with the Raspberry Pi starter kit.

Raspberry Pi 3 B+ Starter Kit

Raspberry Pi 3 B+ Starter Kit

KIT-14644
$91.95
6

Optional Materials

You have several options when it comes to working with the Raspberry Pi. Most commonly, the Pi is used as a standalone computer, which requires a monitor, keyboard, and mouse (listed below). To save on costs, the Pi can also be used as a headless computer (without a monitor, keyboard, and mouse). This setup has a slightly more difficult learning curve, as you will need to use the command-line interface (CLI) from another computer.

Raspberry Pi LCD - 7" Touchscreen

Raspberry Pi LCD - 7" Touchscreen

LCD-13733
$64.95
39
SmartiPi Touch

SmartiPi Touch

PRT-14059
$24.95
8
Multimedia Wireless Keyboard

Multimedia Wireless Keyboard

WIG-14271
$29.95
3

Suggested Reading

Before you get started, I recommend taking a look at some of our other tutorials and familiarizing yourself with some of these topics. We will end up working with the Raspberry Pi, Python programming language, and MQTT protocol to send data over the Internet.

SD Cards and Writing Images

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

Python Programming Tutorial: Getting Started with the Raspberry Pi

This guide will show you how to write programs on your Raspberry Pi using Python to control hardware.

Introduction to MQTT

An introduction to MQTT, one of the main communication protocols used with the Internet of Things (IoT).

Qwiic pHAT for Raspberry Pi Hookup Guide

Get started interfacing your Qwiic enabled boards with your Raspberry Pi. This Qwiic connects the I2C bus (GND, 3.3V, SDA, and SCL) on your Raspberry Pi to an array of Qwiic connectors.
Python Logo

Qwiic

SparkFun's Qwiic System is a quick and easy way to connect I2C devices to your microcontroller. Because our Qwiic boards use a 4-pin JSH-SH connector, you don't need to solder. You just need a cable to connect your modules. The connector is polarized meaning you can't plug it in wrong. Additionally, you can daisy chain all your boards together.

Qwiic Connect System
Qwiic Connect System

I2C is a protocol that has been around for a while, it has a few advantages such as each device being on the same bus but each having a unique address. Messages are sent back and forth with an address and only the device with the correct address listens to the message. This is why we are able to daisy chain our sensors. Currently, a large number of sensors we find communicate over I2C, but what about the ones that don't? Well, some of our Qwiic board use other types of sensors and have a small microcontroller that reads the data and then outputs via I2C, so in other words you can make anything you want to be I2C. One thing to note is that each item on the bus must have its own address. Some sensors will have jumper pads that let you change the address (you usually have 2 or 4 options if this is the case), but not all do. This might make it difficult to have a lot of one sensor in a chain unless you have a dedicated I2C mux.

no soldering

no soldering

Qwiic cables (4-pin JST) plug easily from development boards to sensors, shields, accessory boards and more, making easy work of setting up a new prototype.

polarized connector

There's no need to worry about accidentally swapping the SDA and SCL wires on your breadboard. The Qwiic connector is polarized so you know you’ll have it wired correctly every time, right from the start.

daisy chain-able

It’s time to leverage the power of the I2C bus! Most Qwiic boards will have two or more connectors on them, allowing multiple devices to be connected.

The Qwiic Connect System is designed to keep your projects moving. If you have I2C sensors that don't have a Qwiic connector on them, check out our Qwiic adapter. You might have to write your own Python library, but at least we've made the connection easier for you.

Hardware

The hardware we are using for this kit (other than the Pi) is the Qwiic pHAT which provides a Qwiic connector to your Raspberry Pi, VCNL4040 Proximity sensor, Environmental combo board (which has the BME280 and CCS811), and Qwiic micro OLED screen.

Let's start with connecting the pHAT. The pHAT should fit on the Raspberry Pi like most Pi HATs, but it should also fit on compatible boards such as the Nvidia Jetson Nano, the Google Coral board, and others that use the standard 2x20 GPIO header. It will even work on the Raspberry Pi Zero W. Just line up the headers and connect the pHAT to your Raspberry Pi. If you have more questions on the pHAT check out the hookup guide for more information.

I2C Sensor connected to a Raspberry Pi via Qwiic pHAT

Next, we are going to connect our boards. We've given you a selection of different cable lengths to let you configure your boards however you like. So go ahead and daisy chain all your boards together (while you only need 1 Qwiic connector on the pHAT, you can use as many as you'd like). It doesn't matter which order you connect them in (or which of the connectors on the board you use), as long as they all have a path to the Pi. Keep in mind that these cables are polarized and should only go in one direction (don't force it to go in the wrong direction).

Configure Your Pi

We are going to assume you already have a Raspberry Pi up and running with Raspbian. We'll also assume that it is connected to the Internet. If not, check out our starter kits and tutorials on setting up a Raspberry Pi.

Raspberry Pi 3 Starter Kit Hookup Guide

April 11, 2016

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

Make sure to update the image so that we have the latest distribution. Enter the following commands in the command line individually to update your image.

language:bash
sudo apt-get update
sudo apt-get dist-upgrade
Note: sudo stands for "Super User Do", it is a way to give you superuser powers from the command line. Be careful whenever using sudo.

User Configuration Settings

Once you are set up, I highly recommend changing your password. At this point, we are going be dealing with the Internet of things and don't want unsavory characters sneaking into your system using the default login: (username: pi, password: raspberry).

The raspi-config tool is a quick way to change your password as well as setup the network, language, keyboard, etc. Type the following command using the command line and then go through the menus to update your information.

language:bash
sudo raspi-config

You'll want to enable the I2C pins using the tool to read the sensors on the I2C bus.

Enabling I2C on a Pi

Raspi-config for I2C

I2C Clock Stretching

The CCS811 sensor requires something known as I2C clock stretching to work, so let's get this setup as well. Open up the file /boot/config.txt in your favorite editor. We'll use the following command to edit the file through the command line.

language:bash
sudo nano /boot/config.txt

After typing the command, hit ENTER on your keyboard.

Adjusting I2C Settings in config.txt

Scroll down until you find the block of code that contains the following lines. It will look similar to the following lines.

language:bash
dtparam=i2c_arm=on
dtparam=i2s=on
dtparam=spi=on

Add the following line(s) to enable the clock stretching.

language:bash
# Enable I2C clock stretching
dtparam=i2c_arm_baudrate=10000

When you are finished, you should see something similar to the image below.

I2C Clock Stretching

Then save your file and exit out. We'll use the following commands CTRL+ O and then Enter to save. Then CTRL + X to exit.

Save Changes

You will need to restart your Pi before the settings can take effect after every change to the config.txt. After all that hard work, let's reboot your Pi with the following command.

language:bash
sudo reboot

After typing the command, hit the ENTER key.

Reboot Pi

Python

Notice: This tutorial was written with Raspbian version "June 2019", Python version 3.7.3, and pip 19.1.1 for Python v3.7. Other versions may affect how some of the steps in this guide are performed.

Python is a great language, we actually have a great tutorial on getting started with Python programming on a Raspberry Pi that covers everything from picking an editor and getting the code to run, to syntax and error messages. I highly recommend reading it if you plan on writing your own code. If you just plan on running the example code and maybe making a few changes, we'll go through a few basic things here.

Python Programming Tutorial: Getting Started with the Raspberry Pi

June 27, 2018

This guide will show you how to write programs on your Raspberry Pi using Python to control hardware.

Indentation

In many programming languages, we indent things to make things easier to read. In Python, those indents are part of the code. Instead of putting brackets around your loop or if() statements, you just indent that entire chunk with a leading whitespace. In other words, you have to make sure your indents are correct. I also recommend not using your keyboard's TAB button to indent as various programs will read it differently (and usually incorrectly).

Commenting

Another thing to keep in mind is comments. In Python, the symbol "#" is used to denote that the line is a comment. Unlike many other languages there is no official multi-line comment available. So you'll just have to get use to typing # for each line when writing large comments.

Python Versions and Installing PIP

There are also 2 commonly used Python versions. Even after Python 3 came out many people continued to use 2.7 for many years. Part of the reason is that Python 3 improved on some things and in the process made it not backwards compatible. For our example we will be using Python 3.7 (and the code will not run on 2.7). To see what version of Python your Pi is using, open a command line and type each of the following commands individually to check.

language:bash
python --version
pip --version

If you are not using Python 3, then we'll need to open the *.bashrc file and add an alias.

First, you will need to update the python installation package by running the following command to install pip for Python 3. Execute the following commands.

language:bash
sudo apt-get install python3-pip

Type the following command to open the file.

language:bash
nano ~/.bashrc

Then add the following lines at the end. That should tell the computer whenever you want to run python to look for the file located at /usr/bin/python3.

language:bash
alias python='/usr/bin/python3'
alias pip=pip3

Alias Python 3 and pip3

To exit nano type CTRL + X and then hit Y when it asks you if you want to save and then ENTER. You can now either reboot or type the following to force the Pi to run the *.bashrc file again.

language:bash
source ~/.bashrc

Once adjusted, type the following command to ensure that pip is up to date.

language:bash
python -m pip install --upgrade pip

Python Library

We will also need to install the Qwiic Python libraries. This will automatically download a folder containing all the Qwiic_Py files and dependencies to your Raspberry Pi. Run the following command to automatically install the modules for the Qwiic sensors and micro OLED.

language:bash
pip install sparkfun_qwiic

Setting Up MQTT and Cayenne

MQTT is a messaging protocol that works great for IoT devices. Devices can post to a topic, and/or subscribe to a topic to receive information. Alex wrote a tutorial all about MQTT, which is a great read if you are unfamiliar with MQTT. Amongst other things, our setup is going to act as an MQTT client and publish information to an online service called Cayenne.

Introduction to MQTT

November 7, 2018

An introduction to MQTT, one of the main communication protocols used with the Internet of Things (IoT).

Cayenne

Cayenne is a product from myDevices that allows you to not only display data but also set up triggers, monitor devices, control devices, etc. You can view your home's temperature remotely from their site (or app), but you can also tell it to text you when the temperature goes below 40 so you can figure out why your furnace isn't working. But don't worry, none of the exercises in this tutorial require you to give myDevices any money (or even a credit card).

If you have not already, the first thing to do is make an account. Head over to Cayenne to sign up by clicking on the link below using one of the Raspberry Pi's Internet browsers. If you have an account, just make sure to login in.

Once you have an account we're going to start by setting up the Raspberry Pi. This is a good introduction that provides you with some information on your Pi (RAM usage, temperature, network speed). It also allows you to remotely reset or shutdown you Pi, toggle I/O pins and even give you the IP address of your Pi. That is one of the nice things about Cayenne, it doesn't define devices based on IP address or network. You provide a small script and your Pi basically tells Cayenne where it is. This is helpful if you loose power, reset your device etc., and need to know the IP address to log back in remotely.

Adding a Device in Cayenne

You'll be greeted with a few devices. Select the Raspberry Pi.

Set Up Pi Cayenne

You'll be prompted with an image of the Raspberry Pi before continuing on. Hit on the next button.

Set Up Pi

You'll be provided with a few options. We'll be following option 2. Follow the instructions provided (Cayenne has very good instructions in when setting up your Raspberry Pi).

Set Up via option 2 serial terminal

At this point you should have a working Cayenne account. Type (or copy and paste using your mouse's right click) the first command and hit the ENTER button. The command will begin executing. When it is done, type (or copy and paste) the second command and hit the ENTER button. The process may take a few minutes. When the the command is finished executing, your Raspberry Pi will automatically restart.

After the reboot, open the browser back up and head back to Cayenne. Next, go back to adding a new device or widget. This time you are going to select the blue "Bring Your Own Thing" button.

Cayenne Device

This will provide you with your MQTT username, password, and client ID, as well as the server information for our project. We'll use this information later. You might want to do this on your Pi which will make it easier to copy and paste these values into your code.

Example Code

We've written some example code to read the sensor data and display a few sensor values to the micro OLED. In your terminal window, type the following to download the demo code from the GitHub repository.

language:bash
git clone https://github.com/sparkfun/Qwiic-Kit-for-Pi.git

Then navigate to folder by typing the following command in the command line.

language:bash
cd Qwiic-Kit-for-Pi

Open example via Command Line

You can also navigate to the folder /home/pi/Qwiic-Kit-for-Pi to open the example in your favorite Python editor. In this case, we use opened the code in the Thonny editor.

Run Example via Python Editor

We recommend opening the example code in a Python editor to follow along before running the demo.

Reading the Data

Now that we have everything physically hooked up and ready to go, we can set up our sensors and start reading data. First, the code will need to run through the condition statement to give the sensor values some time to take samples from the environment. At the top of the code, we set up a flag (i.e. initialize) and counter (i.e. n) to keep track of whether or not we have just started the Python script. Further down in the main code under the for loop, we'll take a few readings over a certain period of time. Once we have taken a few values, we'll update the flag so that we can take the reading once through the for loop.

language:python
#These values are used to give BME280 and CCS811 some time to take samples
initialize=True
n=2
.
.
.

        if initialize==True:
            print ("Initializing: BME280 and CCS811 are taking samples before printing and publishing data!")
            print ("")
        else:
            #print ("Finished initializing")
            n=1 #set n back to 1 to read sensor data once in loop
        for n in range (0,n):
            #print ("n = ", n) #used for debugging for loop
            .
            .
            .

            #Give some time for the BME280 and CCS811 to initialize when starting up
            if initialize==True:
                time.sleep(10)
                initialize=False

Reading the Sensors Values

Python does not require you to initialize and type your variables, we just get to go ahead and use them. We've highlighted most of the user functions in the main code under the for loop below as well as a few of the configuration functions. You'll also notice that the CCS811 has a few extra functions that read and calculate the necessary values before we actually grab them.

language:python
            #Proximity Sensor variables - these are the available read functions
            proximity = prox.getProximity()
            ambient = prox.getAmbient()
            white = prox.getWhite()
            close = prox.isClose()
            .
            .
            .

            #BME280 sensor variables
            pressure = bme.readFloatPressure() #in Pa
            altitudef = bme.readFloatAltitudeFeet()
            humidity = bme.readFloatHumidity()
            tempf = bme.readTempF()
            .
            .
            .


            #CCS811 sensor variables
            ccs.readAlgorithmResults() #updates the TVOC and CO2 values
            ccs.readNTC() #updates temp/humidity values
            tvoc = ccs.getTVOC()
            co2 = ccs.getCO2()
            ccstemp = ccs.getTemperature()
            .
            .
            .

Now that we've read all our data, let's figure out what we want to do with it all. Our different outputs will each display a different set of variables based on the application. Feel free to comment out any variables you are not using in your code using a "#" or choose to display different variables. The actual code has a lot more variables and functions listed that you probably won't need.

Display Data to Your Pi

Once we've read the data from the 3 sensors it is time to display that information on the Pi's console, the OLED screen, and send the information to be displayed by Cayenne. Let's dig into the code a bit deeper.

Comments and Libraries

Starting at the very first line you'll see a line of code that looks like a comment (comments start with #). This line actually tells us that we will by using Python 3 which is what is used for the Qwiic Pi libraries. After the header comment is a line to import a few libraries to help us keep things clean between Python 2 and Python 3. Next, we are going to add in a few libraries including an mqtt client, our Qwiic library, the time library, and the system library.

Definitions

If you scroll down a bit you'll, see our Qwiic board definitions. As we add more libraries you'll want to periodically download those updates, each sensor has its own *.py file or module. Inside that file you should find the class definition as well as all the functions. We can then setup that device in our code (the example code has already done this, but if you want to add new sensors from new libraries you'll need to do this yourself). Don't forget the begin() call to get your sensor up and running.

Then we get to the main part of our code, which is in a while() loop. This will loop forever (unless we exit out). Here is where we define and read the variables from the sensors as we talked about earlier. We do this every time through the loop so we always have new data. Next, we'll get into printing the data to the screen. We've selected some of the variables to print out as well as the time. When you run this code, this information will all display on the console.

language:python
#printing time and some variables to the screen
#https://docs.python.org/3/library/time.html
#print (time.strftime("%a %b %d %Y %H:%M:%S", time.localtime())) #24-hour time 
print (time.strftime("%a %b %d %Y %I:%M:%S%p", time.localtime())) #12-hour time

print ("BME Temperature %.1f F" %tempf)
print ("Humidity %.1f" %humidity)

print ("Pressure %.2f Pa" %pressure)
print ("Altitude %.2f ft" %altitudef)

print ("CCS Temperature %.1f F" %ccstemp)
print ("Distance %.2f " %proximity)
print ("Ambient Light %.2f" %ambient)

print ("TVOC %.2f" %tvoc)
print ("CO2 %.2f" %co2)

print ("") #blank line for easier readability

Displaying Data to Your OLED

Next, we are going to look at the Qwiic micro OLED screen. The OLED module should have the same functions as our OLED Arduino library, but they might look a bit different. Let's start with a few basic commands...

Initializing the Micro OLED

We start by defining our OLED screen like we did with our sensors at the top of the code as well as run the initilization.

language:python
oled = qwiic.QwiicMicroOLED()
oled.begin()

Clearing the Screen

Next, we are going to clear the screen. This actually will clear the entire buffer.

language:python
oled.clear(oled.ALL)

Then we can display the cleared screen. This will display what is in the buffer which at this point is nothing.

language:python
oled.display()

Font Size

Next, we can set the font type. The module comes with 4 different fonts. Unless you just need to display 2-3 digits, I recommend sticking with font 0 or font 1 as they will give you enough room to display a few lines of information. This is the end of the commands we'll use to setup the screen at the beginning of the code

language:python
oled.setFontType(1)

Setting Cursor Position

When we are ready to actually print to the screen we'll set the cursor to the top left.

language:python
oled.setCursor(0,0)

Printing

Then we can print some text. When we print the temperature, we don't want to print all the decimal places, partly because the limit of the screen size. The "int" command takes the tempf variable and gives us an integer and then we can print that.

language:python
oled.print("Tmp:")
oled.print(int(tempf))

If we want, we can move the cursor to a different line, print more data, etc.

Displaying

Finally, we will want to display all of this to the screen.

language:python
oled.display()

Also, keep in mind you might want to add delays when using an OLED screen so that the information isn't flickering too fast. In this case, we already have a 1 second delay each time through the loop so we should be fine.

Because we already have the variables setup, we just need to pick a few we think would be useful and print them to our OLED display. We can get about 3 lines of code here comfortably, but you might want to change the font type and just display temperature so that you can view it from more than 12 inches away.

More with Cayenne

Now let's look at the Cayenne part of our code. Let's start with the the definitions. Remember the username, password, and client ID we got earlier? We are going to copy and paste these into the code for the respective username, password, and clientid. Now our code knows not only to post to Cayenne, but who's account and what project this is for.

language:python
username = "______ENTER_MQTT_USERNAME____"
password = "______ENTER_MQTT_PASSWORD____"
clientid = "___ENTER_CAYENNE_CLIENTE_ID___"
mqttc=mqtt.Client(client_id = clientid)
mqttc.username_pw_set(username, password = password)
mqttc.connect("mqtt.mydevices.com", port=1883, keepalive=60)
mqttc.loop_start()

Topics

Next, we are going to setup our topics. Topics are how MQTT keeps track of what is what. Each topic gets a different channel which is the number at the end of the line. Otherwise, the code is exactly the same for each topic name. We just need to figure out once at the beginning what pieces of data we want to send.

language:python
#set MQTT topics (we are not setting topics for everything)
topic_bme_temp = "v1/" + username + "/things/" + clientid + "/data/1"
topic_bme_hum = "v1/" + username + "/things/" + clientid + "/data/2"
topic_bme_pressure = "v1/" + username + "/things/" + clientid + "/data/3"
topic_bme_altitude = "v1/" + username + "/things/" + clientid + "/data/4"

topic_prox_proximity = "v1/" + username + "/things/" + clientid + "/data/5"
topic_prox_ambient = "v1/" + username + "/things/" + clientid + "/data/6"

topic_ccs_temp = "v1/" + username + "/things/" + clientid + "/data/7"
topic_ccs_tvoc = "v1/" + username + "/things/" + clientid + "/data/8"
topic_ccs_co2 = "v1/" + username + "/things/" + clientid + "/data/9"

Publishing Sensor Data to the Cloud

Once in the main part of the code, we are going to publish data to each of those topics so Cayenne will see this. You'll notice we are using the topics we set up earlier, as well as setting the payload to the variable we want to send with it.

language:python
#publishing data to Cayenne (we are not publishing everything)
mqttc.publish (topic_bme_temp, payload = tempf, retain = True)
mqttc.publish (topic_bme_hum, payload = humidity, retain = True)
mqttc.publish (topic_bme_pressure, payload = pressure, retain = True)
mqttc.publish (topic_bme_altitude, payload = altitudef, retain = True)

mqttc.publish (topic_prox_proximity, payload = proximity, retain = True)
mqttc.publish (topic_prox_ambient, payload = ambient, retain = True)

#mqttc.publish (topic_ccs_temp, payload = ccstemp, retain = True)
mqttc.publish (topic_ccs_tvoc, payload = tvoc, retain = True)
mqttc.publish (topic_ccs_co2, payload = co2, retain = True)

Let's Run the Code Already!

OK, now that we've updated our code to submit data to our Cayenne account and figured out which variables we want to send where we can run the code. Make sure you save your code (with your Cayenne account information and any other changes you wanted to make). Then open a terminal window and navigate to the folder where your code is if you have not already. Type the following command and ENTER to run the script. Our code actually runs a loop until we decide to cancel the program CTRL + C.

language:bash
python qwiic_kit_for_pi_demo.py

Run Demo via Command Line

Or hit the Run button in your Python editor to start executing the script. To stop, simply click on the Stop button with your mouse.

Run Demo via Python Editor

Assuming you don't get any errors you should see some of the BME280 sensor data displayed on your screen and data on the OLED.

Output via Command LineOutput via Python Editor
Running Demo via Command LineRunning Demo via Thonny Editor

Click on images for a closer look!

You will also start seeing the green boxes popping up on Cayenne as well so you can add them to your dashboard and move them around.

Sensor Data on Cayenne

Congratulations, you now know how to read Qwiic sensors on a Pi, display data to your Pi, display data on the Qwiic micro OLED screen, and get that information to display on the web. Try adjusting the code to send data to the web at a slower rate or calibrate the sensor readings for stable readings. Keep checking the Qwiic_Py repo for more Python libraries for our Qwiic boards or write your own and start experimenting.

Customizing Data on Cayenne's Dashboard

Once Cayenne sees this data, you should get a green box pop up on your Cayenne dashboard. Click the "+" in the upper right hand corner to permanently add it to your dashboard. By default, the values will be displayed with the associated channel. You will need to head into the settings and assign a name to be displayed for each channel in order to easily read the sensor data. You can also assign an icon to the channel, drag and drop widgets, and resize each window if you prefer.

Sensor Output on Cayenne

After customizing according to your personal preference, the channels may look similar to the image below.

Customized Channels on Cayenne

Triggers and Notifications

While we are not going to go into this in this tutorial, Cayenne will also let you setup triggers and other things to text you, email you, or change things on any of your other devices (such as turn on an I/O pin on the Pi). You can start playing with Cayenne and its various features. Just make sure you don't overwhelm your inbox with notifications by sending texts 100 times per second.

Additional Features with Cayenne

Troubleshooting

Below are a few additional troubleshooting tips and tricks when using the Qwiic devices with a single board computer.

The Demo Code is Not Running.

If you are having trouble running the demo code, there are a few reasons why the Python script may not be executing. Below are two common reasons why the demo code may not be running.

Library Not Installed

If the libraries are not installed properly, you may receive an error similar to the output below when trying to execute the Python script:

language:bash
 Traceback (most recent call last):
  File "./qwiic_kit_for_pi_demo.py", line 24, in <module>
    import qwiic 
ImportError: No module named 'qwiic'

The ImportError indicates that the module(s) was not installed properly. Make sure that the Python modules are installed on the Pi in order to run the demo.

I2C Device Not Connected

If you receive an error similar to the one below, it means that the bus is having issues reading the sensor.

language:bash
Traceback (most recent call last):
  File "/home/pi/qwiicpy/qwiic_kit_for_pi_demo.py",     line 117, in <module>
    ccs.readAlgorithmResults() #updates the TVOC and CO2 values
  File "/home/pi/qwiicpy/qwiic/qwiic_ccs811.py", line 159, in readAlgorithmResults
    data = self.readBlock(CSS811_ALG_RESULT_DATA, 4)
  File "/home/pi/qwiicpy/qwiic/qwiicdevice.py", line 119, in readBlock
    return self._i2cDriver.readBlock(self.address, commandCode, nBytes)
  File "/home/pi/qwiicpy/qwiic/qwiic_i2c/linux_i2c.py", line 144, in readBlock
    return self.i2cbus.read_i2c_block_data(address, commandCode, nBytes)
OSError: [Errno 121] Remote I/O error

The OSError: [Errno 121] Remote I/O error indicates that an I2C device is not connected to the bus. Make sure that the sensors and micro OLED are securely connected to the I2C bus. The demo code currently checks to see if the CCS811, BME280, VCNL4040, and micro OLED are connected to the Pi's I2C bus before executing.

Don't forget to setup the clock stretching for the Raspberry Pi, this is required for the CCS811 to work correctly on the bus. If 10000 is still too fast, try using a slower baud rate. Make sure to reboot for the changes to take effect.


If you receive this error, this is because there is no NTC thermistor connected! You will not want to call this function.

language:bash
Traceback (most recent call last):
  File "/home/pi/Qwiic-Kit-for-Pi/qwiic_kit_for_pi_demo.py", line 128, in <module>
    ccs.readNTC() #updates temp value
  File "/home/pi/.local/lib/python3.7/site-packages/qwiic_ccs811.py", line 356, in readNTC
    self.resistance = self.ntcCounts * self.refResistance / float(self.vrefCounts)
ZeroDivisionError: float division by zero

I'm Having Problems Getting the Qwiic_Py Library.

If you are having trouble installing the modules, you may receive this error:

Could not install packages due to an EnvironmentError: 404 Client Error: Not Found for url: https://www.piwheels.org/simple/sparkfun-qwiic/

Make sure that you are connected to the Internet to install the modules. Also, make sure that you are using Python3 and pip3 with the correct alias as stated earlier.

language:bash
python -m pip install --upgrade pip

I Don't Want to Use Cayenne or Another 3rd Party Service.

That's perfectly alright, you can delete or comment out all the relevant commands as that is not will not affect the rest of the code.

I Can't Connect to Cayenne.

Make sure you have copied your username, password, and clientid correctly from Cayenne into the code before executing the Python script.

How do I add _____ Qwiic sensor.

Right now we only have a few Qwiic sensors in the Qwiic Py library, but we are looking to keep adding more. Please periodically check back to see if the sensor you want is available. You can also check the Internet for existing Python code for that sensor or write your own library.

Resources and Going Further

For more information, check out the resources below:


Python Logo

Looking for more inspiration? Check out these other Raspberry Pi projects and Python tutorials.:

Graph Sensor Data with Python and Matplotlib

Use matplotlib to create a real-time plot of temperature data collected from a TMP102 sensor connected to a Raspberry Pi.

Python GUI Guide: Introduction to Tkinter

Tkinter is the standard graphical user interface package that comes with Python. This tutorial will show you how to create basic windowed applications as well as complete full-screen dashboard examples complete with live graph updates from matplotlib.

How to Run a Raspberry Pi Program on Startup

In this tutorial, we look at various methods for running a script or program automatically whenever your Raspberry Pi (or other Linux computer) boots up.

Pi AVR Programmer HAT Hookup Guide

In this tutorial, we will use a Raspberry Pi 3 and the Pi AVR Programmer HAT to program an ATMega328P target. We are going to first program the Arduino bootloader over SPI, and then upload an Arduino sketch over a USB serial COM port.
New!

TPL5110 Nano Power Timer Hookup Guide

The TPL5110 Nano Power Timer is ideal for applications that require low power, and especially those projects that are running off of a LiPo battery. The Nano Power Timer will turn on your project after the set amount of time, continuously.

Or check out some of these blog posts for ideas:


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

Pi Servo pHAT (v2) Hookup Guide

$
0
0

Pi Servo pHAT (v2) Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Note: This product and tutorial haven't been tested with the new Raspberry Pi 4 nor the recent distribution of Debian Buster. At the time of the development of this product, the Raspberry Pi 4 had just been released and Buster wasn't officially released yet.

The SparkFun Pi Servo pHAT provides your Raspberry Pi with 16 PWM channels that can be controlled over I2C. These channels are broken out in a header combination that is perfect for connecting servo motors. Additionally, the PWM channels can control other PWM devices as well.

SparkFun Servo pHAT for Raspberry Pi

SparkFun Servo pHAT for Raspberry Pi

DEV-15316
$10.95

Furthermore, the Pi Servo pHAT can be used for a serial terminal connection to remotely control the Raspberry Pi, without the need for a monitor and keyboard (header used by the Sphero RVR). As an added bonus, we have provided a Qwiic connector for users to easily interface with the I2C bus using the Qwiic system. Who says you can't have it all?

Required Materials

Note: Below are lists of products that you will need for this hookup guide. You may already have some of these products in your cart or at home; please, feel free to modify your cart as necessary.

To get started with the Pi Servo pHAT, you will need a Raspberry Pi board with headers. There are several options that can be found under the Raspberry Pi Board product category. Additionally, we also offer these boards in various kits.

Raspberry Pi 3 B+

Raspberry Pi 3 B+

DEV-14643
$39.95
29
Raspberry Pi 3 A+

Raspberry Pi 3 A+

DEV-15139
$29.95
1
Raspberry Pi 3

Raspberry Pi 3

DEV-13825
92
Raspberry Pi Zero W

Raspberry Pi Zero W

DEV-14277
$10.00
24
Raspberry Pi 3 B+ Starter Kit

Raspberry Pi 3 B+ Starter Kit

KIT-14644
$91.95
6
SparkFun Raspberry Pi Zero W Basic Kit

SparkFun Raspberry Pi Zero W Basic Kit

KIT-14298
$39.95
3
SparkFun Basic Autonomous Kit for Sphero RVR

SparkFun Basic Autonomous Kit for Sphero RVR

KIT-15302
$119.95
SparkFun Advanced Autonomous Kit for Sphero RVR

SparkFun Advanced Autonomous Kit for Sphero RVR

KIT-15303
$164.95

(Some, but not all of our Raspberry Pi kits include a Raspberry Pi. Be sure to double check the Includes tab of the associated product page. Additionally, the Sphero RVR kits will include this Pi Servo pHAT.).


There are a few additionally accessories that you will need to use your Raspberry Pi.

You will need an microSD Card, Power Supply, and USB-C Cable (optional) at minimum to run your Raspberry Pi. There are two options for the microSD card, a NOOBS card that comes pre-flashed with the OS need to run your Raspberry Pi or a blank SD card that can be flashed using the files and instructions from the Raspberry Pi Foundation page.

microSD Card with Adapter - 16GB (Class 10)

microSD Card with Adapter - 16GB (Class 10)

COM-13833
$19.95
5
microSD Card with Adapter - 64GB (Class 10)

microSD Card with Adapter - 64GB (Class 10)

COM-14833
$29.95
microSD Card with Adapter - 32GB (Class 10)

microSD Card with Adapter - 32GB (Class 10)

COM-14832
$24.95
Raspberry Pi™ - 16GB MicroSD NOOBS Card

Raspberry Pi™ - 16GB MicroSD NOOBS Card

COM-13945
3
Wall Adapter Power Supply - 5.1V DC 2.5A (USB Micro-B)

Wall Adapter Power Supply - 5.1V DC 2.5A (USB Micro-B)

TOL-13831
$7.95
16
microSD USB Reader

microSD USB Reader

COM-13004
$4.95
8
USB 3.1 Cable A to C - 3 Foot

USB 3.1 Cable A to C - 3 Foot

CAB-14743
$4.95
2

(To flash your own SD card, you will also want to grab a microSD USB adapter.)


Last of all, to test the functionality of the Pi Servo pHAT you will want a servo motor.

Servo - Generic (Sub-Micro Size)

Servo - Generic (Sub-Micro Size)

ROB-09065
$8.95
11
Servo - Generic High Torque (Standard Size)

Servo - Generic High Torque (Standard Size)

ROB-11965
$12.95
4
Servo - Hitec HS-422 (Standard Size)

Servo - Hitec HS-422 (Standard Size)

ROB-11884
$18.95
1
Servo - Generic High Torque Continuous Rotation (Standard Size)

Servo - Generic High Torque Continuous Rotation (Standard Size)

ROB-09347
$13.95
6

(Any "standard" 5V servo in our catalog should work. Keep in mind when purchasing, the continuous rotation servos behave differently from the normal servos.)


Required Tools

No tools are required to used this product. However, you may need a soldering iron, solder, and/or general soldering accessories to solder modify the jumpers or solder on headers to your Raspberry Pi board (if it didn't come with them).

Break Away Headers - Straight

Break Away Headers - Straight

PRT-00116
$1.50
20
Solder Lead Free - 15-gram Tube

Solder Lead Free - 15-gram Tube

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

Soldering Iron - 30W (US, 110V)

TOL-09507
$9.95
6
Hobby Knife

Hobby Knife

TOL-09200
$2.95
2

Suggested Reading

Below are several tutorials and hookup guides covering various topics that we suggest users get familiar with before beginning this hookup guide. As a supplement, the hookup guides for the previous Pi Servo Hat are listed as well.

Pulse Width Modulation

An introduction to the concept of Pulse Width Modulation.

I2C

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

Raspberry Pi SPI and I2C Tutorial

Learn how to use serial I2C and SPI buses on your Raspberry Pi using the wiringPi I/O library for C/C++ and spidev/smbus for Python.

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.

Setting Up the Pi Zero Wireless Pan-Tilt Camera

This tutorial will show you how to assemble, program, and access the Raspberry Pi Zero as a headless wireless pan-tilt camera.

Pi Servo Hat Hookup Guide

This hookup guide will show you how to connect and use the Pi Servo Hat in a project.

Getting Started with the Raspberry Pi Zero Wireless

Learn how to setup, configure and use the smallest Raspberry Pi yet, the Raspberry Pi Zero - Wireless.

Python Programming Tutorial: Getting Started with the Raspberry Pi

This guide will show you how to write programs on your Raspberry Pi using Python to control hardware.

Qwiic Connect System

The Pi Servo pHAT also provides a Qwiic connector to take advantage of our new Qwiic system. We recommend familiarizing yourself with the Logic Levels and I2C tutorials before using it. Click on the banner above to learn more about our Qwiic products.

Hardware Overview

There are several functional components of the hat, which are designed to be as foolproof as possible. Although we have attempted to take precautions to guard against the most common user errors, users should still be wary. Most users may already be aware of these common pitfalls. However, if you have forgotten or maybe you have never used a Raspberry Pi (or similar single board computer), they are highlighted throughout this section just in case. There is a lot of detailed content in this section; in general, users primarily need to:

  1. Be cautious of any loose connections and avoid shorting or bridging 5V and 3.3V on the Raspberry Pi.
  2. Be aware of any potential current draw limitations.

Power

⚡ Danger: With connections provided to both the 5V and 3.3V pins of the Raspberry Pi, please be cognizant of any loose wires. A short between the 5V and 3.3V lines will permanently put your Raspberry Pi out of commission.

The power circuitry of the Pi Servo pHAT is more complex than most of the boards we produce. This is primarily due to the fact that is has to be able to handle 3 different power supplies (listed below) as well as 2 different voltage levels. The following subsections will cover the intricate details of the power circuitry on the Pi Servo pHAT.

Power Connections
The power connection on the Pi Servo pHAT. (On the 40-pin GPIO header, a connection is provided to both 5V and 3.3V pins.)

3.3V Power

⚡ Danger: As a design requirement for Pi hats, power cannot be applied into the 3.3V pin from the hat.

Although unlikely, users should still double check that no power will be applied into the Qwiic connection since there is no circuit protection on the 3.3V line of the Servo Pi pHAT. Any application of power to the 3.3V pin through the Qwiic connector, the primary access point, from another device will likely damage your Raspberry Pi.

On the Pi Servo pHAT, 3.3V power is drawn from the Raspberry Pi 3.3V pin, on the 40-pin GPIO header, to power your Qwiic devices and for logic level translation. You cannot power the Raspberry Pi through the 3.3V pin; in fact, you should never connect another power source to this pin. It is intended to be used only as a power output for the Qwiic connect system.

40-pin GPIO
The 40-pin GPIO header connection to the Raspberry Pi.

The 3.3V line is primarily used to power any connected Qwiic devices. In general most users will not reach the current limitations of the Raspberry Pi. However, if you intend to sink a bunch of current or have a ton of Qwiic devices, make sure double check your current draw and the limitations of the Raspberry Pi you are using. As an example, the Raspberry Pi Zero W uses a PAM2306 switching 3.3V regulator (found in the schematic for power regulation), which is rated up to a 1A output current.

Is a 1 amp current draw gonna get HOT? Let's see...

  1. Regulating from 5V down to 3.3V is a ΔV of 1.7V.
    5V - 3.3V = 1.7V
  2. At 1A, this is 1.7W.
    1.7V x 1A = 1.7W
  3. With a Thermal Resistance (Junction to Ambient) of 60 °C/Watt, this should cause an increase of 102 °C.
    1.7W x 60 °C/W = 102 °C
  4. Add room temp (27 °C), this takes us up to 129 °C.
    102 °C + 27 °C = 129 °C

This is well below the Maximum Junction Temperature of 150 °C. Should be good to go for 1A!

Logic Level Conversion

The 3.3V pin also provides a reference voltage for the MOSFET logic level converters to the PCA9685 PWM controller. It is all connected to the I2C pullup resistors for the Qwiic connector.

5.0V Power

⚡ Danger: A proper USB port, powered USB hub, or power supply should be used when providing power over through the USB-C connection. A traditional USB port supplies a regulated 5V, but is limited to about 500mA (USB 2.0). Drawing more current than the USB port on your computer can supply (usually a USB 2.0 port), will most likely cause your computer to freak out and throw an error message and/or cause your computer reset. If you are unlucky, it may even damage the power controller on the computer. Always calculate your expected and maximum current draw to prevent issues like this.

The three different power sources to the 5V line of the servo header are: the 5V pin from the 40-pin header of the Raspberry Pi (power supply connected to the Raspberry Pi), the 5V pin from the RVR serial connection header, and the USB-C female connector. The power protection and control circuitry on the Pi Servo pHAT allows these to be used either individually or in tandem combinations.

  • 40-Pin Header: Power to and/or from the Raspberry Pi is accessed through the 40-pin header. The header provides several connections to a Raspberry Pi. For power, the 5V pin and 3.3V pins are used.

    40-pin GPIO
    The 40-pin GPIO header connection to the Raspberry Pi. Click to enlarge.
  • USB-C Connector: This connector can be used to power the servo motors as well as the Raspberry Pi. It can also be used to connect to the Pi via serial port connection (see Serial-UART section below).

    USB Connection
    The USB-C connection to the Pi Servo pHAT. Click to enlarge.
  • RVR Header: This 4-pin header can be used to power the servo motors as well as the Raspberry Pi. It can also be used to connect to the Pi via serial port connection (see Serial-UART section below).

    RVR Header
    The Sphero RVR 4-pin header connection to the Pi Servo pHAT. Click to enlarge.

Power Control & Protection

Although we have attempted to take precautions to guard against reverse current, users should still be wary of what they are doing.

A short between the 5V and 3.3V lines will permanently put your Raspberry Pi out of commission.

Power cannot be applied into the 3.3V pin (or Qwiic Connector) from the Servo Pi pHAT. Any application of power to the 3.3V pin of the Raspberry Pi will likely damage it; there is no circuit protection.

  • Always calculate your expected and maximum current draw to prevent issues.

A proper USB port or power supply should be used when providing power through the USB-C connection. A USB 2.0 port supplies a regulated 5V, but is limited to about 500mA. Drawing more current than the USB port on your computer can supply, will most likely cause your computer to freak out and may even damage the power controller.

🔥 Over drawing current from the 3.3V line may strain the 3.3V regulator. The regulator on a Raspberry Pi Zero W will get pretty toasty at 1A.

The fuse on the USB-C connection is part of the power protection circuitry. Only use use the fuse bypass jumper if you know what you are doing; otherwise, a small mistake could cost you your whole project.

Reverse Current Protection

The Pi Servo pHAT controls 5V power from three different sources, the 5V pin from the 40-pin header of the Raspberry Pi, the 5V pin from the RVR serial connection header, and the USB-C female connector. To provide reverse current protection, the board utilizes circuitry that acts as an ideal diode, a design used on the Raspberry Pi 3 and a requirement for Raspberry Pi hats.

The ideal diode circuit protection prevents back power from the Pi Servo pHAT to either of the USB-C and RVR connections. When using multiple power sources on the Pi Servo pHAT, there is possibility that the power sources will provide conflicting input voltages. If the voltage differential is great enough between the power supplies, a reversal of the flow of power can occur and current pushed back into a power source. This can potentially damage devices, including your computer. For more information, check out the Raspberry Pi Backpowering Guidelines.

Power Protection Block Diagram

A block diagram of the 5V power protection on the Pi Servo pHAT. Click to enlarge.

As shown in the functional block diagram above, the USB-C and RVR inputs are both protected against possible back power from either the Raspberry Pi and/or servo power sources with ideal diodes. However, in order to allow power to pass from the Pi Servo pHAT to the Raspberry Pi for a headless setup, power protection or isolation circuitry was't implemented on the 5V GPIO pin. This means that current can freely flow back into the Raspberry Pi to provide power, but may be a concern for the Raspberry Pi Zero, Zero W, 3B+, and 3A+ models, which don't include reverse current protection for their power supplies.

This would be a concern if the 5V power supply on the Raspberry Pi (micro-B USB connector) was somehow sinking current from external power provided through either the USB-C or RVR connections on the Pi Servo pHAT. However, in reality, there still is a small voltage drop across the ideal diodes, the 5V rail on the Raspberry Pi does have some tolerance, and it is not very likely that the power supply on the Raspberry Pi would be sinking current either. In the off chance that you decide to be a mad scientist and test the limits of the boards, there is a power isolation jumper can be manually cut since there is no circuit protection from the 5V line on the Pi Servo pHAT to the 5V line of the Raspberry Pi.

Power Control

Also shown in the functional block diagram above, is a MOSFET acting as an automated switch to manage possible power from the Raspberry Pi. If either the RVR header or the USB-C connector provide 5V, then the power from Raspberry Pi's GPIO header is disconnected from the servo 5V rail. The table below outlines the possible power source combinations.

Power SourcesDescription
Pi GPIOUSB-CRVR Header
XXO Raspberry Pi powered primarily by own power supply.
Servos pull power from USB-C (MOSFET closed; no power from Pi).
XOX Raspberry Pi powered primarily by own power supply.
Servos pull power from RVR header (MOSFET closed; no power from Pi).
XXX Raspberry Pi powered primarily by own power supply.
Servos pull power from USB-C or RVR header, whichever works best (MOSFET closed; no power from Pi).
OXX Raspberry Pi and servos are from USB-C or RVR header, whichever is best.
OOXPowered by individual power supplies.
OXO
XOO

No outlined in the table is the possibility of power being connected to the servo 5V rail.

USB-C Fuse

On the Pi Servo pHAT there is a fuse (2.5A hold and 5A trip) that limits current draw over the USB-C connection. If more than 5A is drawn, it automatically throttles the current draw and/or disconnects power until the load is removed. A bypass jumper is provided for users who want to remove this limitation; however, users should know what they are doing when using this jumper. As a recommendation, if you do not know what you are doing, you should leave this jumper alone. (see Jumpers section below)

Power Isolation

There is a power isolation jumper connected to the 40-pin GPIO header on the Pi Servo pHAT. This jumper can be cut to isolate the 5V pin of the Raspberry Pi from the 5V used on the Pi Servo pHAT. This is usually used when you expect to be using heavy loads or are worried about noise transferring back to the Raspberry Pi, which often results in intermittent power loss. (see Jumpers section below)

Cutting this jumper does not affect the serial UART connection. However, the jumper does need to be bridged, if you want to power the Raspberry Pi from the Pi Servo pHAT again.

PCA9685

The PCA9685 provides I2C control over the 16-channels of 12-bit pulse width modulation (PWM) on the Pi Servo pHAT. The PCA9685 is designed primarily for LED control, but can be used for other PWM devices like servos.

PCA9685
The PCS9685 16-channel PWM controller IC.
CharacteristicDescription
Operating Voltage (VDD)2.3 V to 5.5 V (Hardwired: 5V)
Operating Temperature-40°C to 85°C
PWM Outputs 16 Totem pole outputs (Default: Open-Drain)
Sink 25 mA or Source 10 mA (at 5V)
Shared PWM frequency
Supports hot insertion
PWM Frequency24Hz to 1526 Hz (Default (1Eh): 200Hz)
PWM Resolution12-bit (4096 steps of control)
Duty Cycle0% to 100% (adjustable)
Oscillator Internal: 25 MHz (Hardwired)
External: 50 MHz (max.) input (unavailable)
I2C Address 62 hardware configurable addresses (Hardwired: 0x40)
4 programmable addresses to allow simultaneous groups control of multiple devices:
  • 1- General All Call address.
  • 3- Sub Call addresses.

Although, the PWM frequency of all the channels are shared, the duty cycle of the 16 channels of PWM output can be controlled individually. This allows the PCA9685 to control servos or LEDs on each of the outputs. For LEDs, this allows the channels to control or drive the brightness; or the position on servos.

Servo/PWM Headers

The Pi Sevro pHAT can be utilized with various PWM devices, the most typically application will be servos and LEDs. These headers are spaced out to make it easier to attach servo motors to them. Additionally, they are broken out in the standard 3-pin configuration for most hobby-type servo motor connectors.

Servo motor pin headers
The servo headers connected to the 16 PWM channels.

Serial UART Connections

A Raspberry Pi can be interfaced over a serial connection through the Pi Servo pHAT. There are two different access points to the serial UART; the 4-pin header for the Sphero RVR and the USB-C connection. Control over which interface is used is provided by the RX switch on the Pi Servo pHAT.

RX Switch
The RX switch on the Pi Servo pHAT controls whether the TX line of the USB-C connection or Sphero RVR 4-pin header is used. Click to enlarge.

The indication of which connection is used should be straight forward. The interface that is labeled (USB or RVR) on the side that the switch is on (black nub), will indicate the TX connection to the RX pin of the Raspberry Pi for serial communication. As shown in the picture above, the TX line from the USB-C interface is connected to the RX pin of the Raspberry Pi. To change to TX line of the Sphero RVR 4-pin header, users just need to follow the arrow and slide the switch into the RVR position.

For more tips and details on serial communication, read our Serial Communication and Terminal Basics tutorials.

Troubleshooting Tip: If your SSH or serial connection isn't working, double check that this switch is in the proper position and the correct baud rate is used.

USB-C Connector

This connector can be used for power and to connect to the Pi via serial port connection, to access the Raspberry Pi remotely, without needing to use a monitor and keyboard to set up the Pi (see Headless Raspberry Pi Setup tutorial).

USB Seiral Interface
The USB-C interface for serial communication on the Pi Servo pHAT. Click to enlarge.

On the Pi Servo pHAT there is a fuse that limit current draw over the USB-C connection. If more than 5A is drawn, it automatically throttles the current draw and/or disconnects power until the load is removed.

Troubleshooting Tip: Users should take care NOT to pry or leverage on the connector when inserting/removing the USB cable. Doing so, WILL damage the board/connector and may cause the pads and/or traces to tear off as well. The cable should be removed by pulling straight outwards from the board.
CH340C

The CH340C is a USB-to-Serial adapter from WCH, used to convert data to and from USB-C connection to serial terminal of the Raspberry Pi, attached to the Pi Sevro pHAT. Newer operating systems should automatically recognize and install the driver for this chip. The driver allows your computer to recognize the Pi Servo pHAT as a serial device and lets your computer access the serial terminal on the Raspberry Pi.

The CH340 chip and driver have been tested on Windows 7, Windows 10, Mac OSX High Sierra, and Raspbian Stretch (11-13-2018 release) for the Raspberry Pi. However, there are a wide range of operating systems out there; and you may need to manually install your driver or delete/uninstall your old driver before updating to the new driver. We’ve also written a separate SparkFun Serial Basic CH340C Hookup Guide in case you run into issues. Use the buttons below to check and/or update your drivers.

Click the buttons above for further instructions on verifying
that your computer recognizes your board or updating your old drivers.

Driver Verification

To verify that your driver is working, you should see the difference in the following pictures after connecting to the Pi Servo pHAT from the USB-C connection. Alternatively, if you have a serial terminal emulator or the Arduino IDE installed, you should also see a change in the number of available Serial/COM Ports.

Windows

Check that the CH340 shows up in your device manager. You can click the Start or (Windows) button and type "device" to quickly search for the application. (*On Windows 10, the quick search function is picky on the spelling of the application you are searching for. For example, you may get results using "devi" and none for "device".)

Windows 10 Device Manager Window
Screenshot of Window 10 Device Manager with RedBoard (Qwiic) on COM42. Click to enlarge.

Mac OSX

Open the Terminal and run the following command "ls /dev/cu*" in the Terminal and check for the following changes (the serial port may show up under a different device name). To open the Terminal, open your Applications folder, Utilities folder, then double-click on Terminal. Otherwise, press (Command) + space bar (Space Bar) to launch Spotlight and type "Terminal," then double-click the search result.

Mac OSX CLI Command Entry
Screenshot of Mac OSX terminal with RedBoard (Qwiic) on cu.wchusbserialfd1410. Click to enlarge.

ls /dev/cu*
Note: If you are still unsure of how to access the Terminal, watch this video or read this Apple support article.

Raspbian

Run the following command "ls /dev/ttyUSB*" in the CLI/Terminal and check for the following changes (your serial port may show up under a different device name).

Raspbian CLI Command Entry
Screenshot of Raspberry Pi CLI with RedBoard (Qwiic) on ttyUSB0. Click to enlarge

ls /dev/ttyUSB*

Updating Drivers

The CH340C is made by WCH. You can find the latest version of their drivers here, but most of their pages are in Mandarin. If you use a Chrome web browser, you should have the option to have the web page translated.

If you have the older CH340 drivers installed, you may need to update them. Below are the instructions for doing so on each of the tested operating systems:

Windows 7/10

Download and run the executable. Click the "Uninstall" button first, followed by the "Install" button.

Win 10 Installation Screenshot
Windows CH340 Driver Installation

Mac OSX

Run the following commands in the CLI/Terminal before installing the new drivers:

rm -rf /System/Library/Extensions/usb.kext
rm -rf /System/Library/Extensions/usbserial.kext
Note:
To open the Terminal, open your Applications folder, Utilities folder, then double-click on Terminal. Otherwise, press (Command) + space bar (Space Bar) to launch Spotlight and type "Terminal," then double-click the search result.

If you are still unsure of how to access the Terminal, watch this video or read this Apple support article.
Download and extract the folder. Then, open the ".pkg" file from the unzipped folder.

Mac OSX Installation Screenshot
Mac OSX CH340 Driver Installation File

Raspbian

Run the following commands in the CLI/Terminal:

sudo apt-get upgrade
sudo apt-get update

Other Linux Distributions

Unfortunately, we cannot test all Linux distributions, but here is the downloadable .zip folder for the CH340 driver should you need it.

CH340C
The USB-C interface for serial communication on the Pi Servo pHAT. Click to enlarge.

Whenever you send or receive serial data on the USB-C connection, you should seen the RX (yellow) and/or TX (green) LEDs flashing. The RX pin is shares a connection with the 4-pin RVR header and may flash when it is receiving data.

RVR Header

The Sphero RVR requires a 4-pin header to access a Raspberry Pi. On the Pi Servo pHAT we have broken out this connection for a painless integration with the Sphero RVR.

RVR Header Pins
4-pin header for Sphero RVR to access the serial terminal of the Raspberry Pi.

Qwiic Connector

Note: Users should use caution when adding non-Qwiic devices or using a Qwiic jumper cable, as there is no circuit protection for this connector.

A Qwiic connector is provided for additional compatibility with our Qwiic line of products. The Qwiic system is intended to be a quick, hassle-free cabling/connector system to conveniently add your favorite I2C devices. The Qwiic connector is tied to the I2C pins of the Raspberry Pi and draws power directly from the 3.3V pins.

Qwiic Connection
Qwiic connector on the Pi Servo pHAT. Click to enlarge.
Note: There are a set of logic level converters on the I2C bus to step up the logic level for the PCA9685.

Jumpers

There are a few jumpers broken out on this board to easily modify a few hardware connections without having to rework individual components. If you are ot sure how to cut a jumper, please read our tutorial here! As a recommendation, please review what each jumper does before making a modification. This is especially true for the fuse bypass jumper, which can have dire consequences.

Power Isolation

This jumper is closed by default. It can be cleared/opened to isolate the power sources on the Pi Servo pHAT from the Pi 5V power rail.

5V Power Isolation Jumper
Power isolation jumper on the Pi Servo pHAT. Click to enlarge.
Note: As long as the Pi is powered, the serial interface will still work regardless of the state of this jumper.

Fuse Bypass

⚡ Danger: This jumper is used to bypass the fuse on the Pi Servo pHAT, which is part of the power protection circuitry. Only use this jumper if you know what you are doing; otherwise, a small mistake could cost you your whole project.

The bypass jumper is provided for users who want to remove the current limitation of the fuse on the USB-C connection; however, users should know what they are doing when using this jumper. The fuse is rated to a 2.5A hold and 5A trip current.

Fuse Bypass Jumper
Fuse bypass jumper on the Pi Servo pHAT. Click to enlarge.

As a recommendation, if you don't know what you are doing, you should leave this jumper alone. The USB-C is capable of delivering tremendous amounts of power and can easily damage hardware.

I2C Pull-Up

Cutting the I2C jumper will disconnect the 10 kΩ pull-up resistors from the I2C bus.

I2C Pull-Up Jumper
I2C pull-up jumper on the Pi Servo pHAT. Click to enlarge.

As an example, if you have multiple Qwiic devices with pull-up resistors connected, you may want to cut these jumpers. When there are multiple devices on the I2C bus with pull-up resistors, the equivalent parallel resistance may create too strong of a pull-up for the bus to operate correctly.

Hardware Assembly

Note: This tutorial assumes that users are familiar with the Raspberry Pi and have a general knowledge base of Python. If you have unfamiliar with these items, as a starting point, we suggest setting up your Raspberry Pi, familiarizing yourself with the graphics user interface (GUI), and then learning the basics of Python. Below are resources to get you started:

Raspberry Pi

Assembling the Pi Servo pHAT (v2) with a Raspberry Pi is pretty straight forward. First make sure that nothing is powered. Then, just stack the board onto the Raspberry Pi so that the PCBs line up on top of each other; the Pi Servo pHAT is NOT meant to protrude out to the side.

  • Stacking the Pi Servo pHAT with the PCB protruding to the side of the Raspberry Pi instead of on top (or above) will incorrectly connect pins and will most likely damage something.
  • Although usually minimal, even when connecting a Raspberry hat there is a chance to short, brown-out, and/or damage something. As a best practice, you should never plug in a hat while anything is powered (including the hat, servos, LEDs, or additional qwiic boards).
  • Make sure you aren't using a Raspberry Pi 4 or the Debian Buster image. Both have yet to be tested for use with this product.
  • Never plug in a servo while your Raspberry Pi is running. The sudden current spike needed to power your servo will reset your Raspberry Pi. Always plug in all of your servos first, and then boot up.

Never plug in a servo while your Raspberry Pi is running. The sudden current spike needed to power your servo will reset your Raspberry Pi. Always plug in all of your servos first, and then boot up.

Pi Servo pHAT on Raspberry Pi 3
Pi Servo pHAT on Raspberry Pi ZeroW

Pi Servo pHAT properly connected to a Raspberry Pi. Click image to enlarge.

Sphero RVR

Unfortunately, this tutorial won't cover the use of the Pi Servo pHAT with the Sphero RVR. Currently, the hookup guide for that is still in development, but a link will be provided when the kit and guide are ready. If you are interested, we do have kits available for pre-order. The hookup guide should be available shortly after we are able to get some production models and the kit goes live.

SparkFun Basic Autonomous Kit for Sphero RVR

SparkFun Basic Autonomous Kit for Sphero RVR

KIT-15302
$119.95
SparkFun Advanced Autonomous Kit for Sphero RVR

SparkFun Advanced Autonomous Kit for Sphero RVR

KIT-15303
$164.95

Other Single Board Computers

Using this hat with other single board computers (SBCs) like the Nvidia Jetson or Google Coral is a similar process. Just make sure that you have the HAT aligned in the proper orientation. For example, with the Nvidia Jetson, the hat should be protruding outwards from the board (do not try to remove the heatsink to make the HAT fit, that is the wrong orientation).

Pi Servo pHAT on Nvidia Jetson
Pi Servo pHAT properly connected to a Nvidia Jetson.

Power

As described in the Hardware Overview, 5V power to the servo headers is provided through three different sources.

Note: An example for the 4-pin header in use with the Sphero RVR kit is not available yet.
Power from Pi
Power from USB-C

Examples of the various power supply options.
Note: On the the Raspberry Pis (models below 4) use the micro-B connector labeled as the PWR IN port.

Servos

In this tutorial we will be testing out a hobby servo on channel "0". Based on the servo that you are using, try looking at the hobby servo's datasheet or referring to some of the standard servo connector pinouts listed in this tutorial.

Servo in Action
Pi Servo pHAT properly connected to a Raspberry Pi with servo working.

Qwiic Devices

The Qwiic connection system makes it easy to add your favorite Qwiic compatible sensor or device.

Adding Qwiic devices
Qwiic devices can be daisy chaned to the Pi Servo pHAT.

Software - Python

Note: A python library for this product will be released shortly. This section of the hookup guide will be updated at that time.

We'll go over in some detail here how to access and use the pi servo hat in Python. Full example code is available in the product GitHub repository.

Set Up Access to SMBus Resources

First point: in most OS level interactions, the I2C bus is referred to as SMBus. Thus we get our first lines of code. This imports the smbus module, creates an object of type SMBus, and attaches it to bus "1" of the Pi's various SMBuses.

language:python
import smbus
bus = smbus.SMBus(1)

We have to tell the program the part's address. By default, it is 0x40, so set a variable to that for later use.

language:python
addr = 0x40

Next, we want to enable the PWM chip and tell it to automatically increment addresses after a write (that lets us do single-operation multi-byte writes).

language:python
bus.write_byte_data(addr, 0, 0x20)
bus.write_byte_data(addr, 0xfe, 0x1e)

Write Values to the PWM Registers

That's all the setup that needs to be done. From here on out, we can write data to the PWM chip and expect to have it respond. Here's an example.

language:python
bus.write_word_data(addr, 0x06, 0)
bus.write_word_data(addr, 0x08, 1250)

The first write is to the "start time" register for channel 0. By default, the PWM frequency of the chip is 200Hz, or one pulse every 5ms. The start time register determines when the pulse goes high in the 5ms cycle. All channels are synchronized to that cycle. Generally, this should be written to 0.

The second write is to the "stop time" register, and it controls when the pulse should go low. The range for this value is from 0 to 4095, and each count represents one slice of that 5ms period (5ms/4095), or about 1.2us. Thus, the value of 1250 written above represents about 1.5ms of high time per 5ms period.

Servo motors get their control signal from that pulse width. Generally speaking, a pulse width of 1.5ms yields a "neutral" position, halfway between the extremes of the motor's range. 1.0ms yields approximately 90 degrees off center, and 2.0ms yields -90 degrees off center. In practice, those values may be slightly more or less than 90 degrees, and the motor may be capable of slightly more or less than 90 degrees of motion in either direction.

To address other channels, simply increase the address of the two registers above by 4. Thus, start time for channel 1 is 0x0A, for channel 2 is 0x0E, channel 3 is 0x12, etc. and stop time address for channel 1 is 0x0C, for channel 2 is 0x10, channel 3 is 0x14, etc. See the table below.

Channel #Start AddressStop Address
Ch 00x060x08
Ch 10x0A0x0C
Ch 20x0E0x10
Ch 30x120x14
Ch 40x160x18
Ch 50x1A0x1C
Ch 60x1E0x20
Ch 70x220x24
Ch 80x260x28
Ch 90x2A0x2C
Ch 100x2E0x30
Ch 110x320x34
Ch 120x360x38
Ch 130x3A0x3C
Ch 140x3E0x40
Ch 150x420x44

If you write a 0 to the start address, every degree of offset from 90 degrees requires 4.6 counts written to the stop address. In other words, multiply the number of degrees offset from neutral you wish to achieve by 4.6, then either add or subtract that result from 1250, depending on the direction of motion you wish. For example, a 45 degree offset from center would be 207 (45x4.6) counts either more or less than 1250, depending upon the direction you desire the motion to be in.

Examples

Below, are some convenient examples for users to draw from.

Example 1: 50 Hz Frequency

Unlike the higher-end or modern servos that can handle higher frequencies, most servos (often older and cheaper) prefer a 50 Hz PWM frequency and will struggle with a 200 Hz PWM frequency. Usually, they end up buzzing or over heating, while trying to search for hone/track their position.

Servo in Action
Example 1 with servo working.

Below is an example of how to configure the PCA9685 to drive at a 50 Hz PWM frequency. This does reduce the resolution of the servo arm position, but for most servos that was probably causing the servo to overheat anyways.

language:python
import smbus, time
bus = smbus.SMBus(1)
addr = 0x40

## Running this program will move the servo to 0, 45, and 90 degrees with 5 second pauses in between with a 50 Hz PWM signal.

bus.write_byte_data(addr, 0, 0x20) # enable the chip
time.sleep(.25)
bus.write_byte_data(addr, 0, 0x10) # enable Prescale change as noted in the datasheet
time.sleep(.25) # delay for reset
bus.write_byte_data(addr, 0xfe, 0x79) #changes the Prescale register value for 50 Hz, using the equation in the datasheet.
bus.write_byte_data(addr, 0, 0x20) # enables the chip

time.sleep(.25)
bus.write_word_data(addr, 0x06, 0) # chl 0 start time = 0us

time.sleep(.25)
bus.write_word_data(addr, 0x08, 209) # chl 0 end time = 1.0ms (0 degrees)
time.sleep(.15)
bus.write_word_data(addr, 0x08, 312) # chl 0 end time = 1.5ms (45 degrees)
time.sleep(.15)
bus.write_word_data(addr, 0x08, 416) # chl 0 end time = 2.0ms (90 degrees)

while True:
     time.sleep(.5)
     bus.write_word_data(addr, 0x08, 209) # chl 0 end time = 1.0ms (0 degrees)
     time.sleep(.5)
     bus.write_word_data(addr, 0x08, 312) # chl 0 end time = 1.5ms (45 degrees)
     time.sleep(.5)
     bus.write_word_data(addr, 0x08, 209) # chl 0 end time = 1.0ms (0 degrees)
     time.sleep(.5)
     bus.write_word_data(addr, 0x08, 416) # chl 0 end time = 2.0ms (90 degrees)

Example 2: Create a Function

This example creates simple functions to set the start and end times of the PWM signal based on the designated servo position for a specific channel. This example should make it easier for users to create their own scripts with more limited knowledge of the python language.

language:python
import smbus, time
bus = smbus.SMBus(1)
addr = 0x40

def servo_Init(channel):
     # Mapping Channel Register
     channel_0_start = 0x06
     channel_reg = 4*channel + channel_0_start

     # Write to Channel Register
     bus.write_word_data(addr, channel_reg, 0) 


def servo_Pos(channel, deg_range, deg_position):
     # Mapping Channel Register
     channel_0_end = 0x08
     channel_reg = 4*channel + channel_0_end

     # Mapping Sevo Arm Position
     #   209 = 0 deg
     #   312 = 45 deg
     #   416 = 90 deg
     deg_0 = 209
     deg_max = 416
     pos_end_byte = lambda x: (deg_max-deg_0)/deg_range*x + deg_0

     # Write to Channel Register
     bus.write_word_data(addr, channel_reg, round(pos_end_byte(deg_position)))

## Running this program will move the servo to 0, 45, and 90 degrees with 5 second pauses in between with a 50 Hz PWM signal.

# Configure 50Hz PWM Output
bus.write_byte_data(addr, 0, 0x20) # enable the chip
time.sleep(.25)
bus.write_byte_data(addr, 0, 0x10) # enable Prescale change as noted in the datasheet
time.sleep(.25) # delay for reset
bus.write_byte_data(addr, 0xfe, 0x79) #changes the Prescale register value for 50 Hz, using the equation in the datasheet.
bus.write_byte_data(addr, 0, 0x20) # enables the chip

# Initialize Channel (sets start time for channel)
servo_Init(3)

# Run Loop
while True:
     time.sleep(.5)
     servo_Pos(3, 90, 0) # chl 3 end time = 1.0ms (0 degrees)
     time.sleep(.5)
     servo_Pos(3, 90, 45) # chl 3 end time = 1.5ms (45 degrees)
     time.sleep(.5)
     servo_Pos(3, 90, 0) # chl 3 end time = 1.0ms (0 degrees)
     time.sleep(.5)
     servo_Pos(3, 90, 90) # chl 3 end time = 2.0ms (90 degrees)

Troubleshooting Tips

Checking Your I2C Connection

A simple method to check if your Raspberry Pi can communicate with the Pi Servo pHAT over I2C is to ping the I2C bus. On the latest releases of Raspbian Stretch, the i2ctools package should come pre-installed. If it isn't run the following command in the terminal:

sudo apt-get install i2ctools

Once the i2ctools package is installed, you can ping the I2C bus with the following command in the terminal:

i2cdetect -y 1

You should see a table printed out in the terminal. If the Servo pHAT is connected/working properly you should see the address space for 0x40 marked with 40.

Current Draw Issues

If your servos are drawing more current that your power supply can handle, your Pi Servo pHAT will not operate correctly and the Raspberry Pi may reboot/brown out itermittently.

Otherwise, if the power isolation jumper is cut, the Raspberry Pi will continue to work since its power supply is isolated from the Pi Servo pHAT. However, the PCA9685 will reset itermittently. A good indicator for this is if you see/hear the attached servos respond to the default configuration for the PCA9685. Another option is to ping the Servo pHAT, as mentioned in the issue above. If you ping the board fast enough (us the up arrow key on your keyboard to pull up a previous entry), you will occasionally that the Pi Servo pHAT address will disappear from the address table.

All Other Questions: Post on the Forum

If you still have questions or issues with this product, please create a post on our forum under the Pi Servo pHAT (DEV-15316): Questions and Issues topic.

Resources and Going Further

For more information, check out the resources below:

Need some inspiration for your next project? Check out the tutorials below:

Raspberry Pi Tutorials

Headless Raspberry Pi Setup

Configure a Raspberry Pi without a keyboard, mouse, or monitor.

How to Use Remote Desktop on the Raspberry Pi with VNC

Use RealVNC to connect to your Raspberry Pi to control the graphical desktop remotely across the network.

Graph Sensor Data with Python and Matplotlib

Use matplotlib to create a real-time plot of temperature data collected from a TMP102 sensor connected to a Raspberry Pi.

How to Run a Raspberry Pi Program on Startup

In this tutorial, we look at various methods for running a script or program automatically whenever your Raspberry Pi (or other Linux computer) boots up.

Robotics Tutorials

Continuous Rotation Servo Trigger Hookup Guide

How to use the SparkFun Continuous Rotation Servo Trigger with continuous rotation servos, without any programming!

Getting Started with the AutoDriver - v13

SparkFun's AutoDriver is a powerful tool for controlling stepper motors. Here's how to use it.

SparkFun Inventor's Kit Experiment Guide - v4.0

The SparkFun Inventor's Kit (SIK) Experiment Guide contains all of the information needed to build all five projects, encompassing 16 circuits, in the latest version of the kit, v4.0a.

Qwiic Joystick Hookup Guide

Looking for an easy way to implement a joystick to your next Arduino or Raspberry Pi project? This hookup guide will walk you through using the Qwiic Joystick with the Arduino IDE on a RedBoard Qwiic and in Python on a Raspberry Pi.

Servo and Motor Control Tutorials

Motors and Selecting the Right One

Learn all about different kinds of motors and how they operate.

Actobotics Basic Differential Platform

Get started with Actobotics with this simple vehicle. Then expand and customize it for your own evil robot empire.

Wireless Motor Driver Shield Hookup Guide

Get started with the SparkFun Wireless Motor Driver Shield!

SparkFun Inventor's Kit Experiment Guide - v4.0

The SparkFun Inventor's Kit (SIK) Experiment Guide contains all of the information needed to build all five projects, encompassing 16 circuits, in the latest version of the kit, v4.0a.

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

SparkFun gator:particle Hookup Guide

$
0
0

SparkFun gator:particle Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Do you have an experiment involving biometrics or particle detection?

SparkFun gator:particle - micro:bit Accessory Board

SparkFun gator:particle - micro:bit Accessory Board

SEN-15271
$10.95

The gator:particle is an amazing tool that uses a high-sensitivity pulse oximeter and heart-rate sensor, the MAX30102. Similar to the SparkFun Particle Sensor, with the MAX30105 high-sensitivity optical sensor, the gator:particle can also be used for particle detection. The primary difference between these boards is that the SparkFun Particle Sensor also uses a green LED that requires more power than the micro:bit can provide. This tutorial will show you how to get started using the gator:particle sensor with the gator:bit (v2) in the micro:bit development environment.

Required Materials

To get started, you'll need a micro:bit to control everything. Each of the products below includes a micro:bit, but the kit and bundle also include some additional accessories that you may want as well.

SparkFun Inventor's Kit for micro:bit

SparkFun Inventor's Kit for micro:bit

KIT-15228
$49.95
micro:bit Go Bundle

micro:bit Go Bundle

DEV-14336
$16.50
16
micro:bit Board

micro:bit Board

DEV-14208
$14.95
7

To easily use the gator board ecosystem, a gator:bit (v2) will help breakout the necessary pins and you will also need alligator and/or banana cables to connect the gator:bit to the gator:particle.

SparkFun gator:bit v2.0 - micro:bit Carrier Board

SparkFun gator:bit v2.0 - micro:bit Carrier Board

DEV-15162
$19.95
Alligator Test Leads - Multicolored (10 Pack)

Alligator Test Leads - Multicolored (10 Pack)

PRT-12978
$3.25
4
Banana to Banana Cable - Right Angle

Banana to Banana Cable - Right Angle

CAB-15368
$4.95

(*These banana cables have a special diameter on the attachment points designed specifically for use with the micro:bit ecosystem. They may or may not be compatible with the banana cables used on your test equipment.)

You may already have some of these materials, so feel free to modify your cart as necessary.

Suggested Reading

There isn't much to learning how to use the gator:particle sensor. However, you may find the following concepts useful along the way.

Light

Light is a useful tool for the electrical engineer. Understanding how light relates to electronics is a fundamental skill for many projects.

Logic Levels

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

I2C

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

MAX30105 Particle and Pulse Ox Sensor Hookup Guide

The SparkFun MAX30105 Particle Sensor is a flexible and powerful sensor enabling sensing of distance, heart rate, particle detection, even the blinking of an eye. Get ready. Set. Shine!

If you aren't familiar with the micro:bit, 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.

Getting Started with the micro:bit

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

How to Load MicroPython on a Microcontroller Board

This tutorial will show you how to load the MicroPython interpreter onto a variety of development boards.

SparkFun gator:bit v2 Hookup Guide

The gator:bit v2 is a breakout board for the BBC micro:bit. The gator:bit exposes almost every pin on the micro:bit to clippable pad with circuit protection. It also has as built-in addressable LEDs and a built-in buzzer.

Hardware Overview

The gator:particle consists of 4 pads for power and data.

ContactsDirectionDescription
GNDN/AGround: Reference voltage and ground loop.
3.3VInPower: Provides 3.3V to board.
SDABi-directionalData: Data and commands are transmitted between the sensor and microcontroller.
SCLInClock: The microcontroller provides the timing needed to communicate on the data line.

Power

The specified operating voltage for the MAX30102 is between 1.7V - 2V. For use with the gator:bit (v2) and micro:bit, you should provide 3.3V through the 3V3 and GND pads to keep the logic levels consistent; the 3.3V input is then regulated to 1.8V for the MAX30102.

Power Connections and LED
Power connection pads and power indication LED.

MAX30102

The MAX30102 is a high-sensitivity pulse oximeter and heart-rate sensor that communicates over an I2C bus. The MAX30102 uses both red and IR LEDs along with a very sensitive photodetector for pulse oximetry (SpO2), heart-rate (HR) monitoring, and particle (PM) detection. For the most part, users will only need to know I2C addresses to prevent address conflicts with other devices or sensors.

MAX30102 IC
MAX30102: HR and SpO2 sensor.

Here are some of the characteristics of the MAX30102 sensor from the datasheet:

CharacteristicRange
Operating Voltage1.8V to 2V
Supply Current Heart Rate and SpO2 Mode: 600 to 1200 µA
IR Only Mode: 600 to 1200 µA
Operating Temperature-40°C to 85°C
(ΣΔ) ADC Resolution: 15 to 18-bits (programmable)
Sampling Rate: 50 - 3200 sps (programmable)
IR LED LED Wavelength: 870 to 900 nm (avg. 880 nm)
Forward Voltage: 1.4V
Radiant Power: 6.5 mW
LED Driver Current: 0 to 50 mA (programmable)
Red LED LED Wavelength: 650 to 670 nm (avg. 660 nm)
Forward Voltage: 2.1V
Radiant Power: 9.8 mW
LED Driver Current: 0 to 50 mA (programmable)
Photodetector Spectral Range of Sensitivity: 600 to 900 nm
Radiant Sensitive Area: 1.36 mm2
I2C Address 0xAE - Write Address
0xAF - Read Address

What are Heart-Rate and Oxygen Saturation?

Heart-rate is the speed at which your heart pumps blood through your body. Pulse oximetry is a noninvasive method of determining saturation of oxygen in your blood. However, this is a peripheral measurement is not always a direct reflection of the arterial oxygen saturation (SaO2), but two are correlated enough for clinical purposes. There are a multitude of applications for these measurements; especially, in the medical field.

Here are some examples of studies using HR monitoring and pulse oximetry:

Here are additional resources on how the MAX30102 functions for HR detection and pulse oximetry:

Note: The MAX30102 can be used as a biosensor that for SpO2 and HR measurements on finger tips or earlobes. The sensor does need good contact with constant pressure against the epidermis for accurate results.

What are Particulates?

Particulate matter is the accumulation of matter (solid or liquid) in Earth's atmosphere. These particles vary in size, composition, and distribution. Their effects range from individual health on a microscopic scale to regional climate on a macroscopic scale. Particulate matter is also used in the food industry. Apiarist traditionally use bee smokers when harvesting honey. Smoking is also a method of flavoring and preserving meats and other products.

Here is a link to some experiments involving PM:

For more information on particulate matter and their detection, check out some of these resources:

Note: Particle detection is another application of the MAX30102. The sensor relies on the reflection and scattering of the red and IR light from particles to detect their presence.

I2C Connection

I2C is a communication protocol used to transfer data between master and slave devices. It is a 2-wire connection consisting of SDA (data) and SCL (clock). The protocol is pretty well defined so it can be shared with multiple devices. This is beneficial for daisy chaining multiple devices together on a single bus. The primary thing users will need to watch out for is address conflicts (you can't have devices with the same address).

I2C Connection
I2C connection pads.

Hardware Assembly

Connecting your gator:particle to the gator:bit (v2) is simple. The board can also be daisy-chained with other I2C boards. This can easily be done with alligator cables or these special banana cables.

Hardware Assembly
Hardware assembly of connections used in example. Click to enlarge.
Daisy Chain
Example of daisy chaining multiple I2C gator boards. Click to enlarge.
Gator:UVGND3V3SDASCL
Gator:BitGND3.3V OUTP20 (SDA)P19 (SCL)

Adding the MakeCode Extension

Note: This tutorial assumes you are familiar with MakeCode, the gato:bit (v2), and the micro:bit board.

The easiest way to get started using the gator:particle is to use Microsoft MakeCode, a web-based block editor. This tutorial assumes you are familiar with the with MakeCode, the gato:bit (v2), and the micro:bit development board. If this is your first time check out this guides linked in the suggested reading section (above).

Installing Extensions

To get started with using MakeCode with the miccro:bit, head over to the MakeCode for micro:bit website by Microsoft. Then, click the New Project button to start a new project and open the Editor. (*Yes, all you only need to get start coding is a computer with internet access, an up-to-date web browser, and an available USB port!)

MakeCode Website
Click the New Project button to start a new project and open the Editor. Click on image to enlarge.

Once you have the editor up, click on the the Advanced block in the block library to reveal the drop down menu.

Editor
Click on the the Advanced block in the block library to reveal the drop down menu. Click on image to enlarge.

Finally, click on the Extensions block. This should bring up the extensions page. (*Alternatively, you could also click on the extensions link from the settings menu.)

Advanced Block
Click on the the Extensions block to open the extensions page. Click on image to enlarge.

There are two methods for finding the gator:particle extension:

  • Search for the name used on the extension3.
  • Use the link to the GitHub repository for the pxt-package as the search term.

Extensions Page
Use the search bar to find the extension you want to install. Click on image to enlarge.
Note: Unfortunately, it does take time to get an extension approved by the micro:bit Educational Foundation before it can be searchable by name. Part of the requirements for the approval process involves a live product page. Therefore, at the time of the launch of this product, the extension has not been approved yet and the only method of adding the extension is to use the link to the GitHub repository of the pxt-package. We will update this tutorial as soon as the extension has been approved.

Search for the PXT-Package

Search for the gator:particle extension using the GitHub repository link to the pxt-package:

https://github.com/sparkfun/pxt-gator-particle

Search for Extension
Search for Extension. Then, click on the box to add it to the block library. Click on image to enlarge.

Then, click on the box for the extension to add it to the block library. The gator:particle extension should now appear in the block library.

Extension in Block Library
Extension in the block library; click on the block to open menu options. Click on image to enlarge.

To verify that you have added the extension, click on the gator:particle block to make sure that your drop down menu options match the image below.

Menu Options
Available blocks for the gator:particle extension. Click on image to enlarge.

MakeCode Example

Now that you have added the gator:particle extension to the Editor, lets start with some example code. Plug the micro:bit into your computer using an USB micro-B cable after you have assembled your hardware with the instructions from the previous section. The micro:bit should appear on your computer as a removable storage device.

USB Drive
The micro:bit showing up as a USB drive on a Windows computer. Click to enlarge.

To upload new code, this is where you will be copying the downloaded .hex file to later.

Block Functions

initialize gator:particle sensor
This block should be pretty self explanatory, it sets the sensor up to be used. You should use this within the on start block.

get _____ value
This is a value block as indicated by the block's shape. The output is an integer value from 0 to 262,143 for the sensor's detection of the specified wavelength. There is a drop down menu with selectable options for the sensor reading for the block. Below is a description of the available menu options:

  • red- An 18-bit integer value for sensor detection in the IR wavelength (0 and 262,143).
  • infrared- An 18-bit integer value for sensor detection in the IR wavelength (0 and 262,143).
  • With the default LED intensity, I was only able to see a maximum of approximately 120,000. To get higher values, the LED intensity needs to be turned up.

detect heartbeat in _____
This is a value block as indicated by the block's shape. There is a drop down menu with selectable options for the output value of the block. Below is a description of the available menu options:

  • BPM- Outputs a single heart-rate measurement in beats per minute (BPM).
  • AVG- Outputs the average of the last four heart-rate readings in BPM.

Set LED mode to read _____
This block should allows users to designate the LED modes. There are only two opions:

  • red- Only the red LED is used or on.
  • red & infrared- Both the red and IR LEDs are on.
  • There is no option to use only the IR LED.

Change strength of _____ to _____
This block should allows users to control the brightness or intensity of the LEDs.

  1. LED- Users designate which LED to control.
    • red
    • infrared
  2. Strength- Users specify the intensity of the LED. Enter an integer.
    • 0 to 255

Basic Read

Below, is a simple example of how to take simple measurements from the sensor. To use this example, there are multiple options for accessing the .hex file:

  • Replicate the block functions from the display below to copy the example project. Then download the .hex file.
  • Expand the display widow to pull up the example project. Then download the .hex file.
  • Use this link to pull up the example project. Then download the .hex file.
  • Download the .hex file from the button below or the link on the bottom of the display.

The output is redirected over the serial port to avoid conflicts on pins P0 and P1, which are also used for serial communication. To read the sensor values, pull up your favorite serial terminal emulator. Then, connect to the serial port that the micro:bit is on; the default baud rate is 115200 bps. Below, is an example of the sensor output for the example code.

Sample Readings
Example of readings from the sensor.

Troubleshooting Tips

Here are a few tips for troubleshooting this device.

Heart-Rate and SpO2

Make sure that you are making good contact and have constant pressure on the sensor. For the best results, use your finger tip. A special open-source algorithm is used to determine the Heart-Rate and SpO2 measurements. The algorithm is relatively accurate, but is primarily meant for demonstration purposes and should not be used in critical applications for monitoring a person's health.

If you still have questions or issues with this product, please create a post on our forum under the Gator Products topic.

Additionally, if you are an educator and you have class or application based questions, please create a post on our forum under the Educational Products topic.

Resources and Going Further

For more product information, check out the resources below:

Interested in the micro:bit? Check out some of these other micro:bit products:

SparkFun gator:bit v2.0 - micro:bit Carrier Board

SparkFun gator:bit v2.0 - micro:bit Carrier Board

DEV-15162
$19.95
SparkFun Inventor's Kit for micro:bit Lab Pack

SparkFun Inventor's Kit for micro:bit Lab Pack

LAB-15229
$450.00
SparkFun micro:climate kit for micro:bit

SparkFun micro:climate kit for micro:bit

KIT-15301
$117.95
1
SparkFun Inventor's Kit for micro:bit

SparkFun Inventor's Kit for micro:bit

KIT-15228
$49.95

Need some inspiration for your next project? Check out some of these other micro:bit product tutorials:

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.

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!

How to Load MicroPython on a Microcontroller Board

This tutorial will show you how to load the MicroPython interpreter onto a variety of development boards.

How to Create a MakeCode Package for Micro:Bit

Learn how to develop code blocks for the Micro:bit in Microsoft MakeCode!

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

Hookup Guide for the BlackBoard Artemis ATP

$
0
0

Hookup Guide for the BlackBoard Artemis ATP a learn.sparkfun.com tutorial

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

Introduction

We affectionately refer to the BlackBoard Artemis ATP as the "All The Pins!" board, since it breaks out every single one of the Artemis Module's 48 GPIO pins into a familiar Mega like form factor. On top of the BlackBoard's improved power conditioning and USB to serial, we've added a slew of features to help you take full advantage of the Artemis module's unique features. Let's have a look!!

BlackBoard Artemis ATP

BlackBoard Artemis ATP

SPX-15412
$24.95

Required Materials

You'll need the BlackBoard Artemis ATP and a USB C cable. Any USB C cable should work, including the one that probably came with your phone charger.

BlackBoard Artemis ATP

BlackBoard Artemis ATP

SPX-15412
$24.95
USB 2.0 Cable A to C - 3 Foot

USB 2.0 Cable A to C - 3 Foot

CAB-15092
$3.95

Suggested Reading

If you aren't familiar with the Qwiic system, we recommend reading here for an overview.

Qwiic Connect System
Qwiic Connect System

We also recommend checking out these tutorials before continuing:

I2C

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

RedBoard Qwiic Hookup Guide

This tutorial covers the basic functionality of the RedBoard Qwiic. This tutorial also covers how to get started blinking an LED and using the Qwiic system.

Using SparkFun Edge Board with Ambiq Apollo3 SDK

We will demonstrate how to get started with your SparkFun Edge Board by setting up the toolchain on your computer, examining an example program, and using the serial uploader tool to flash the chip.
New!

Designing with the SparkFun Artemis

Let's chat about layout and design considerations when using the Artemis module.
New!

Artemis Development with Arduino

Get our powerful Artemis based boards (Artemis Nano, BlackBoard Artemis, and BlackBoard Artemis ATP) blinking in less than 5 minutes using the SparkFun Artemis Arduino Core!

Hardware Overview

If you've ever used an Arduino Mega before you should be pretty familiar with the various female headers and the barrel jack power. In this tutorial we'll be covering the unique aspects of the BlackBoard Artemis ATP.

Front view of the SparkFun BlackBoard Artemis ATP

Serial and JTAG Programming

The BlackBoard Artemis ATP has two methods for programming. The most common is the USB C connector that operates as a USB to serial bridge. By simply pressing 'Upload' in the Arduino IDE or 'make bootload' from the SDK the firmware on Artemis is updated.

We use the CH340C on the BlackBoard Artemis ATP. You shouldn't need to install drivers but if you run into problems head on over to our CH340 hookup guide.

The second method is JTAG programming. An unpopulated JTAG footprint is available for more advanced users who need breakpoint level debugging. We recommend checking out our JTAG section for the compatible male header and a compatible JTAG programmer and debugger.

BlackBoard Artemis ATP USB C and JTAG ports

USB-C and JTAG footprints

Mic and RTC

The Artemis exceeds at low power voice recognition. To enable this we've included a PDM MEMS microphone on the board. Additionally, the Artemis module can operate an RTC given an external 32kHz crystal so we've included that was well.

PDM Microphone and RTC on BlackBoard Artemis ATP

Pins 36 and 37 are connected to the onboard PDM MEMS microphone and are broken out on the upper right side of the ATP board. You can hookup a second PDM microphone to pins 36/37 or you can load PDM firmware onto the Artemis module and watch PDM traffic from the microphone(s).

Pins 36 and 37 are on the upper right hand side of the front of the board

If you have no plans to use the on-board microphones, pins 36 and 37 can be used as GPIO by cutting the jumpers on the back of the board.

Cut these two jumpers on the back of the board to use Pins 36 and 37 as GPIO

Qwiic and I2C

The I2C pins on the Artemis are labeled SDA and SCL. They are controlled in the Arduino IDE using Wire.begin(), Wire.read(), etc. The same SDA/SCL pins are connected to the Qwiic connector so you can use SparkFun's Qwiic ecosystem (there's over 50 boards and more every week!).

Qwiic connector on BlackBoard Artemis ATP

Serial0, AREF, and USB Pads

On the rear of the BlackBoard ATP are some advanced features. Normally, an AREF pin is located between to the SDA and GND pins. The Artemis module has no equivalent pin so we've converted that pin to GND. If you have a shield that utilizes the AREF pin or just want to free it, you can cut the AREF jumper and the labeled 'GND' located between SDA and GND will be left disconnected.

On Artemis, TX0/RX0 are used for bootloading new code and Serial.println() statements to the computer's terminal window. The CH340C takes care of the serial to USB conversion. However, if you need access to these pins, they are available. TX0/RX0 can be used as GPIO as well as special functions, but for most applications these pins are left as Serial for bootloading.

For users who are embedding the BlackBoard Artemis ATP into an enclosure, the USB pads are exposed so that an external USB connector can be located at the edge of the enclosure and wired back to the USB pads.

Back of BlackBoard Artemis ATP showing various SMD pads and jumpers

Current Measurement Jumper

The Artemis can run as low as 6μA/MHz, meaning the module can run at 48MHz at less than half a milliamp. To enable measurements and to isolate the power hungry devices (such as the LM317 voltage regulator) we've added a NC (normally closed) jumper. By cutting the jumper the VDD trace to the module is interrupted. Soldering in a male jumper or wires into the accompanying holes will give you the ability to insert a current meter and precisely monitor how much current your application is consuming.

For the vast majority of projects a wall adapter or USB power can be used. But when properly isolated the Artemis can run on a coincell battery for weeks! So we've designed in a 20mm SMD coin cell footprint so that users can experiment with powering the Artemis from a standard CR2032. You can pickup the compatible coincell holder here.

Current Measurement Jumper

Click the image for a closer look

Bypass Jumper

USB C is wonderful. It's reversible and can source up to 2 amps at 5 volts without any power delivery (PD) negotiation. We've included a 2A resettable fuse (often called a PTC) on the Artemis as a safety feature in case your project decides to consume inordinate amounts of power (And possibly begins to spark and set fire. That was fun wasn't it? Get it? SparkFun?). In the event the BlackBoard begins to pull more than 2 amps from the USB source, the resettable fuse will automatically trigger and disconnect the board from the computer or power supply. This should protect your power source and the traces on your BlackBoard.

However, there are plenty of legitimate projects that need more than 2A. We've designed the power traces to withstand up to 2A with a 10C rise in temperature. If your power supply can provide adequate power, and you know what you are doing, you can close the BYP jumper, thus circumventing the resettable fuse.

The bypass jumper on BlackBoard Artemis ATP

I/O Masters

You can have up to 6 I2C or SPI masters with the BlackBoard Artemis ATP, and these pins are distributed across the board. We've listed each of the masters below with their associated pins. Check out the Apollo3 PinMap for more information.

MasterSCK/SCLMISO/SDAMOSI
M0567
M18910
M2272528
M3424338
M4394044
M5484947

Software Setup

The BlackBoard Artemis ATP runs both Arduino and the more advanced Ambiq HAL/SDK. Checkout these tutorials to get you up and blinking in 5 minutes!

New!

Artemis Development with Arduino

June 20, 2019

Get our powerful Artemis based boards (Artemis Nano, BlackBoard Artemis, and BlackBoard Artemis ATP) blinking in less than 5 minutes using the SparkFun Artemis Arduino Core!

Using SparkFun Edge Board with Ambiq Apollo3 SDK

March 28, 2019

We will demonstrate how to get started with your SparkFun Edge Board by setting up the toolchain on your computer, examining an example program, and using the serial uploader tool to flash the chip.

Troubleshooting

Resources and Going Further

Did you know you can use the BlackBoard Artemis ATPas the starting point of your very own Artemis product? Get the design files from our repo here and edit them using Eagle PCB!

For more information on the BlackBoard Artemis and the Artemis module itself, check out the links below:

You've now explored the board, let's get blinking with Arduino! Or perhaps you want to learn a little more about the Artemis module itself. Checkout these tutorials!

New!

Designing with the SparkFun Artemis

Let's chat about layout and design considerations when using the Artemis module.
New!

Artemis Development with Arduino

Get our powerful Artemis based boards (Artemis Nano, BlackBoard Artemis, and BlackBoard Artemis ATP) blinking in less than 5 minutes using the SparkFun Artemis Arduino Core!
New!

Hookup Guide for the BlackBoard Artemis Nano

Get started with the powerful BlackBoard Artemis Nano

Did you know the Artemis is compatible with our Qwiic line? Checkout these products that simply plug in and work!

SparkFun Human Presence Sensor Breakout - AK9753 (Qwiic)

SparkFun Human Presence Sensor Breakout - AK9753 (Qwiic)

SEN-14349
$25.95
2
SparkFun Qwiic Shield for Arduino

SparkFun Qwiic Shield for Arduino

DEV-14352
$6.95
Zio Haptic Motor Controller - DRV2605L (Qwiic)

Zio Haptic Motor Controller - DRV2605L (Qwiic)

ROB-15181
$22.95
SparkFun GPS Breakout - ZOE-M8Q (Qwiic)

SparkFun GPS Breakout - ZOE-M8Q (Qwiic)

GPS-15193
$44.95
1

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

Modifying Your EL Wire Inverter

$
0
0

Modifying Your EL Wire Inverter a learn.sparkfun.com tutorial

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

Introduction

In this tutorial, we will modify the 12V EL wire inverter's in order to power the EL Sequencer or EL Escudo Dos off a single power supply.

alt text

Required Materials

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

Tools

You will need a soldering iron, solder, and general soldering accessories. You will also need a screwdriver , alligator clip, and multimeter for testing.

  • Soldering Iron
  • Solder
  • Flux
  • Screw Driver
  • Multimeter

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.

Getting Started with Electroluminescent (EL) Wire

This guide will help you get started with electroluminescent (EL) wire, tape, panel, chasing wire, and bendable wire to let your project glow!

EL Sequencer/Escudo Dos Hookup Guide

A basic guide to getting started with the SparkFun EL Sequencer and Escudo Dos to control electroluminescence (EL) wire, panels, and strips.

Hacking Your EL Wire Inverter's Connector

By default, the DC input on the 12V inverter has a connector that accepts a barrel jack connector. This is usually a great feature but we'd rather have that input be a JST connector so we can hook it directly to the EL Sequencer/EL Escudo Dos off a single power supply. Don't worry. We can easily hack one in. Remove the QC sticker on the back of the 12V EL inverter. Using a Phillips screwdriver, open the inverter's enclosure.

alt text

Remove the screw and open the case. The PCB will look different depending on when you ordered the 12V inverter. The inverter on the left is from an older model as opposed to the one on the right. Regardless of how the PCBs look, they will still function the same.

alt text

Remove the board from the enclosure so that we can remove the existing wires connected to the barrel jack connector. The wires with the black sheath will be the ones that we will be desoldering. On newer 12V inverters, there should be some hot glue between the wires and PCB. This is for strain relief. If there is hot glue, carefully separate the it between the cable and the components on the 12V inverter. Desolder the wires connected by heating the pin or PTH pad. If necessary, give the PTH pad a small bump on the table with the slap method to remove any solder before threading new wire through it. If the diode's pin is already soldered on the PTH pad, the wire would need to be soldered to the joint. Feel free to keep the wires connected to the barrel jack in your parts bin for a different project instead of tossing it.

alt text

Take note of what color wire is connected to the PTH and which side the wires were removed. The PCB may be different depending on when it was manufactured so there may not be any silkscreen indicating the input voltage for "+" and "-". The images in the center and far right did not have any silkscreen associated with the wiring. Usually the "+" is connected to the anode of the diode. In this case, we desoldered the wires from the PCB shown as sample 3 in the pictures below.

Sample 1Sample 2Sample 3

Having a hard time viewing the images? Click on image for a closer view.

Solder the new JST pigtail to the board. We'll be adding the wires to the bottom of the PCB. To be consistent with the wire colors for the input voltage, we will be connecting the red wire to the pad or pin that is connected to the diode's anode pin. Then we will be connecting the black wire to the other pad or pin that was desoldered.

alt text

Insert the board back into its respective enclosure while ensuring that the wires are between the openings. Re-insert the screw and tighten. Since the wire colors are the same, try labeling the EL inverter with a marker or tape to indicate the side that is the DC input and AC output. Usually the input voltage is closest to the switch.

alt text

Before powering up, insert jumper wire between your power adapter and DC input similar to how EL wire was tested in the Getting Started Guide. Keep in mind that the DC input has a polarity so VIN should be connected to the red wire and GND would need be connected to black wire. Then insert jumper wires between the AC output and EL Wire. If you need, feel free to add some electrical tape as a precaution when handling the AC output.

alt text

Insert the wall adapter to an outlet (or add a 9V battery if you are using this in a remote setup) to the connection to test. Using the wires connecting to the DC input, connect the red wire to the center pin of the barrel jack and the black wire to the sheath of the wall adapter. Flip the switch if you do not see the EL powering up. The EL wire should blink or stay on depending on the mode that is used.

EL Wire Powered

Now that we have modified the EL Inverter, the next step is to use it with the EL Sequencer or EL Escudo Dos! Plug the DC input you just made into the "DC TO INVERTER" connector, plug the AC output into the "AC FROM INVERTER" connector, and we're ready to fire things up! For more information, check out the guide below to adjust the solder jumper on the board before connecting.

EL Sequencer/Escudo Dos Hookup Guide

December 3, 2015

A basic guide to getting started with the SparkFun EL Sequencer and Escudo Dos to control electroluminescence (EL) wire, panels, and strips.

Resources & Going Further

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

EL Wire Light-Up Dog Harness

Learn how to create a light-up dog harness using EL wire for when you need to take your four-legged friend for a walk in the dark.

Heartbeat Straight Jacket

An EL project that displays one person's heartbeat on another person's costume.

Sound Reactive EL Wire Costume

Learn how to make your EL wire costumes sound reactive in this project tutorial.

EL Wire Hoodie

In this tutorial, we will sew standard electroluminescent (EL) wire to a hoodie.

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

EL Wire Pants

$
0
0

EL Wire Pants a learn.sparkfun.com tutorial

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

Introduction

The design and build time of this project depends on your experience manually sewing, the length of EL wire used, and where you are sewing it to. This can take about ~1 - 3 hours if you are following the side of pants.

In this tutorial, we will sew standard EL wire onto a pair of pants.

alt text

Required Materials

To follow along with this tutorial, you will need the following materials. We will be using standard EL wire on the pants. You may not need everything, depending on what you have and your setup. Add it to your cart, read through the guide, and adjust the cart as necessary.

EL Inverter - Battery Pack

EL Inverter - Battery Pack

COM-11222
$4.95
5
EL Wire - White 3m

EL Wire - White 3m

COM-10197
$9.95
1500 mAh Alkaline Battery - AA

1500 mAh Alkaline Battery - AA

PRT-09100

Tools

At a minimum, you will need a needle. If you are making an extension cable, you will need a soldering iron, solder, and general soldering accessories.

Needle Set

Needle Set

TOL-10405
$1.95

You Will Also Need

  • Pants
  • Clear Thread or Fishing Line
  • Binder Clips, Pins, or, Tape
  • Scissors

Suggested Reading

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

Getting Started with Electroluminescent (EL) Wire

This guide will help you get started with electroluminescent (EL) wire, tape, panel, chasing wire, and bendable wire to let your project glow!

Planning a Wearable Electronics Project

Tips and tricks for brainstorming and creating a wearables project.

How to Make a Custom EL Wire Extension Cable

In this tutorial, we will make a custom EL Wire extension cable as an alternative to splicing wire.

Prepare the EL Wire

Testing the EL Wire and EL Inverter

Before sewing the EL wire to a piece of clothing, make sure to test it out to see if it is functioning. To test, connect the EL wire to an inverter. In this case, we are using AA batteries and the 3V EL inverter battery pack.

Insert EL Wire's JST Connector into EL Battery Pack

With the battery in the EL inverter battery pack, press the button to test. If the EL wire lights up, both the EL wire and EL inverter are good to go!

EL Wire Lit Up

Planning the Path

Plan out where to add EL wire. To hold down the EL wire when sewing, we will be using binder clips. Depending on what you have, you could also try to use pins or tape. Place the EL wire into the binder clip and clamp it down against the fabric. Make sure to avoid clamping the EL wire down where the binder clip pinches as this can damage the corona wires.

Binder Clip Guiding EL Wire on Pants

In this case, all 3 meters of EL wire were used starting by the left pocket, running down the side of the leg, and back up to the waist. The EL wire then followed the waist in the back before running down the right side of the leg and back up to the right pocket. The length along each side was adjusted to be symmetric.

Planning a path with binder clips along the side of pants and waist

Prepare the Needle and Thread

For this tutorial, we will double up the clear thread. Prepare your needle and thread by inserting the end of the clear thread through the eye (opening) of the needle and pull it through. Cut about an arms length of thread (approximately 2 feet long) to work with. Tie the two ends of the fishing wires into a knot. You may need to use the needle to help guide the knot close to the end of the thread.

Pulling the Knot Closer To the End Using a Needle

Repeat the steps again for a second knot. Cut of any excess tail left over.

Clear Thread Tied in a Knot

Sewing the EL Wire

Start sewing by the EL wire's heat shrink and tie a knot around the EL wire. Continue making a loop around the EL wire to hold it down. When sewing with clear thread, make sure to pull the thread all the way through since the thread is slippery when sewn in certain fabrics. Be careful not to sew the front and back of the pants together. Also, ensure that the distance between each stitch is not too long. About 0.5" to 1.0" is a good stitch. Longer stitches can cause the EL wire to snag or become loose when wearing the EL pants.

alt text

After about 5x stitches, loop back through the last stitch with an overhand knot to lock the thread in and prevent it from sliding.

EL Wire Loop with Running Stitch

Once you begin to run out of thread to work with, tie the clear thread down against the fabric. Then repeat the steps outlined above with another piece of clear thread.

Clear Thread Tied in a Knot

When you are finished sewing the EL wire down, make a loop with the end of the EL wire and sew the wire down for strain relief. Make sure this loop is beyond the heat shrink as the connection at the heat shrink is sensitive to bending.

Thread with Strain Relief

Plug the EL wire back into the EL inverter to test it out. If it lights up, you are good to go! Place the EL inverter in a pocket or clip to a belt to enjoy! If you are using an EL inverter battery pack, you may want to make an extension cable.

EL Wire with Extension Cable and EL Inverter

Remember, EL wire works best in low light. It may be hard to see in daylight or in rooms with sources of light.

Different Pant Sizes

Remember what I said about the size of the pants? Different pant sizes will require different lengths of EL wire - this variation can cause the EL wire to not start or end where you expect it to. Note the difference in the the image compared to the youth sized pants.The beginning of the EL wire was sewn further down the pant leg and followed a narrow path as it headed back up toward the waist.

alt text

Resources and Going Further

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

EL Wire Light-Up Dog Harness

Learn how to create a light-up dog harness using EL wire for when you need to take your four-legged friend for a walk in the dark.

Heartbeat Straight Jacket

An EL project that displays one person's heartbeat on another person's costume.

Sound Reactive EL Wire Costume

Learn how to make your EL wire costumes sound reactive in this project tutorial.

Prototype Wearable LED Dance Harness

A project tutorial to add an extra effect for dancers performing a choreographed piece. The harness can be added quickly under a costume.

EL Wire Hoodie

In this tutorial, we will sew standard electroluminescent (EL) wire to a hoodie.

Looking for more ideas, check out these related blog posts:


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


Qwiic Ambient Light Sensor (VEML6030) Hookup Guide

$
0
0

Qwiic Ambient Light Sensor (VEML6030) Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The SparkFun Ambient Light Sensor (VEML6030) is an I²C enabled ambient light sensor with high sensitivity and high accuracy. It reads ambient light in Lux and boasts a number of nice features including: the ability to set high and low thresholds for an optional interrupt, power saving features that enable single digit micro-amp current draw, and a readable range from zero to 120,000 Lux. We've also written an Arduino library that gives full access to all features and includes example code demonstrating all its' abilities. Follow along and let's learn about all its features and how to use them!

SparkFun Ambient Light Sensor - VEML6030 (Qwiic)

SparkFun Ambient Light Sensor - VEML6030 (Qwiic)

SEN-15436
$4.95

Required Materials

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

If you need different size Qwiic cables we offer a kit that contains many sizes but we also carry them individually as well:

SparkFun Qwiic Cable Kit

SparkFun Qwiic Cable Kit

KIT-15081
$7.95
1
Qwiic Cable - 100mm

Qwiic Cable - 100mm

PRT-14427
$1.50
Qwiic Cable - 500mm

Qwiic Cable - 500mm

PRT-14429
$1.95
Qwiic Cable - Breadboard Jumper (4-pin)

Qwiic Cable - Breadboard Jumper (4-pin)

PRT-14425
$1.50

Suggested Reading

If you aren't familiar with the Qwiic system, we recommend reading here for an overview.

Qwiic Connect System

We would also recommend taking a look at the following tutorials if you aren't familiar with them.

I2C

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

How to Work with Jumper Pads and PCB Traces

Handling PCB jumper pads and traces is an essential skill. Learn how to cut a PCB trace, add a solder jumper between pads to reroute connections, and repair a trace with the green wire method if a trace is damaged.

RedBoard Qwiic Hookup Guide

This tutorial covers the basic functionality of the RedBoard Qwiic. This tutorial also covers how to get started blinking an LED and using the Qwiic system.

Hardware Overview

Power

You can provide 3.3V through the Qwiic connector on the board or through the 3V3 labeled pin on the through hole header. When you correctly power the board, the on-board red power LED will turn on.

This image shows a picture of the top of the product with the Qwiic connectors and two left most through holes highlighted.

LED

There is one red LED on the product that will turn on when power is supplied to the board. You can disconnect this LED by cutting the jumper on the underside of the product labeled LED, see Jumpers below.

This shows an image of the top of teh board with the top left Power LED highlighted.

Qwiic Connector or I2C Pins

There are two Qwiic connectors on the board to easily connect to the sensor via I2C. Another option is to solder directly to the I2C plated through holes on the side of the board. We have many Qwiic sensors and Qwiic enabled micro-controllers. Check out our Qwiic Ecosystem page to get a glimpse of what else we have to offer.

This shows an image of the product with the Qwiic connectors again highlighted but now the two pins labeled SDA and SCL for I2C data lines are now hightlighted as well.

Interrupt Pin

A nice feature on the SparkFun Ambient Light sensor is its ability to set both LOW and HIGH thresholds that triggers an interrupt on the product. For example, we can know when the light in a room falls below a certain amount and conversely when the light comes back on! You don't have to settle for just the hardware interrupt though. We also have a software solution, check out the interrupt example code below.

This image shows a picture of the product the right most interrupt through hole labeled "INT" highlighted.

Jumpers

There are three jumpers on the underside of this board. Starting in the lower left is a triple jumper labeled I2C that connects pull-up resistors to the I²C data lines. If you're daisy chaining many I²C devices together than you may need to consider cutting these traces.

I2C Jumper

To the right of that is the address jumper labeled ADR that allows you to select the SparkFun Ambient Light Sensor's other I²C address: 0x10. By default your SparkFun Ambient Light Sensor is shipped with the I²C address 0x48.

Address Jumper

Finally the jumper in the upper right is the LED jumper which can be cut to disconnect the on board power LED.

LED Jumper

Gain and Integration Time Settings

What does gain and integration time mean? You can think of gain as an electronic mechanism to amplify a weak signal. If you're in a dark room with very little light, the sensor needs a way to capitalize on that weak light source for its' lux calculations and so we need higher gain. Likewise, Integration time is the amount of time the sensitive photo diodes within the sensor absorb light before storing the Lux value. So another setting necessary for a dark room. On the flip side lower settings are required for outdoors where it's bright!

The SparkFun Ambient Light Sensor can detect ranges of light in Lux from zero to 120,796! That's a gigantic range from dark to direct sun in the middle of the day. To accomplish this you have to set the Gain and Integration Time settings. This is trivial with the Arduino Library we've written and we'll walk you through it below in Example1 Ambient Light Basics. With each setting gives you a range of light that you can read. Check out the table below to see what's capable at each possible setting. Notice that slower integration and higher gain gives you a smallest range of (0->236) but the highest resolution (0.0036 lux/bit).

The datasheet recommends that you use a setting of 1/4 (.25) or 1/8 (.125) unless the Ambient Light Sensor is going to sit behind dark glass. This will help to prevent over saturation of the photodiodes within the sensor.

Maximum Light Detection Range: Lux

Integration Time (milliseconds) GAIN 2 GAIN 1 GAIN 1/4 GAIN 1/8
800 236 472 1887 3775
400 472 944 3775 7550
200 944 1887 7550 15099
100 1887 3775 15099 30199
50 3775 7550 30199 60398
25 7550 15099 60398 120796

Resolution: Lux/Bit

Integration Time (milliseconds) GAIN 2 GAIN 1 GAIN 1/4 GAIN 1/8
800 0.0036 0.0072 0.0288 0.0576
400 0.0072 0.0144 0.0576 0.1152
200 0.0144 0.0288 0.1152 0.2304
100 0.0288 0.0576 0.2304 0.4608
50 0.0576 0.1152 0.4608 0.9216
25 0.1152 0.2304 0.9216 1.8432

Power Save Modes

Another cool feature of the SparkFun Ambient Light Sensor is its ability to run at extremely low currents. Power save modes should be used when you're continuously reading ambient light data. For example, if you're going to gather ambient light data every second, why not use a power save mode and save battery life? There are four power save modes that can be enabled with integration times of 100ms and above. Below is a table showing the power save mode, the current draw, and it's refresh rate. Check out Example 4 in the Arduino Library to see how to set it up and use the table below as a reference.

Note the Refresh Time is the time needed for a new reading to be ready. Make sure there is a delay in your code of at least this length between readings to ensure you're getting new data.
Integration Time Power Save Mode Refresh Time (milliseconds) Current Draw (microamperes) Resolution (lx/bit)
100 1 600 8 0.0288
100 2 1100 5 0.0288
100 3 2100 3 0.0288
100 4 4100 2 0.0288
200 1 700 13 0.0144
200 2 1200 8 0.0144
200 3 2200 5 0.0144
200 4 4200 3 0.0144
400 1 900 20 0.0072
400 2 1400 13 0.0072
400 3 2400 8 0.0072
400 4 4400 5 0.0072
800 1 1300 28 0.0036
800 2 1800 20 0.0036
800 3 2800 13 0.0036
800 4 4800 8 0.0036

Rounding Errors?!

Later on when you read back an interrupt threshold, you may notice that the interrupt lux values are off by one in some cases. This is because of the inherent rounding error with the Ambient Light Sensor. The final Lux value is calculated by multiplying the value of the bits that represent the ambient light by a decimal number (0.2304 for example). This decimal number is rounded to a whole number (e.g. 19.97 becomes 19) because the sensor does not care about fractions of a Lux. I chose to read back the rounded number because that's the interpreted value of the ambient light sensor and what is stored in its' registers.

Hardware Hookup

This will be an easy one thanks to the Qwiic connectors. Take one end of a Qwiic cable and plug it into your RedBoard Qwiic Board and then take the other end and plug it into the SparkFun Ambient Light Sensor.

This image shows a picture of the SparkFun Ambient Light Sensor connected to a Redboard Qwiic by a Qwiic cable.

Arduino Library

Note: This example below 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.

If you've never connected an CH340 device to your computer before, you may need to install drivers for the USB-to-serial converter. Check out our section on How to Install CH340 Drivers for help with the installation

We've written a library to make it even easier to get started with the SparkFun Ambient Light Sensor. The library will give you the full functionality of the sensor and provides example code to get the most our of your project. You can obtain these libraries through the Arduino Library Manager by searching SparkFun Ambient Light Sensor. The second option is to download the ZIP file below from its GitHub repository to manually install.

Example 1: Ambient Light Basics

In this first example, we'll get you comfortable with gathering ambient light and setting two vital properties of the sensor's ability to read light: the gain and the integration time. These two properties determine the resolution (accuracy) of the reading and the available ranges of light that you can read! For example, a gain of 1/8 and 800ms integration time cannot read anything above 3775 Lux. This means you'll max out your sensor outdoors but would be a proper setting for dim rooms due to it's higher resolution.

At the top of the example we have three variables gain, time, and luxval. The first two hold the value for the gain and integration time settings mentioned above. Gain settings can be: 2, 1, 1/4, and 1/8; typically 1/4 gain will capture everything you need with good resolution. Possible integration times can be 800, 400, 200, 100, 50, 25 and by default the sensor is set to 100; times are in milliseconds. Check the Gain and Integration Time table above under Hardware Overview to see maximum illumination capabilities and resolution for every setting.

If you have any doubt with which settings to pick, just keep the example code's default settings: a gain of 1/4 (0.125) and an integration time of 100ms. This will give you a range of up to 15,000 Lux with a decent resolution!

language:c
#include <Wire.h>
#include "SparkFun_VEML6030_Ambient_Light_Sensor.h"

#define AL_ADDR 0x48

SparkFun_Ambient_Light light(AL_ADDR);

// Possible values: .125(1/8), .25(1/4), 1, 2
// Both .125 and .25 should be used in most cases except darker rooms.
// A gain of 2 should only be used if the sensor will be covered by a dark
// glass.
float gain = .125;

// Possible integration times in milliseconds: 800, 400, 200, 100, 50, 25
// Higher times give higher resolutions and should be used in darker light. 
int time = 100
long luxVal = 0; 

In the setup, we call light.begin() to check if we can communicate with the SparkFun Ambient Light Sensor. Next, we call the light.setGain() and light.setIntegTime() functions giving them the variables holding the gain and time values above. Next we'll read back those values to make sure that they were set correctly. That's it! We're now set to read some light!

language:c
void setup(){

  Wire.begin();
  Serial.begin(115200);

  if(light.begin())
    Serial.println("Ready to sense some light!"); 
  else
    Serial.println("Could not communicate with the sensor!");

  // Again the gain and integration times determine the resolution of the lux
  // value, and give different ranges of possible light readings. Check out
  // hoookup guide for more info. 
  light.setGain(gain);
  light.setIntegTime(time);

  Serial.println("Reading settings..."); 
  Serial.print("Gain: ");
  float gainVal = light.readGain();
  Serial.print(gainVal, 3); 
  Serial.print(" Integration Time: ");
  int timeVal = light.readIntegTime();
  Serial.println(timeVal);

}

One thing to keep in mind is that you need to set a delay() in between readings. The Integration Time is the amount of time that the sensor uses to fill its' sensitive components with light. If you set an integration time of 100ms then make sure you're delay is at least that long. A longer integration time will need a longer delay.

language:c
void loop(){

  luxVal = light.readLight();
  Serial.print("Ambient Light Reading: ");
  Serial.print(luxVal);
  Serial.println(" Lux");  
  delay(1000);

}

Example 2 and 3: Ambient Light Interrupt

The SparkFun Ambient Light Sensor can issue an interrupt whenever the ambient light readings cross high or low thresholds. In this example, we'll talk about setting those thresholds and reading when those thresholds have been crossed in two different ways:

  • the on-board hardware interrupt pin labeled INT
  • through software monitoring

The code for both Example 2 and 3 only differ in the main loop() and these differences are highlighted under Example 2 - Hardware Interrupt and Example 3 - Software Interrupt sections below.

Again as in example one, at the top we see the gain, time and luxVal variables. The gain and integration times are vital for setting the tolerance for light and resolution of your sensor - see the Gain and Integration Time table under Hardware Overview above. The luxVal variable holds the ambient light readings further down in the code. Just below we see the interrupt settings lowThresh, highThresh and numbValues. The first two set the low and high threshold variables that will trigger the interrupt when the ambient light crosses the given values. The last variable is the number of times a value must cross a threshold to trigger an interrupt. I have the variables set to 20 Lux for the lower end, 400 Lux for the upper end, and that an interrupt must be issued after the ambient light crosses one of these thresholds once.

language:c
#include <Wire.h>
#include "SparkFun_VEML6030_Ambient_Light_Sensor.h"


// Close the address jumper on the product for addres 0x10.
#define AL_ADDR 0x48

SparkFun_Ambient_Light light(AL_ADDR);

// Possible values: .125, .25, 1, 2
// Both .125 and .25 should be used in most cases except darker rooms.
// A gain of 2 should only be used if the sensor will be covered by a dark
// glass.
float gain = .125;

// Possible integration times in milliseconds: 800, 400, 200, 100, 50, 25
// Higher times give higher resolutions and should be used in darker light. 
int time = 100;
long luxVal = 0; 


// Interrupt settings. 
long lowThresh = 20; 
long highThresh = 400; 
int numbValues = 1;

// Interrupt pin
int intPin = 3;
// -- OR -- if not using interrupt pin:
int interrupt;

Again, as in the first example, we start communication with the sensor with light.begin(), set the gain (light.setGain()) and integration time settings (light.setIntegTime()), and read them back by printing them out to the serial monitor with the respective read functions. But just below we see where we set the two thresholds. First the low threshold with light.setIntLowThresh() and then the high threshold with light.setIntHighThresh(), giving these functions the values we set in the variables above. We then read those settings back to make sure that they're set correctly.

Now we set how many values will need to cross the threshold with the light.setProtect() function call and read it back. This setting is optional and defaults to one. Finally, we enable the interrupt with light.enableInt(). While the sensor knows our thresholds it does not quite know we want the interrupt to be enabled until we tell it to.

language:c
void setup(){

  Wire.begin();
  Serial.begin(115200);
  pinMode(intPin, INPUT);

  if(light.begin())
    Serial.println("Ready to sense some light!"); 
  else
    Serial.println("Could not communicate with the sensor!");

  // Again the gain and integration times determine the resolution of the lux
  // value, and give different ranges of possible light readings. Check out
  // hoookup guide for more info. The gain/integration time also affects 
  // interrupt threshold settings so ALWAYS set gain and time first. 
  light.setGain(gain);
  light.setIntegTime(time);

  Serial.println("Reading settings..."); 
  Serial.print("Gain: ");
  float gainVal = light.readGain();
  Serial.print(gainVal, 3); 
  Serial.print(" Integration Time: ");
  int timeVal = light.readIntegTime();
  Serial.println(timeVal);

  // Set both low and high thresholds, they take values in lux.
  light.setIntLowThresh(lowThresh);
  light.setIntHighThresh(highThresh);
  // Let's check that they were set correctly. 
  // There are some rounding issues inherently in the IC's design so your lux
  // may be one off. 
  Serial.print("Low Threshold: ");
  long lowVal = light.readLowThresh();
  Serial.print(lowVal);
  Serial.print(" High Threshold: ");
  long highVal = light.readHighThresh();
  Serial.println(highVal);

  // This setting modifies the number of times a value has to fall below or
  // above the threshold before the interrupt fires! Values include 1, 2, 4 and
  // 8. 
  light.setProtect(numbValues);
  Serial.print("Number of values that must fall below/above threshold before interrupt occurrs: ");
  int protectVal = light.readProtect();
  Serial.println(protectVal);

  // Now we enable the interrupt, now that he thresholds are set. 
  light.enableInt();
  Serial.print("Is interrupt enabled: ");
  int enabInt = light.readIntSetting();
  if( enabInt == 1 )
    Serial.println("Yes"); 
  else
    Serial.println("No");

  Serial.println("-------------------------------------------------");

  // Give some time to read our settings on startup.
  delay(3000);
}

Example 2: Hardware Interrupt

Now let's read some light! Since we're just using a hardware interrupt we have a pin attached to PIN 3. When the ambient light reading passes either threshold the pin will go LOW. When an interrupt fires we check to see which threshold was crossed and print it out in the serial monitor.

language:c 
void loop(){

  luxVal = light.readLight();
  Serial.print("Ambient Light Reading: ");
  Serial.print(luxVal);
  Serial.println(" Lux");  

  if (digitalRead(intPin) == LOW){
    int intVal = light.readInterrupt();
    if (intVal == 1)
      Serial.println("High threshold crossed!");
    else if (intVal == 2){
      Serial.println("Low threshold crossed!");
    }
  }

  delay(200);

Example 3: Software Interrupt

If you're committed to keeping this Qwiic then we can look for an interrupt by monitoring the Ambient Light Sensor directly rather than through a digital pin. In the code we'll use the light.readInterrupt() function call directly to see if there's been an interrupt issued. That's it!

language:c
void loop(){

  luxVal = light.readLight();
  Serial.print("Ambient Light Reading: ");
  Serial.print(luxVal);
  Serial.println(" Lux");  

  interrupt = light.readInterrupt();
  if (interrupt == 1)
    Serial.println("High threshold crossed!");
  else if (interrupt == 2){
    Serial.println("Low threshold crossed!");

  delay(200);

}

Example 4 - Power Save Mode

I won't break down this example code because you have all the necessary tools to get you started with the Ambient Light Sensor. However, if you plan on continuously reading ambient light data then give this sketch a try. It'll show you how to put the board into power save mode, which will save you battery life while still getting ambient light data. Check the Power Save Mode section under Hardware Overview as a reference when looking at the sketch.

Resources and Going Further

For more on the AS3935, check out the links below:

Need some other weather sensing parts for your project? Check out some of the ones listed below.

Weather Meters

Weather Meters

SEN-08942
$76.95
26
SparkFun Environmental Combo Breakout - CCS811/BME280 (Qwiic)

SparkFun Environmental Combo Breakout - CCS811/BME280 (Qwiic)

SEN-14348
$35.95
12
SparkFun Pressure Sensor Breakout - MS5803-14BA

SparkFun Pressure Sensor Breakout - MS5803-14BA

SEN-12909
$59.95
7
SparkFun Weather Shield

SparkFun Weather Shield

DEV-13956
$39.95
4

Need some inspiration for your next project? Check out some of these related tutorials to sense your environment!

Creating a Humidor Control Box

Because some of our boards need to be re-humidified after reflow, we decided to make our own humidor. This tutorial will focus on how to model a project in 3D and then fabricate it using a CNC routing machine.

T5403 Barometric Pressure Sensor Hookup Guide

T5403 Barometric Pressure Sensor Hookup Guide

ML8511 UV Sensor Hookup Guide

Get up and running quickly with this simple to use UV sensor.

Weather Meter Hookup Guide

How to assemble your very own weather meter!

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

LilyPad RGB LED Hookup Guide

$
0
0

LilyPad RGB LED Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The LilyPad RGB LED is a specialty board that can produce a variety of colors. On the board is an RGB (red-green-blue) LED, made of three tiny LEDs connected together. Each of the colors in the RGB LED are connected to one of the sew tabs on the board labeled R, G, and B.

LilyPad RGB LED

LilyPad RGB LED

DEV-13735
$3.50

Required Materials

To follow along with the code examples, we recommend:

Suggested Reading

To add this LED to a project, you should be comfortable sewing with conductive thread and uploading code to your LilyPad Arduino (for the programming examples). Here are some tutorials to review before working with this part:

What is a Circuit?

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

Light

Light is a useful tool for the electrical engineer. Understanding how light relates to electronics is a fundamental skill for many projects.

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.

Getting Started with LilyPad

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

The color channels on this RGB LED are all connected through a common cathode (negative) pin. This configuration means that the individual red, green, and blue LEDs share a common ground tab. To light up each color individual LED, connect them each to a power source. For simple circuit hookups, this means you need to connect the R, G, or B sew tabs to power (+) and in code set them to HIGH (for digital output) or 255 (for analog output) to turn them on.

Common Anode RGB LED LilyPad Breakout Board


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

Using in a Simple E-Sewing Project

The RGB LED doesn't need to be connected to a microcontroller in order to control it. Here are some examples of using simple circuits to mix colors with the LED.

To experiment with basic color mixing, you can use alligator clips on the RGB LED's sew tabs to temporarily connect them to a power source, such as a LilyPad Coin Cell Battery Holder with a coin cell battery. Connect the negative tab (-) to the negative sew tab on the battery holder with a clip, and each color tab R (Red), G (Green), and B (Blue) to the postivie tab (+) to connect them. The combination of color sew tabs that are connected to power will create a variety of colors.

LilyPad RGB LED connected to three alligator clips and a LilyPad Battery Holder

You can replace these connections with switches or buttons for a simple color mixing circuit. After prototyping and testing a project with the RGB LED, you can replace the connections with conductive thread in your project.

RGB LED stitched with conductive thread to three LilyPad Switches and a LilyPad Battery Holder

Simple color mixing circuit using a LilyPad Switches connected to each color tab of the RGB LED.

Attaching to a LilyPad Arduino

To follow along with the code examples in this tutorial, connect the RGB LED to a LilyPad Arduino as shown below. Use alligator clips to temporarily connect the R (Red) tab on the LED to 11, G (Green) to 10, B (Blue) to 9, and (-) to (-). When you are finished prototyping, replace the alligator clips with conductive thread traces for permanent installation in your project.

Note: To follow along with the Custom Color Mixing example code, you will need to attach the R, G, and B tabs to a sew tabs on the LilyPad with PWM capabilities. In this case, we are using a LilyPad Arduino USB with an ATmega32U4.

Attaching the RGB LED to a LilyPad Arduino USB

Additional Board Hookup

If you'd like to use RGB LED with the LilyPad ProtoSnap Plus, attach the R, G, and B tabs to the ProtoSnap's expansion ports. You will not be able to follow along with the Custom Color Mixing example unless you snap the ProtoSnap Plus apart and connect the RGB LED directly to tabs on the LilyPad USB Plus on pin 6, A7, and A8. Make sure to adjust the pins definitions in the example code when using the LilyPad ProtoSnap Plus.

Basic Color Mixing with 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.

This example code demonstrates how to display a simple rainbow of colors using the RGB LED. In order to create colors with the RGB LED, you'll have to set each of the LEDs within it individually. The combination of light from the LEDs mixed together creates new colors.

Upload the following code to your LilyPad Arduino, making sure to select the correct LilyPad board from the drop down menu below. Choose LilyPad Arduino USB if using a LilyPad Arduino USB. The LilyPad Arduino Simple, LilyPad Arduino, and LilyPad Development Board, and Development Board Simple all use a LilyPad ATmega 328. Select LilyPad USB Plus if following along with the LilyPad ProtoSnap Plus.

Copy and paste the following code into the Arduino IDE and upload it to your LilyPad Arduino.

language:c
/*
  LilyPad Tri-Color LED: Basic Color Mixing
  Written by: Gella and Ho Yun "Bobby" Chan
  SparkFun Electronics
  https://www.sparkfun.com/products/13735

  Create primary and secondary colors on the tri-color (Red/Green/Blue)
  LED connected to a LilyPad Arduino.

  Tri-Color LED connections:
  R pin to 11
  G pin to 10
  B pin to 9
  - pin to -


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

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

// This example uses a tri-color, also known as an RGB
// (Red / Green / Blue) LED.
// This example uses digitalWrite() to turn the three LEDs on and off
// in various combinations to create eight primary and secondary colors.

//debug mode, comment one of these lines out using a syntax for a single line comment: //
#define DEBUG 0     //0 = LEDs only
//#define DEBUG 1     //1 = LEDs w/ serial output

// Create integer variables for our LED pins:
#define RGB_red 11
#define RGB_green 10
#define RGB_blue 9

void setup() {

  // Make all of our LED pins outputs:
  pinMode(RGB_red, OUTPUT);
  pinMode(RGB_green, OUTPUT);
  pinMode(RGB_blue, OUTPUT);

#if DEBUG
  Serial.begin(9600); //initialize Serial Monitor
  //while (!Serial);  // Comment out to wait for serial port to connect to Serial Monitor. Needed for native USB.
  Serial.println("Basic Color Mixing w/ a Common Cathode RGB LED");
#endif

}//end setup()

void loop() {

  // This code will step through the six primary and secondary colors, plus white and black.
  // Note: for this particular LED, the wiring shares a common anode (+), which means to
  // turn on the LEDs you will set them LOW instead of HIGH.
  // Keep this in mind as you prototype with the LED and mix your colors.

  // For each of these colors, we'll turn the necessary RGB LEDs on or off.


  // Black (all LEDs off)
  // RGB LEDs:
#if DEBUG
  Serial.println("OFF");
#endif
  digitalWrite(RGB_red, LOW);
  digitalWrite(RGB_green, LOW);
  digitalWrite(RGB_blue, LOW);
  delay(1000);

  // Red (red LED on)
#if DEBUG
  Serial.println("RED");
#endif
  digitalWrite(RGB_red, HIGH);
  digitalWrite(RGB_green, LOW);
  digitalWrite(RGB_blue, LOW);
  delay(1000);

  //Yellow (red and green LEDs on)
#if DEBUG
  Serial.println("YELLOW");
#endif
  digitalWrite(RGB_red, HIGH);
  digitalWrite(RGB_green, HIGH);
  digitalWrite(RGB_blue, LOW);
  delay(1000);

  // Green (green LED on)
#if DEBUG
  Serial.println("GREEN");
#endif
  digitalWrite(RGB_red, LOW);
  digitalWrite(RGB_green, HIGH);
  digitalWrite(RGB_blue, LOW);
  delay(1000);

  // Cyan (blue and green LEDs on)
#if DEBUG
  Serial.println("CYAN");
#endif
  digitalWrite(RGB_red, LOW);
  digitalWrite(RGB_green, HIGH);
  digitalWrite(RGB_blue, HIGH);
  delay(1000);

  // Blue (blue LED on)
#if DEBUG
  Serial.println("BLUE");
#endif
  digitalWrite(RGB_red, LOW);
  digitalWrite(RGB_green, LOW);
  digitalWrite(RGB_blue, HIGH);
  delay(1000);

  // Magenta (red and blue LEDs on)
#if DEBUG
  Serial.println("MAGENTA");
#endif
  digitalWrite(RGB_red, HIGH);
  digitalWrite(RGB_green, LOW);
  digitalWrite(RGB_blue, HIGH);
  delay(1000);

  // White (all LEDs on)
#if DEBUG
  Serial.println("WHITE");
#endif
  digitalWrite(RGB_red, HIGH);
  digitalWrite(RGB_green, HIGH);
  digitalWrite(RGB_blue, HIGH);
  delay(1000);

}//end loop

After uploading your code, the RGB LED will step through a color sequence beginning with all LEDs off ('black'), red, yellow, green, cyan, blue, magenta, and white. Once the color sequence is complete, the program will loop back to the beginning and repeat the sequence.

Turning on different combinations of three LEDs inside the RGB LED will create new colors. Combining the primary colors of light (red, green, and blue) gives different results than combining pigments in paints or inks. Turning on all three colors will create white - this is called additive color. Take a look a the graphic below to see what colors combine to create primary and secondary colors with light.

Venn Diagram for Additive Colors

Custom Color Mixing with Code

In this example, you will but use analogWrite() function to change the brightness of each channel in relation to each other. Adjusting the brightness of the red, green, and blue LEDs within the LED will allow you to create a new range of values and color combinations. You will need to confirm that the sew tabs you connect to the RGB LED have PWM capabilities - this code will run on a LilyPad Arduino USB, LilyPad Arduino Simple, LilyPad Arduino SimpleSnap, and LilyPad Main board without any changes needed.

In the last example, you created basic primary and secondary colors by turning the red, green, and blue channels on or off with different combinations. In this activity, you'll create tertiary colors by combining the three color channels at 50% brightness levels. There are actually millions of color combinations available using RGB LEDs once you begin experimenting by adjusting the brightness/saturation of each channel. This example will cover a set of twelve tertiary colors and white.

Copy and paste the following code into the Arduino IDE and upload to your LilyPad Arduino.

language:c
/*
  LilyPad RGB LED: Custom Color Mixing
  Written by: Gella and Ho Yun "Bobby" Chan
  SparkFun Electronics
  https://www.sparkfun.com/products/13735

  Expand your color options using analogWrite and the LilyPad RGB LED

  RGB LED connections:
  R pin to 11
  G pin to 10
  B pin to 9
  - pin to -

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

******************************************************************************/
// In this example we'll use analogWrite to control the brightness of the three channels
// of the RGB LED.
// Here we'll create a rainbow of tertiary colors by adding a 50%-brightness option.

//debug mode, comment one of these lines out using a syntax for a single line comment: //
//#define DEBUG 0     //0 = LEDs only
#define DEBUG 1     //1 = LEDs w/ serial output

// Create integer variables for our LED pins:
#define RGB_red 11
#define RGB_green 10
#define RGB_blue 9

void setup() {

  // Make all of our LED pins outputs:
  pinMode(RGB_red, OUTPUT);
  pinMode(RGB_green, OUTPUT);
  pinMode(RGB_blue, OUTPUT);

#if DEBUG
  Serial.begin(9600); //initialize Serial Monitor
  //while (!Serial); // Comment out to wait for serial port to connect to Serial Monitor. Needed for native USB.
  Serial.println("Custom Color Mixing w/ a Common Cathode RGB LED");
#endif

}//end setup()

void loop()
{
  // In this code we'll step through twelve rainbow colors (primary, secondary, tertiary).

  // Unlike digitalWrite, which can be only HIGH (on) or LOW (off),
  // analogWrite lets you smoothly change the brightness from 0 (off) to 255 (fully on).
  // When analogWrite is used with the RGB LED, you can create millions of colors!

  // In the analogWrite() functions:
  // 0 is off
  // 128 is halfway on (used for the tertiary colors)
  // 255 is full brightness.

  // Black (all LEDs off)
  // RGB LEDs:
#if DEBUG
  Serial.println("OFF");
#endif
  analogWrite(RGB_red, 0);
  analogWrite(RGB_green, 0);
  analogWrite(RGB_blue, 0);
  delay(1000);

  // Red
#if DEBUG
  Serial.println("RED");
#endif
  analogWrite(RGB_red, 255);
  analogWrite(RGB_green, 0);
  analogWrite(RGB_blue, 0);
  delay(1000);

  // Orange
#if DEBUG
  Serial.println("ORANGE");
#endif
  analogWrite(RGB_red, 255);
  analogWrite(RGB_green, 128);
  analogWrite(RGB_blue, 0);
  delay(1000);

  // Yellow
#if DEBUG
  Serial.println("YELLOW");
#endif
  analogWrite(RGB_red, 255);
  analogWrite(RGB_green, 255);
  analogWrite(RGB_blue, 0);
  delay(1000);

  // Chartruese
#if DEBUG
  Serial.println("CHARTRUESE");
#endif
  analogWrite(RGB_red, 128);
  analogWrite(RGB_green, 255);
  analogWrite(RGB_blue, 0);
  delay(1000);

  // Green
#if DEBUG
  Serial.println("GREEN");
#endif
  analogWrite(RGB_red, 0);
  analogWrite(RGB_green, 255);
  analogWrite(RGB_blue, 0);
  delay(1000);

  // Spring Green
#if DEBUG
  Serial.println("SPRING GREEN");
#endif
  analogWrite(RGB_red, 0);
  analogWrite(RGB_green, 255);
  analogWrite(RGB_blue, 128);
  delay(1000);

  // Cyan
#if DEBUG
  Serial.println("CYAN");
#endif
  analogWrite(RGB_red, 0);
  analogWrite(RGB_green, 255);
  analogWrite(RGB_blue, 255);
  delay(1000);

  // Azure
#if DEBUG
  Serial.println("AZURE");
#endif
  analogWrite(RGB_red, 0);
  analogWrite(RGB_green, 128);
  analogWrite(RGB_blue, 255);
  delay(1000);

  // Blue
#if DEBUG
  Serial.println("BLUE");
#endif
  analogWrite(RGB_red, 0);
  analogWrite(RGB_green, 0);
  analogWrite(RGB_blue, 255);
  delay(1000);

  // Violet
#if DEBUG
  Serial.println("VIOLET");
#endif
  analogWrite(RGB_red, 128);
  analogWrite(RGB_green, 0);
  analogWrite(RGB_blue, 255);
  delay(1000);

  // Magenta
#if DEBUG
  Serial.println("MAGENTA");
#endif
  analogWrite(RGB_red, 255);
  analogWrite(RGB_green, 0);
  analogWrite(RGB_blue, 255);
  delay(1000);

  // Rose
#if DEBUG
  Serial.println("ROSE");
#endif
  analogWrite(RGB_red, 255);
  analogWrite(RGB_green, 0);
  analogWrite(RGB_blue, 128);
  delay(1000);

  // White (all LEDs on)
#if DEBUG
  Serial.println("ALL ON, WHITE");
#endif
  analogWrite(RGB_red, 255);
  analogWrite(RGB_green, 255);
  analogWrite(RGB_blue, 255);
  delay(1000);
}//end loop

After uploading your code the RGB LED will step through a rainbow sequence of red, orange, yellow, chartruese, green, spring green, cyan, azure, blue, violet, magenta, rose, and white repeatedly.

By adjusting the brightness of each LED in the RGB LED individually, we open up a much wider range of color options to display than the previous example. In fact, there are many more combinations than we show in the example code. The image below shows a chart of the tertiary colors the example program creates by stepping down the LEDs to half brightness, creating a rainbow with more color transitions than the Basic Color Mixing example. By using analog output to adjust the brightness of each color channel individually, the RGB LED can display almost any color you can choose from a color picker - if you are familiar with RGB sliders in a graphics program, you'll recognize the 0-255 values used in this code.

Tertiary Color Wheel Chart

Project Examples

Need some inspiration for your next project? Check out some of the projects below. Just make sure to adjust the connections when using the common cathode RGB LED.

Light Up Silk Flower Corsage

This tutorial uses a specialty Silk Flower LED with embedded RGB LED in it, but functions similar to the example circuit above. You can create a similar project using an RGB LED and your own flower or fabric covering.

Light Up Silk Flower Corsage

April 20, 2015

Combine a silk flower with a built-in RGB LED and some LilyPad Switches to create a customizable accessory.

Color Changing LED Brooch by Becky Stern

In this project for Craftzine, Becky uses three potentiometers to make a customizable colored LED brooch using the RGB LED.



Skirt Full of Stars by Shannon Henry

This skirt reacts to movement and displays in color with RGB LEDs and fiber optic strands. It uses a LilyPad Accelerometer connected to a LilyPad Arduino Main Board to sense movement while being worn.

Skirt Full of Stars project by Shannon Henry

Photo courtesy of PolyMath Design Lab

Resources and Going Further

Now that you've successfully got your LilyPad Tri-Color LED up and running, it's time to incorporate it into your own project! For more information about the LilyPad Tri-Color LED, check out the resources below:

Check out these other tutorials using RGB LEDs:

Hackers in Residence - Sound and Motion Reactivity for Wearables

How to consciously wear light-up and and sound reactive clothing.

Humidity-sensing LED Flower

How about that humidity? This tutorial shows how to add sensing capability to the 21st Century Fashion Kit's RGB flower project.

Light Up Silk Flower Corsage

Combine a silk flower with a built-in RGB LED and some LilyPad Switches to create a customizable accessory.

LED Cloud-Connected Cloud

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

Learn more about working with LilyPad LEDs in your projects:

LilyPad Pixel Board Hookup Guide

Add changing colors to your wearable projects using LilyPad Pixel Boards.

Powering LilyPad LED Projects

Learn how to calculate how many LEDs your LilyPad project can power and how long it will last.

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

PCA9306 Logic Level Translator Hookup Guide (v2)

$
0
0

PCA9306 Logic Level Translator Hookup Guide (v2) a learn.sparkfun.com tutorial

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

Introduction

Heads up! This is for the PCA9306 breakout v2. If you are using the previous PCA9306, you'll want to head over to the older tutorial. The package used on the PCA9306 breakout v2 is different from the PCA9306 breakout v1.

The PCA9306 is a dual bi-directional voltage translator for the I2C-bus and SMBus. It works at a range of voltages between 1.0 and 5.0V and doesn't require a direction pin to function. This is a great board for shifting voltages between sensors and your microcontroller.

SparkFun Level Translator Breakout - PCA9306

SparkFun Level Translator Breakout - PCA9306

BOB-15439
$3.95

Required Materials

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

Arduino Uno - R3

Arduino Uno - R3

DEV-11021
$22.95
126
Break Away Headers - Straight

Break Away Headers - Straight

PRT-00116
$1.50
20
USB Cable A to B - 6 Foot

USB Cable A to B - 6 Foot

CAB-00512
$3.95
1
SparkFun Triple Axis Accelerometer Breakout - MMA8452Q

SparkFun Triple Axis Accelerometer Breakout - MMA8452Q

SEN-12756
$9.95
8
Breadboard - Mini Modular (White)

Breadboard - Mini Modular (White)

PRT-12043
$3.95
Jumper Wires Premium 4" M/M - 26 AWG (30 Pack)

Jumper Wires Premium 4" M/M - 26 AWG (30 Pack)

PRT-14284
$1.95

Tools

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

Soldering Iron - 60W (Adjustable Temperature)

Soldering Iron - 60W (Adjustable Temperature)

TOL-14456
$14.95
7
Solder Lead Free - 15-gram Tube

Solder Lead Free - 15-gram Tube

TOL-09163
$3.50
2

Suggested Reading

These level converters are pretty easy to start using, but you may want to check out some of the additional reading material below if you are unfamiliar with logic level shifting or haven't worked with Arduino boards prior to this.

How to Solder: Through-Hole Soldering

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

What is an Arduino?

What is this 'Arduino' thing anyway?

Logic Levels

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

I2C

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

Hardware Overview

Power and I2C Sides

At a minimum, the breakout board has seven pins that need to be connected to function properly. VREF1, SCL1, and SDA1 all connect to your lower voltage side.

Low Side Pins

VREF2, SCL2, and SDA2 connect to your higher voltage side. One of the GND pins on either side needs to be connected to ground in your system.

High Side Pins

What's that extra through-hole on the board labeled as EN? Well, it can be connected to an I/O pin to toggle the PC9306 from the high side. You'll need to adjust the jumper in the back to be able to use this feature. Check below for more information.

Allowable Voltage Level Translation

For most of the products listed in the catalog, usually you will be translating voltages between 3.3V and 5V. However, the datasheet for the PCA9306 states that it can be used to translate lower voltages if you need. Below are the acceptable voltages on the low and high sides.

VREF1 (i.e. Low Side)VREF2 (i.e. High Side)
1.2V1.8, 2.5V, 3.3V, 5V
1.8V2.5V, 3.3V, 5V
2.5V3.3V, 5V
3.3V5V

Jumpers

There is a jumpers on the underside of this board to turn on and off the PCA9306. By cutting the trace and adding a solder jumper toward the pad labeled as "Switch," you can toggle the logic level translator with your microcontroller.

Enable Jumper

Enable Feature

It's possible to use the PCA9306 as an I²C switch. First, as mentioned above, you'll want to cut the ON trace and solder the Switch trace. To use the feature you'll attach the high side VREF2 to you're high side voltage as you normally would, and then attach the EN (enable) pin, to a digital Pin. Now when you want to enable I²C communication, pull the line HIGH.

Hardware Assembly

To connect the board, you will need to solder headers into the through-holes, and use jumper wires to connect between devices when prototyping. Make sure to place it on a breadboard before soldering to test. You will need to make sure that the headers on each side of the PCA9306 breakout board are soldered at an angle in order for it to sit securely on a breadboard. The board shown at the top of the image shows how the pins are offset and soldered at a small angle. The board shown at the bottom of the image shows pins flush with the board. You will want to make sure that you soldered the pins like the board shown at the top of the image.

Offset Headers

You could also just solder some hookup wire or add a protoshield to connect all of your boards together securely for a project.

Hardware Hookup

For this example, we are going to use an Arduino Uno to connect to an MMA8452 accelerometer breakout board, which runs at 3.3V and communicates over I2C.

3.3V Device (i.e. MMA8452)PCA9306 (Low Side)PCA9306 (High Side)5V Device (i.e. Arduino Uno w/ ATmega328P)
3.3VVREF13.3V
VREF25V
SCLSCL1SCL2A5
SDASDA1SDA2A4
GNDGNDGNDGND
ENAny I/O Pin If Jumper is Adjusted

Here is a Fritizing diagram showing the actual connections between the MMA8452, the PCA9306 breakout and the Arduino Uno.

Fritzing Diagram of hookups

You'll need to connect power for the Arduino via the barrel jack, VIN, or USB connector. In this case, we'll simply use power from the USB cable to provide 5V to the high side. The diagram shows the MMA8452 running off the Arduino Uno's 3.3V rail. Keep in mind your power supplies could be different, but you will still need to have a power supply for the lower voltage side of the system and a separate supply for the higher voltage side.

Once you have the boards physically connected, you are good to go! You don't need to use any special code with the PCA9306 board, and you can simply use any example sketch available for your sensors. In this case, we are using the example MMA8452 from the hookup guide. Head over to the tutorial to finishing programing your Arduino to start using the accelerometer!

MMA8452Q Accelerometer Breakout Hookup Guide

June 11, 2014

How to get started using the MMA8452Q 3-axis accelerometer -- a solid, digital, easy-to-use acceleration sensor.

Resources and Going Further

Now that you know how to use the logic level shifter, it's time to go and use this in your own project! Check out the additional resources below if you have any questions, or leave us feedback on the tutorial itself. Best of luck interfacing with all of your sensors!

Looking to shift the logic levels for a different sensor with the Arduino? Try modifying a Qwiic cable before shifting the logic levels of your I2C device for a Qwiic enabled product.

Pioneer IoT Add-On Shield

Pioneer IoT Add-On Shield

DEV-14531
$19.95
1
SparkFun Differential I2C Breakout - PCA9615 (Qwiic)

SparkFun Differential I2C Breakout - PCA9615 (Qwiic)

BOB-14589
$10.95
6
SparkFun Grid-EYE Infrared Array Breakout - AMG8833 (Qwiic)

SparkFun Grid-EYE Infrared Array Breakout - AMG8833 (Qwiic)

SEN-14607
$40.95
SparkFun Advanced Autonomous Kit for Sphero RVR

SparkFun Advanced Autonomous Kit for Sphero RVR

KIT-15303
$164.95

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

SparkFun AS3935 Lightning Detector Hookup Guide (v20)

$
0
0

SparkFun AS3935 Lightning Detector Hookup Guide (v20) a learn.sparkfun.com tutorial

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

Introduction

Note: This tutorial was written for v20 of the AS3935 lightning detector. For information on the previous version of the hookup guide, you will need to head over to the older tutorial.

The SparkFun AS3935 Lightning Detector adds lightning detection to your next weather station or to your next bike ride. Are you worried about the looming clouds in the distance, how far away is that storm exactly? The lightning detector can tell you the distance to the front of the storm 40 km away with an accuracy of 1km. It has false positive rejection and comes with many configurable features. To get at those features we have written a library that gives you access to settings such as storm sensing sensitivity, when detecting indoors vs outdoors, or the number of lightning strikes needed to trigger an interrupt! Revision 2.0 of the board is SPI only*, with the caveat that if you wanted to use I²C, all the parts are there but it is NOT supported by SparkFun.

SparkFun Lightning Detector - AS3935

SparkFun Lightning Detector - AS3935

SEN-15441
$24.95

Required Materials

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

Break Away Headers - Straight

Break Away Headers - Straight

PRT-00116
$1.50
20
SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

DEV-15123
$19.95
1
Jumper Wires - Connected 6" (M/F, 20 pack)

Jumper Wires - Connected 6" (M/F, 20 pack)

PRT-12794
$1.95
USB micro-B Cable - 6 Foot

USB micro-B Cable - 6 Foot

CAB-10215
$4.95
12

Tools

Depending on your setup, you will may need a soldering iron, solder, and general soldering accessories.

Soldering Iron - 60W (Adjustable Temperature)

Soldering Iron - 60W (Adjustable Temperature)

TOL-14456
$14.95
7
Solder Lead Free - 15-gram Tube

Solder Lead Free - 15-gram Tube

TOL-09163
$3.50
2

Suggested Reading

We would also recommend taking a look at the following tutorials if you aren't familiar with them.

Serial Peripheral Interface (SPI)

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

I2C

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

How to Work with Jumper Pads and PCB Traces

Handling PCB jumper pads and traces is an essential skill. Learn how to cut a PCB trace, add a solder jumper between pads to reroute connections, and repair a trace with the green wire method if a trace is damaged.

RedBoard Qwiic Hookup Guide

This tutorial covers the basic functionality of the RedBoard Qwiic. This tutorial also covers how to get started blinking an LED and using the Qwiic system.

Hardware Overview

Power

You can provide 3.3V through the through hole labeled 3V3 on the header along the side of the product. When the board is powered, the on board red power LED will turn on.

This image shows a picture of the product with the leftmost through holes labeled for ground and 3.3V highlighted.

LED

There is one LED on the product and it will turn on when power is supplied to the board. You can disconnect this LED by cutting the jumper on the underside of the product labeled LED.

This image shows a picture of the product with the power LED (only LED) on the board highlighted.

SPI

The SPI data pins on the header along the edge of the board are labeled with the respective functions necessary for using SPI: MOSI, MISO, CS, and SCK. We'll walk through how to use these pins in the example code below with Example 1-Lightning Basics.

This pictures shows a picture of the product with the SPI data through holes highlighted. Those include: MOSI, MISO, CS, and SCK.

Interrupt Pin

The interrupt pin goes HIGH when the lightning detector has sensed an event, whether it's lightning, a disturber, or noise. Make sure to connect to this pin to check if there is an event detected.

This image shows a picture of the interrupt pin on the product highlighted.

Antenna

The largest part on the SparkFun Lightning Detector is lightning antenna. Keep the area around the antenna free for optimal lightning detection.

This image shows a picture of the top of the product with the large antenna on the right hand side highlighted.

Jumpers

There are four jumpers on this product all on its underside. Starting at the lower left is the triple pull-up jumper labeled I2C PU, used for the I²C data lines (check section: A note on I²C below). If you have many I²C devices chained together, you will need to leave these jumpers open.

This image shows the bottom of the product with the lower left most trip jumper highlighted.

Next to the I2C PU jumper are two address jumpers labeled ADR that allow you to change the SparkFun Lightning Detector's I²C address. The default I²C address is 0x03 but it can be changed to two other addresses: 0x02, 0x01.

This image shows the bottom of the product with the jumper next to right of the pull up jumper highlighted.

In the upper right is the power LED disconnect jumper; cut this to disconnect the red power LED.

This image shows the bottom of the product but with the power LED disconnect jumper highlighted in the upper right hand side.

Finally towards the top is the I²C jumper which does two things: grounds the CS pin and enables I²C. SparkFun does not support I²C on this particular product (check section: A note on I²C below).

This image shows the bottom of the product with the I squared C enable jumper in the center top portion of the product highlighted.

A Note on I²C

The SparkFun Lightning Detector's original design supported I²C but there were issues raised by a small percentage of customers who purchased this product with regards to its' reliability. This issue was followed up with an investigation by our engineers and unfortunately, we decided we could not support it officially. However, if you want to use it, all of the goods are there. Just know SparkFun won't be supporting problems that may arise with its' use.

To enable I²C: close the CS side of the I2C EN jumper and cut the SI side. Then close the right side of the I2C PU jumper. See jumpers above for pictures. You'll have to dig into the datasheet to see which lines are the I²C data lines. Happy Hacking!

False Positives and Noise

There are a number of sources that can cause false positives but the lightning detector itself can reliably filter these out by default. If not, there are a number of settings you can configure easily with SparFun's Lightning Detector library to increase the chip's robustness to noise and false positives (see Example2 More Lightning Features SPI). However, it can help to know some potential sources of noise: fluorescent lighting, microwave ovens, smartphone and smartwatch displays, DC-DC converters, refrigerators, and/or things that can switch large voltages in general.

Hardware Assembly

For this you'll have to solderbreak away headers to the header on the SparkFun Lightning Detector. After plugging that into your breadboard, you'll wire the RedBoard Qwiic to the Lightning Detector with the following order.

RedBoard Qwiic (Set to 3.3V Logic) SparkFun Lightning Detector
3.3V 3.3V
GNDGND
13 SCK
12 MISO
11 MOSI
10 CS
4 INT

Lightning Detector Hookup Fritzing

Arduino Library Installation

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

If you've never connected an CH340 device to your computer before, you may need to install drivers for the USB-to-serial converter. Check out our section on How to Install CH340 Drivers for help with the installation.

We've provided a library for the SparkFun Lightning Detector that configures every available setting the IC offers. Some of the features include modifying the sensitivity of the antenna, whether you're inside or outside, fine tuning when the IC triggers an interrupt, or modifying the resonance frequency of the antenna. You can search the Arduino Library Manager for "SparkFun Lightning Detector", or you can click the button below to get the library and install it manually. Finally, you can also download it manually from the GitHub Repo.

Example 1 - Basic Lightning SPI

The example below will start with the basic functionality in Example1_BasicLightning_SPI.ino. Open the example up to follow along.

Example 1 - Basic Lightning SPI

At the very top, we have a few defines that will help us to distinguish what sort of event the SparkFun Lightning Detector has sensed. There are three possible "events". The first of course is lightning, but we may also get a false lightning event called a disturber, and finally we may hear noise. Also of note are the noise and disturber variables. We'll talk about those farther down in the main loop.

language:c
#include <SPI.h>
#include <Wire.h>
#include "SparkFun_AS3935.h"

#define INDOOR 0x12 
#define OUTDOOR 0xE
#define LIGHTNING_INT 0x08
#define DISTURBER_INT 0x04
#define NOISE_INT 0x01

SparkFun_AS3935 lightning;

// Interrupt pin for lightning detection 
const int lightningInt = 4; 
int spiCS = 10; //SPI chip select pin

// This variable holds the number representing the lightning or non-lightning
// event issued by the lightning detector. 
int intVal = 0;
int noise = 2; // Value between 1-7 
int disturber = 2; // Value between 1-10

By default the SparkFun Lightning Detector is set to be run inside because I'm assuming you're at your computer running this code. If you're outside change the parameter to OUTDOOR.

language:c
void setup()
{
  // When lightning is detected the interrupt pin goes HIGH.
  pinMode(lightningInt, INPUT); 

  Serial.begin(115200); 
  Serial.println("AS3935 Franklin Lightning Detector"); 

  SPI.begin(); 

  if( !lightning.beginSPI(spiCS, 2000000) ){ 
    Serial.println ("Lightning Detector did not start up, freezing!"); 
    while(1); 
  }
  else
    Serial.println("Schmow-ZoW, Lightning Detector Ready!");

  // The lightning detector defaults to an indoor setting at 
  // the cost of less sensitivity, if you plan on using this outdoors 
  // uncomment the following line:
  //lightning.setIndoorOutdoor(OUTDOOR); 
}

In the main loop the interrupt pin is monitored for a lightning event from the Lightning Detector. If the interrupt pin goes HIGH we check whether this event is lightning, a disturber, or noise with the lightning.readInterruptReg() function call. Each of these events are printed out in the serial window at 115200 baud. If lightning is detected, then we check the distance to the storm with lightning.distanceToStorm() and print that out to the window. There are two other possibilities: noise and disturber. If you see a lot of noise or disturbers check the section False Positives and Noise above to help guide you to reduce the noise in your environment. We can also increase the SparkFun Lightning Detector's robustness to noise with the lightning.setNoiseLevel() function call. Likewise we can increase the SparkFun Lightning Detector's resistance to false lightning events with lightning.watchdogThreshold().

language:c
void loop()
{
   // Hardware has alerted us to an event, now we read the interrupt register
  if(digitalRead(lightningInt) == HIGH){
    intVal = lightning.readInterruptReg();
    if(intVal == NOISE_INT){
      Serial.println("Noise."); 
      // Too much noise? Uncomment the code below, a higher number means better
      // noise rejection.
      //lightning.setNoiseLevel(noise); 
    }
    else if(intVal == DISTURBER_INT){
      Serial.println("Disturber."); 
      // Too many disturbers? Uncomment the code below, a higher number means better
      // disturber rejection.
      //lightning.watchdogThreshold(disturber);  
    }
    else if(intVal == LIGHTNING_INT){
      Serial.println("Lightning Strike Detected!"); 
      // Lightning! Now how far away is it? Distance estimation takes into
      // account any previously seen events in the last 15 seconds. 
      byte distance = lightning.distanceToStorm(); 
      Serial.print("Approximately: "); 
      Serial.print(distance); 
      Serial.println("km away!"); 
    }
  }
  delay(100); // Slow it down.
}

When lightning is sensed you'll see the following in your Arduino serial window.

This image shows a picture of the Arduino IDE's Serial Monitor with lightning being detected printed out.

Example 2 - More Lightning Sensor Features SPI

In the following example we'll explore some of the other features available to you from the SparkFun Lightning Detector Arduino Library. This example actually functions exactly as the example above in that it monitors for a lightning event in the main loop; so we'll focus on the setup to see how it demonstrates different settings that you can set.

At the top we have a few more variable for a number of settings. The first two noiseFloor and watchDogVal holds the values for increasing the Lightning Detector's robustness against noise and false lightning events respectively. The following variable spike holds a value to further increase the robustness of the SparkFun Lightning Detector towards false events. Finally lightningThresh holds the value for the number of lightning events that need to occur before the SparkFun Lightning Detector alerts you.

language:c
// Values for modifying the IC's settings. All of these values are set to their
// default values. 
byte noiseFloor = 2;
byte watchDogVal = 2;
byte spike = 2;
byte lightningThresh = 1; 

The first function call lightning.maskDisturber(true) will stop the Lightning Detector from alerting you to any false events at all. We check that the setting was set correctly with lightning.readMaskDisturber()

language:c
lightning.maskDisturber(true); 

int maskVal = lightning.readMaskDisturber();
Serial.print("Are disturbers being masked: "); 
if (maskVal == 1)
    Serial.println("YES"); 
else if (maskVal == 0)
    Serial.println("NO"); 

The next two function calls increase the SparkFun Lightning Detector's robustness to noise with lightning.setNoiseLevel() and false lightning events with lightning.watchdogThreshold(). We give these function the values in the variables mentioned above: noiseFloor and watchDogVal. Just below each of these respective functions are functions that read back the settings we just set: lightning.readNoiseLevel() and lightning.readWatchdogThreshold().

language:c
lightning.setNoiseLevel(noiseFloor);  

int noiseVal = lightning.readNoiseLevel();
Serial.print("Noise Level is set at: ");
Serial.println(noiseVal);

// Watchdog threshold setting can be from 1-10, one being the lowest. Default setting is
// two. If you need to check the setting, the corresponding function for
// reading the function follows.    

lightning.watchdogThreshold(watchDogVal); 

int watchVal = lightning.readWatchdogThreshold();
Serial.print("Watchdog Threshold is set to: ");
Serial.println(watchVal);

The next setting is a bit light on details in the datasheet but helps to increase the SparkFun Lightning Detector's ability to reject false positives by reducing the spike that is analyzed by the validation routine within the Lightning Detector. This will make the lightning detector less sensitive.

language:c
// Spike Rejection setting from 1-11, one being the lowest. Default setting is
// two. If you need to check the setting, the corresponding function for
// reading the function follows.    
// The shape of the spike is analyzed during the chip's
// validation routine. You can round this spike at the cost of sensitivity to
// distant events. 

lightning.spikeRejection(spike); 

int spikeVal = lightning.readSpikeRejection();
Serial.print("Spike Rejection is set to: ");
Serial.println(spikeVal);

The lightning.lightningThreshold() function makes it possible to increase the number of lightning strikes that the lightning detector senses before it issues an interrupt. Possible settings are 1, 5, 9 , or 16 lightning strikes.

language:c
// This setting will change when the lightning detector issues an interrupt.
// For example you will only get an interrupt after five lightning strikes
// instead of one. Default is one, and it takes settings of 1, 5, 9 and 16.   
// Followed by its corresponding read function. Default is zero. 

lightning.lightningThreshold(lightningThresh); 

uint8_t lightVal = lightning.readLightningThreshold();
Serial.print("The number of strikes before interrupt is triggerd: "); 
Serial.println(lightVal); 

Did you set too many settings and just want to get it back to default settings? Then the function lightning.resetSettings() will do just that.

As mentioned above this example code does exactly the same as the first example above but offers more settings to tailor your SparkFun Lightning Detector to your project.

More Example Code

If you're looking to tune the antenna's frequency of the SparkFun Lightning Detector then check out the Example 3- Tune Antenna SPI included in the SparkFun Lightning Detector Library. You'll need some method of reading a square wave of at least 4kHz: an oscilloscope, or logical analyzer. As a good starting point, we've found that the resonance frequency of our manufactured boards start at about ~496kHz. The datasheet specifies that the resonance frequency should be within 3.5 percent above or below 500mHz for optimal lightning detection. Our boards ship within less than one percent of that value.

Resources and Going Further

For more on the AS3935, check out the links below:

Need some other weather sensing parts for your project? Check out some of the ones listed below.

Weather Meters

Weather Meters

SEN-08942
$76.95
26
SparkFun Environmental Combo Breakout - CCS811/BME280 (Qwiic)

SparkFun Environmental Combo Breakout - CCS811/BME280 (Qwiic)

SEN-14348
$35.95
12
SparkFun Pressure Sensor Breakout - MS5803-14BA

SparkFun Pressure Sensor Breakout - MS5803-14BA

SEN-12909
$59.95
7
SparkFun Weather Shield

SparkFun Weather Shield

DEV-13956
$39.95
4

Need some inspiration for your next project? Check out some of these related tutorials to sense your environment!

Experiment Guide for the Johnny-Five Inventor's Kit

Use the Tessel 2 and the Johnny Five Inventors kit to explore the world of JavaScript enabled hardware through 14 awesome experiments!

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.

RHT03 (DHT22) Humidity and Temperature Sensor Hookup Guide

Measure relative humidity and temperature or your environment with the RHT03 (a.k.a DHT22) low cost sensor on a single wire digital interface connected to an Arduino!
New!

Qwiic Ambient Light Sensor (VEML6030) Hookup Guide

The VEML6030 is a high accuracy ambient light sensor with 16-bit resolution. This I2C sensor can detect light similar to the human eye response. Start detecting light levels in your environment!

Or check out this related blog post.


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

How to Install CH340 Drivers

$
0
0

How to Install CH340 Drivers a learn.sparkfun.com tutorial

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

Introduction

In this tutorial, we'll show you how to install CH340 drivers on multiple operating systems if you need. The driver should automatically install on most operating systems. However, there are is a wide range of operating systems out there. You may need to install drivers the first time you connect the chip to your computer's USB port or when there are operating system updates.

CH340 Highlighted and Closeup

Required Materials

Depending on your application, the CH340 may be populated on a breakout or development board. Here are a few boards that use this particular USB-to-serial converter.

BlackBoard Artemis ATP

BlackBoard Artemis ATP

SPX-15412
$24.95
1
BlackBoard Artemis

BlackBoard Artemis

SPX-15332
$19.95
SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

DEV-15123
$19.95
1
SparkFun Serial Basic Breakout - CH340C and USB-C

SparkFun Serial Basic Breakout - CH340C and USB-C

DEV-15096
$8.95
2
SparkFun Serial Basic Breakout - CH340G

SparkFun Serial Basic Breakout - CH340G

DEV-14050
$7.95
5
SparkFun Servo pHAT for Raspberry Pi

SparkFun Servo pHAT for Raspberry Pi

DEV-15316
$10.95

Accessories

You'll also need the correct USB cable to connect the board to your computer. You may need a jumper wires and a breadboard for prototyping.

Jumper Wires Premium 6" M/M Pack of 10

Jumper Wires Premium 6" M/M Pack of 10

PRT-08431
$3.95
2
USB 3.1 Cable A to C - 3 Foot

USB 3.1 Cable A to C - 3 Foot

CAB-14743
$4.95
2
SparkFun Traveler microB Cable - 1m

SparkFun Traveler microB Cable - 1m

CAB-14741
$3.95

Suggested Reading

Before you begin this tutorial, you should have the Arduino IDE installed on your computer. Check out our Installing Arduino tutorial for a step by step guide.

Serial Communication

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

Connector Basics

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

What is an Arduino?

What is this 'Arduino' thing anyway?

Logic Levels

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

Serial Terminal Basics

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

Alright, let's get to work! You can visit the next section to learn more about the CH340 and why you need the drivers, or you can skip straight to the operating system of your choice!

Meet the CH340

There are a few variants of the CH340. The CH340G requires an external crystal oscillator to function while the CH340C includes a built-in crystal oscillator. However, both function in the same fashion - they convert USB data for a serial UART and vice versa!

CH340G HighlightedCH340C Highlighted
CH340GCH340C

The CH340 is also populated on development boards such as the RedBoard Qwiic to upload code using the Arduino IDE.

RedBoard Qwiic w/ CH340 Highlighted

Drivers (If You Need Them)

The CH340 has been tested on:

  • Windows 7/10
  • Mac OSX
    • v.10.13.1 (High Sierra)
  • Linux
    • Raspbian Buster (2019-07-10 release) for the Raspberry Pi
    • Ubuntu v18.04.2, 64-bit

These operating systems have the CDC drivers pre-installed, which means you shouldn't need to install any extra software. However, there are a wide range of operating systems out there, so if you run into driver problems, you can get the archived drivers linked below:

The CH340 is made by WCH. You can find the latest version of their drivers here, but most of their pages are in Mandarin. If you use a Chrome web browser, you should have the option to have the web page translated.

Updating Drivers

If you have the older CH340 drivers installed, you may need to update them. Below are the instructions for doing so on each of the tested operating systems.

Windows 7/10

Note for Educators: You will need to obtain administrative privileges from your network or IT administrator in order to install these drivers. Make sure to test the drivers before class and set aside some time with students in the classroom when installing the drivers.

Download and run the executable.

Click the "Uninstall" button first. Then click on the "Install" button.

Win 10 Installation Screenshot
Windows CH340 Driver Installation

Driver Verification for Windows

To verify that your driver is working, you should see a difference in the following pictures after plugging the CH340 to a USB port.

Device Manager

To check that the CH340 enumerates to a COM port, you can open the device manager. You can click the Start or (Windows) button and type "device manager to quickly search for the application.

searching for device manager

Using the search on Windows 10 to look for the device manager.

After opening the device manager, you will need to open the Ports (COM & LPT) tree. The CH340 should show up as USB-SERIAL CH340 (COM##). Depending on your computer, the COM port may show up as a different number.

CH340 in the Device Manager

Screenshot of Window 10 Device Manager with a CH340 displayed on COM123. Click to enlarge.

Arduino IDE

Alternatively, if you have the Arduino IDE installed, you should also see a change in the number of available COM Ports (you may need to restart the Arduino IDE for the board to populate). Without the CH340 connected to your computer, click on Tools>Port. Take note of the Serial Ports available.

Arduino IDE COM Ports

Connect the CH340 to your computer's USB port. Click on somewhere else on the screen for the menu to refresh itself. Then head back to the menu by clicking on Tools>Port. A new COM port should pop up. By process of elimination, the CH340 should have enumerated to the new COM port! Feel free to click on the COM port to select if you are uploading code to a microcontroller. Depending on your computer, the COM port may show a different number.

Arduino IDE COM Ports CH340

Mac OSX

Note for Educators: You will need to obtain administrative privileges from your network or IT administrator in order to install these drivers. Make sure to test the drivers before class and set aside some time with students in the classroom when installing the drivers.

Open the Terminal program by selecting Go>Applications.

Applications Folder

Select and open the Terminal program under Applications>Utilities>Terminal.

Open the Terminal Window
Note: You can also search with Spotlight by pressing (Command) + space bar (Space Bar). Then type "Terminal" and double-click the search result.

If you are still unsure of how to access the Terminal, watch this video or read this Apple support article.

You'll need to move to the directory where the *.kext files are stored.

  • For Mac OSX v10.9+, you will need to use this command:

    language:bash
    cd /Library/Extensions
    
  • For Mac OSX v10.8-, you will need to use this command:

    language:bash
    cd /System/Library/Extensions
    

In this case, we will be using Mac OSX v10.13, so we will need to use the first command.

change directory to where the drivers are located

To check to see if the CH340 driver is in the correct path, use the following command to list the contents of the folder.

language:bash
ls

To look for CH340 driver files (i.e. usb.kext or usbserial.kext) in the path, you could use the following command.

language:bash
ls | grep usb

You should see something similar to the output below after using the commands.

KEXT file path

If you have found the file in the path, you will need to run each of the following commands in the CLI/Terminal to remove old CH340 drivers. In this case, there was only the usbserial.kext file but it does not hurt to run both commands. Make sure to have administrative privileges to ensure that the drivers are removed.

language:bash
sudo rm -rf /Library/Extensions/usb.kext
sudo rm -rf /Library/Extensions/usbserial.kext

Download and extract the folder.

Then, open the "*.pkg" file from the unzipped folder and follow the instructions. You'll need to restart your computer for the changes to take effect.

Mac OSX Installation Screenshot

Mac OSX CH340 Driver Installation File


Driver Verification for Macs

To verify that your driver is working, you should see a difference in the following pictures after plugging the CH340 to a USB port.

Command Line

Open the Terminal by heading to Applications>Utilities>Terminal if the program is not open yet.

Open Terminal Program

Then run the following command:

language:bash
ls /dev/cu* 

A list of devices connected to your Mac's COM ports will be displayed as a result. Assuming that the CH340 is not connected to your computer, you should see something similar to the image below.

List of Devices Connected

Connect the CH340 to one of your Mac's COM ports. Check for the following changes (your board may show up under a different device name). The CH340 should show up as /dev/cu.wchusbserial*****. Depending on your computer, the COM port may show up as a different number.

List of Devices Connected with the CH340

Screenshot of Mac OSX terminal with CH340 on cu.wchusbserialfd1410. Click to enlarge.

Arduino IDE

Alternatively, if you have the Arduino IDE installed, you should also see a change in the number of available COM Ports (you may need to restart the Arduino IDE for the board to populate). Without the CH340 connected to your computer, click on Tools>Port. Take note of the Serial Ports available.

Available Serial Ports on Arduino IDE

Connect the CH340 to your computer's USB port. Click on somewhere else on the screen for the menu to refresh itself. Then head back to the menu by clicking on Tools>Port. A new COM port should pop up. By process of elimination, the CH340 should have enumerated to the new COM port! Feel free to click on the COM port to select if you are uploading code to a microcontroller. Depending on your computer, the COM port may show a different number.

Available Serial Ports  w/ CH340 on Arduino IDE

Linux

Note for Educators: You will need to obtain administrative privileges from your network or IT administrator in order to install these drivers. Make sure to test the drivers before class and set aside some time with students in the classroom when installing the drivers.

Raspbian for Raspberry Pi

Run the following commands in the CLI/Terminal when using Raspbian on a Raspberry Pi. After updating, the latest CH340 should be installed!

language:bash
sudo apt-get update
sudo apt-get upgrade

Other Linux Distributions

Here is a downloadable *.ZIP of standard CH340 drivers for Linux.

There are some reported cases of serial communication failure when using the factory drivers in Linux. If you encounter this problem, you can try installing patched drivers as explained in this forum post. Here are the steps (to run in the command line):

  • Plug and unplug your CH340 device from the USB port
  • Type dmesg to see what has happened
    • The expected output (shows "ch341") should have the following in the recent log:
[  xxx] ch341-uart ttyUSB0: ch341-uart converter now disconnected from ttyUSB0
[  xxx] ch341 3-2:1.0: device disconnected
  • Download the patched drivers repository and unzip the files


  • cd into the directory where the files are saved
  • make clean
  • make
  • sudo make load
  • sudo rmmod ch341 to uninstall the broken driver
  • lsmod | grep ch34 to list what modules are currently installed
  • Plug and unplug your CH340 device again on the USB port
  • dmesg
    • Expected output (should show "ch34x" now):
[  xxx] ch34x ttyUSB0: ch34x converter now disconnected from ttyUSB0
[  xxx] ch34x 3-2:1.0: device disconnected

Depending on your root permissions, you may need to configure the serial port with the following two commands. Make sure to adjust the $username with respect to the user ID that is currently logged in.

language:bash
sudo usermod -a -G dialout $username 
sudo chmod a+rw /dev/ttyUSB0

Driver Verification for Linux

Plug the CH340 back to your computer's USB port. Then run the following command in the CLI/Terminal on any Linux distribution. Check for the following changes (your board may show up under a different device name).

language:bash
ls /dev/ttyUSB*

The serial port that CH340 is connected to should pop up as a result.

Raspbian CLI Command Entry
Screenshot of Raspberry Pi CLI with the CH340 on ttyUSB0. Click to enlarge

Troubleshooting

COM Port is Not Showing Up as CH340 Windows

We have had a few reports on Windows 10 where the driver will automatically install and the board will show up under a new COM port as USB-Serial CH340, but with a different device name. However, the board cannot be accessed on the Arduino IDE. Others have had issues where the installation process hangs.

Based on the customer experiences, this might be specific to the manufacturer and are usually isolated cases. Users seem to be able to eventually get the board recognized by a combination of giving the computer time to finish the install (close to 20 min), plugging the board back in multiple times, reinstalling the drivers, and/or resetting the computer multiple times (repeat both steps).

COM Port Not Available Windows, Mac, and Linux

If you installed the drivers for the CH340 on your computer but have issues connecting via serial terminal or uploading code using the Arduino IDE, there may be an issue with your user settings preventing you from using the CH340. You may receive an avrdude: ser_open(): can't open device error similar to the output shown below.

language:bash
avrdude: ser_open(): can't open device "/dev/ttyUSB0": No such file or directory

In this case, the error appeared on a Linux when trying to upload code due to the drivers not being installed and the root permissions.

Arduino ser_open() error

Make sure to check your configuration settings and ensure that the serial port for the CH340 is enabled for your OS. You may also need to reinstall the drivers for your operating system.

USB Cable Windows, Mac, and Linux

Certain USB cables are for power only and may not have the data lines available. Try checking your USB cable and ensure that the data lines are intact.

Resources and Going Further

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

USB-to-serial converters like the CH340 are great for uploading code to a microcontroller or viewing data from a GPS on a serial terminal. Check out these tutorials to dive even deeper into the world of microcontrollers or send serial data to your computer with a GPS!

Serial Terminal Basics

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

Headless Raspberry Pi Setup

Configure a Raspberry Pi without a keyboard, mouse, or monitor.

GPS-RTK Hookup Guide

Find out where you are! Use this easy hook-up guide to get up and running with the SparkFun high precision GPS-RTK board.

RedBoard Qwiic Hookup Guide

This tutorial covers the basic functionality of the RedBoard Qwiic. This tutorial also covers how to get started blinking an LED and using the Qwiic system.

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

Viewing all 1123 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>