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

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

$
0
0

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

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

Introduction

The Real Time Clock Module - RV-8803 (Qwiic) is a Qwiic-enabled breakout board for the RV-8803 RTC module. The RV-8803 boasts some impressive features including a temperature compensated crystal, extremely precise time-keeping, low power consumption, time stamp event input along with a user-programmable timing offset value. It even has a programmable Clock Output to control precise timing for peripheral devices. The RV-8803 also has an improved I2C interface compared to the RV-1805 RTC that removes the need to sequence commands/writes to the device. This is particularly helpful if you are not using our Arduino Library to control the RTC.

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

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

BOB-16281
$14.95

In this hookup guide we will go over the unique features of the RV-8803 along with some Arduino examples demonstrating how to use those features. By the end of this tutorial you will have your Real Time Clock Module - RV-8803 (Qwiic) configured and tick-tocking away (well, ticking, maybe not tocking) for your next time-keeping project!

Required Materials

To follow along with this guide you will need a microcontroller to configure and communicate with the RTC Module breakout. Below are a few options that come Qwiic-enabled out of the box:

SparkFun Qwiic Pro Micro - USB-C (ATmega32U4)

SparkFun Qwiic Pro Micro - USB-C (ATmega32U4)

DEV-15795
$19.95
SparkFun Thing Plus - ESP32 WROOM

SparkFun Thing Plus - ESP32 WROOM

WRL-15663
$20.95
1
SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

DEV-15123
$19.95
5
SparkFun RedBoard Artemis

SparkFun RedBoard Artemis

DEV-15444
$19.95

If your chosen microcontroller is not already Qwiic-enabled, you can add that functionality with one or more of the following items:

SparkFun Qwiic Cable Kit

SparkFun Qwiic Cable Kit

KIT-15081
$7.95
1
SparkFun Qwiic Shield for Arduino

SparkFun Qwiic Shield for Arduino

DEV-14352
$6.95
SparkFun Qwiic Adapter

SparkFun Qwiic Adapter

DEV-14495
$1.50
SparkFun Qwiic Shield for Arduino Nano

SparkFun Qwiic Shield for Arduino Nano

DEV-16130
$3.50

You will also want at least one Qwiic cable to connect your RTC to your microcontroller.

Qwiic Cable - 100mm

Qwiic Cable - 100mm

PRT-14427
$1.50
Qwiic Cable - 200mm

Qwiic Cable - 200mm

PRT-14428
$1.50
Qwiic Cable - 50mm

Qwiic Cable - 50mm

PRT-14426
$0.95
Qwiic Cable - 500mm

Qwiic Cable - 500mm

PRT-14429
$1.95

Some of the examples demonstrate how to use more than just the I2C pins. If you want to follow along with them you will need to solder to the EVI, INT, CLKOUT and CLKOE pins broken out on the board. Click the button below to see some recommended soldering tools and materials if you need them.


Finally, if you want to fine tune the RV-8803's oscillator for extremely precise time keeping you will need to use an oscilloscope or logic analyzer to calibrate it. Click the button below to see some options for oscilloscopes and logic analyzers if you need one.

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 taking a look at the hookup guides for the Qwiic Shields listed above if you plan on using one of them. Brushing up on your skills in I2C is also recommended as all Qwiic sensors communicate via I2C.

I2C

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

Qwiic Shield for Arduino & Photon Hookup Guide

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

SparkFun Qwiic Shield for Arduino Nano Hookup Guide

Hookup Guide for the SparkFun Qwiic Shield for Arduino Nano.

SparkFun Qwiic Shield for Thing Plus Hookup Guide

A short guide for assembling and using the SparkFun Qwiic Shield for Thing Plus.

Hardware Overview

The heart of this breakout is the RV-8803 Real Time Clock module from Micro Crystal. In this section we'll cover most of the features and characteristics of the RV-8803 and this breakout but if you are looking for a more thorough synopsis of the RV-8803, take a look through the Application Manual . The table below lists some of the operating characteristics of the RV-8803.

CharacteristicValue
Operating Voltage Range1.5V - 5.5V
Time Accuracy (Temp. Compensated -40° to +85°C) +/-3 ppm
Time Accuracy (Temp. Compensated +85° to +105°C) +/-7 ppm
Current Consumption240 nA (Typ.) to 350 nA
I2C Address0x64

Power

There are two primary ways to power the SparkFun Real Time Clock Module - RV-8803 (Qwiic). The best and easiest way is through the Qwiic Connectors on either side of the board. When used with any of our Qwiic-enabled boards or our Qwiic Shields, this voltage will be 3.3V. The other power input is the 3.3V pin broken out. The board also includes a 3V 47mAh battery in the 12mm coin cell battery holder on the back for backup power.

Photo highlighting battery holder and power pins.
Heads up! While the RV-8803 can accept an input voltage between 1.5-5.5V, the Qwiic system operates at 3.3V so it is recommended to power the RTC with 3.3V or lower, especially if you are using it with other Qwiic devices.

Qwiic and I2C Interface

The easiest way to use the Real Time Clock Module - RV-8803 (Qwiic) is with the Qwiic connect system. Just connect the board using a Qwiic Cable to your microcontroller to start talking to it. Alternatively, you can solder to the I2C pins broken out on the board. The 7-bit I2C address is 0x32 (0110010b). This is a hardware set address and there are no alternate slave addresses for the RV-8803. If you need multiple RTC's on a single I2C bus you will need to use a multiplexer or mux like the Qwiic Mux Breakout - 8 Channel.

Photo highlighting Qwiic connector and SDA and SCL pins.

Pin Descriptions

While the Qwiic interface is the easiest and fastest way to start using your RTC, there are several other pins for extra functionality broken out. You will need to either solder to these pins to make use of them or you can create a temporary connection using something like these IC Hooks. The table below outlines all of the pins broken out on the RTC and summarizes their functionality.

Pin LabelPin FunctionInput/OutputFunctionality Notes
GNDGroundInput0V/Common Voltage
3.3VPower SupplyInputPower Supply voltage range is 1.5-3.3V
SDAI2C Data SignalBi-directionalBi-directional data line. Voltage should not exceed power supply (e.g. 3.3V).
SCLI2C Clock SignalInputMaster-controlled clock signal. Voltage should not exceed power supply (e.g. 3.3V).
EVIEvent InputInput/OutputExternal event interrupt pin with Time Stamp Function. Active LOW by default. Tied to the button labeled EVI for easy use.
INTInterrupt OutputOutputOpen-drain, active LOW. Used to output Alarm, Periodic Countdown Timer, Periodic Time Update and External Event Interrupt signals. Pulled to 3.3V with 100k resistor.
CLKOUTClock OutputOutputProgrammable square wave output for peripheral devices. Available frequencies are 32.768 kHz (default), 1024 Hz or 1Hz. Set on power-up and controlled by the state of CLKOE pin. When disabled, pin is high impedance.
CLKOEClock Output EnableInputEnables and disables the CLKOUT pin. If HIGH, CLKOUT is enabled and is in output mode. If LOW, CLKOUT is disabled. Pin is pulled to GND by default with a 100k resistor.

Photo Highlighting Pinout and EVI Button
The EVI pin is broken out but also connected to the button highlighted to easily trigger interrupt events like time stamps.

Jumpers

There are two jumpers on the SparkFun Real Time Clock Module - RV-8803 (Qwiic) labeled "I2C" and "LED". The I2C jumper is closed by default and can be opened by severing the trace between the three pads to disconnect the two 4.7k Ohm resistors from the SDA and SCL lines. Open this jumper for if you have many I2C devices on the same bus or to reduce current draw for low-power projects. The LED jumper is closed by default and enables the on board power LED. To open it, simply sever the trace in between the two jumper pads to disconnect the power LED (particularly useful for low-power applications). Note: The power LED is tied to the 3.3V input and is not powered by the backup battery.

Highlighting the I2C jumperHighlighting the LED Jumper
I2C Jumper highlightedLED Jumper Highlighted
Never worked with solder jumpers before or need some tips? Take a look at our How to Work with Jumper Pads and PCB Traces Tutorial.

Board Dimensions

The SparkFun Real Time Clock Module - RV-8803 (Qwiic) is built to the standard 1 x 1" size for Qwiic Breakouts. One thing you may notice is this board's lack of mounting holes. In order to fit the 1 x 1" standard for Qwiic Breakouts, there was no space for mounting holes as the battery holder takes the space normally reserved for those mounting holes.

Qwiic RTC RV-8803

Hardware Assembly

Using the Qwiic system, assembling the hardware is simple. All you need to do is connect your Real Time Clock Module - RV-8803 (Qwiic) to your chosen development board with a Qwiic cable or adapter cable. Otherwise, you can use the I2C pins broken out if you do not have a Qwiic connector on your development board. If you are not using a Qwiic-enabled board, make sure your input voltage and logic are either running at 3.3V or you are running both controller and RTC at the same logic level.

Qwiic RTC connected to the RedBoard Qwiic

In order to use the full functionality of the RV-8803, you will want to solder to the EVI, INT, CLKOUT and CLKOE pins broken out on this board. If you are not familiar with through-hole soldering, take a look at this tutorial:

How to Solder: Through-Hole Soldering

September 19, 2013

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

With everything connected properly, we're ready to move on to uploading a sketch and start keeping track of time!

RV-8803 Arduino Library

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

The easiest way to install the library is to search for SparkFun RV-8803 in the Arduino Library Manager tool. You can also manually install the RV-8803 Library from the GitHub Repository or you can download it by clicking the button below.

Library Functions

The list below outlines all of the functions of the library with some quick descriptions of what they do. The examples cover most of the functions so we recommend going through those first.

Device Setup & Settings

  • bool begin(TwoWire &wireport); - Initializes the RV-8803 on the I2C bus.
  • void set12Hour(); - Configures the microcontroller to convert to 12 hour mode.
  • void set24Hour(); - Configures the microcontroller to not convert from the default 24 hour mode.
  • bool is12Hour(); - Returns true if the microcontroller is configured to 12 hour mode.
  • bool isPM(); - Returns true if the microcontroller is in 12 hour mode and the RTC has an hours value greater than or equal to 12 (Noon).
  • char* stringDateUSA(); - Returns the date in MM/DD/YYYY format.
  • char* stringDate(); - Returns the date in the DD/MM/YYYY format.
  • char* stringTime(); - Returns the time in hh:mm:ss (Adds AM/PM if in 12 hour mode).
  • char* stringTimeStamp(); - Returns the most recent timestamp captured on the EVI pin (if the EVI pin has been configured to capture events). The format is hh:mm:ss:HHXM with \0 terminator where 'X' is 'A' or 'P' depending on the time of day.
  • char* stringTime8601(); - Returns timestamp in ISO 8601 format (yyyy-mm-ddThh:mm:ss).
  • bool setTime(uint8_t sec, uint8_t min, uint8_t hour, uint8_t date, uint8_t month, uint8_t year, uint8_t day); - Sets the RTC's time registers using a set of individual variables.
  • bool setTime(uint8_t * time, uint8_t len); - Sets the RTC's time registers using an array with the following structure; {HUNDREDTHS, SECONDS, MINUTES, HOURS, WEEKDAY, DATE, MONTH, YEAR}
  • bool setHundredthsToZero(); - The hundredths register is read only so instead of writing to it, this function uses the Reset Bit Function on the RV8803 to set this register to zero. Check out section 4.13 of the RV-8803 Application Manual for more information about this function.
  • bool setSeconds(uint8_t value); - Sets the seconds register to value.
  • bool setMinutes(uint8_t value); - Sets the minutes register to value.
  • bool setHours(uint8_t value); - Sets the hours register to value.
  • bool setDate(uint8_t value); - Sets the date register to value.
  • bool setMonth(uint8_t value); - Sets the month register to value.
  • bool setYear(uint16_t value); - Sets the year register to value.
  • bool setWeekday(uint8_t value); - Sets the weekday register to value.
  • bool setToCompilerTime(); - Sets the RTC to the time from the last build and uses it as current time.
  • bool setCalibrationOffset(float ppm); - Loads the calibrated PPM offset to the RV8803_OFFSET register.
  • float getCalibrationOffset(); - Returns the calibration offset value stored in the RV8803_OFFSET register.

Reading from the RTC

  • bool updateTime(); - Move the time registers (hours, mins, secs, etc.) from the RV-8803 into the _time array that lives on the microcontroller. Needs to be called before printing time or date.
  • uint8_t getHundredths(); - Returns _time value from the hundredths register.
  • uint8_t getSeconds(); - Returns _time value from the seconds register.
  • uint8_t getMinutes(); - Returns _time value from the minutes register.
  • uint8_t getHours(); - Returns the _time value from the hours register.
  • uint8_t getDate(); - Returns the _time value from the date register.
  • uint8_t getWeekday(); - Returns the _time value from the weekday register.
  • uint8_t getMonth(); - Returns the _time value from the month register.
  • uint16_t getYear(); - Returns the _time value from the year register.
  • uint8_t getHundredthsCapture(); - Returns the captured value from the hundredths register (Time Stamp).
  • uint8_t getSecondsCapture(); - Returns the captured value from the seconds register (Time Stamp).

Alarm & Interrupt Functionality

Since the RV-8803 has three types of alarms/interrupts, this list is quite extensive so we've split it up into the individual alarm and interrupt functionalities.

External Event Interrupt
  • bool setEVICalibration(bool eviCalibration); - Enables or disables the the External Event Interrupt (EVI) button and pin.
  • bool setEVIDebounceTime(uint8_t debounceTime); - Sets the debounce time for the EVI pin and button. Can be set to None, 256 Hz, 64 Hz or 8 Hz.
  • bool setEVIEdgeDetection(bool edge); - Sets the EVI to fire on either the rising or falling edge of the signal.
  • bool setEVIEventCapture(bool capture); - Enables or disables the EVI Event Capture function.
  • uint8_t getEVIDebounceTime(); - Returns the value set for the EVI Debounce time.
  • bool getEVICalibration(); - Returns whether or not the EVI functionality is enabled or disabled.
  • bool getEVIEdgeDetection(); - Returns whether the EVI function is set to rising or falling edge.
  • bool getEVIEventCapture(); - Returns whether or not the EVI Event Capture function is enabled or disabled.
Countdown Interrupt
  • bool setCountdownTimerEnable(bool timerState); - Enables or disables the Periodic Countdown Timer interrupt function.
  • bool setCountdownTimerFrequency(uint8_t countdownTimerFrequency); - Sets the time for the Periodic Countdown Timer. Built in values are 4096 Hz, 60 Hz, 1 Hz and 1/60 Hz.
  • bool setCountdownTimerClockTicks(uint16_t clockTicks); - Sets the number of clock ticks to count for the Countdown Timer. Refer to the Example 4B - Countdown Interrupt overview in the next section of this guide for more information on calculating the number of clock ticks for your timer.
  • bool getCountdownTimerEnable(); - Returns whether or not the Countdown Timer is enabled or disabled.
  • uint8_t getCountdownTimerFrequency(); - Returns the frequency set for the Countdown Timer.
  • uint16_t getCountdownTimerClockTicks(); - Returns the number of clock ticks set for the Countdown Timer.
Periodic Interrupt
  • bool setPeriodicTimeUpdateFrequency(bool timeUpdateFrequency); - Sets the frequency of the Periodic Time Update interrupt function. Can be 1 Hz (one second) or 1/60 Hz (one minute).
  • bool getPeriodicTimeUpdateFrequency(); - Returns the time set for the Periodic Time Update interrupt frequency.
Alarm Interrupt
  • void setItemsToMatchForAlarm(bool minuteAlarm, bool hourAlarm, bool dateAlarm, bool weekdayOrDate); - Function to select which time values need to match to trigger an alarm. Can be set to minutes, hours, date or weekday+date. Setting the bit to 1 means the RTC will not look to match that item for an alarm.
  • bool setAlarmMinute(uint8_t minute); - Set the minute value for the RTC to match to trigger an alarm.
  • bool setAlarmHour(uint8_t hour); - Set the hour value for the RTC to match to trigger an alarm.
  • bool setAlarmWeekday(uint8_t weekday); - Set the weekday value for the RTC to match to trigger an alarm.
  • bool setAlarmDate(uint8_t date); - Set the date value for the RTC to match to trigger an alarm.
  • uint8_t getAlarmMinute(); - Returns the minute value set for the RTC to match for an alarm.
  • uint8_t getAlarmHour(); - Returns the hour value set for the RTC to match for an alarm.
  • uint8_t getAlarmWeekday(); - Returns the weekday value set for the RTC to match for an alarm.
  • uint8_t getAlarmDate(); - Returns the date value set for the RTC to match for an alarm.

Configuring the Clock Out (CLKOUT) pin

These two functions are for enabling and configuring the Clock Out pin. Use these with the setCalibrationOffset(); and getCalibrationOffset(); functions to fine tune your RTC. Refer to Example 6 - Fine Tuning in the next section of this guide for more information.

  • bool setClockOutTimerFrequency(uint8_t clockOutTimerFrequency); - Sets the frequency of the square wave output from the Clock Out pin. Available frequencies are 1Hz, 1024Hz and 32,768 Hz.
  • uint8_t getClockOutTimerFrequency(); - Returns the frequency set for the Clock Out.

Extra Functions

  • uint8_t BCDtoDEC(uint8_t val); - Convert values in the RTC from Binary Coded Decimal to Decimal.
  • uint8_t DECtoBCD(uint8_t val); - Convert values in the RTC from Decimal to Binary Coded Decimal.
  • bool readBit(uint8_t regAddr, uint8_t bitAddr); - Read a single bit from the selected register.
  • uint8_t readTwoBits(uint8_t regAddr, uint8_t bitAddr); - Read two bits from the selected register.
  • bool writeBit(uint8_t regAddr, uint8_t bitAddr, bool bitToWrite); - Write a selected bit to a register.
  • bool writeBit(uint8_t regAddr, uint8_t bitAddr, uint8_t bitToWrite); - Write a selected bit to a register.
  • uint8_t readRegister(uint8_t addr); - Read a specific register.
  • bool writeRegister(uint8_t addr, uint8_t val); - Write a specific register.
  • bool readMultipleRegisters( uint8_t addr, uint8_t * dest, uint8_t len); - Read multiple consecutive registers.
  • bool writeMultipleRegisters(uint8_t addr, uint8_t * values, uint8_t len); - Write multiple consecutive registers.

Next up we'll go over the examples included with the RV-8803 Arduino Library.

Arduino Examples

Example 1 - Set Time

This example demonstrates how to set the time on the RV-8803 RTC to either the compiler time or a custom time. This is necessary to set the RTC's internal clock to keep time so long as the RTC has power. First, the code initializes the RV-8803 on the I2C bus and verifies the microcontroller can talk to it. Next, it sets the internal clock. Take note of the following bits of code to set the RTC time to either the compiler or a custom time:

When setting a custom time, change these values at the beginning of the sketch:

language:c
//The below variables control what the date and time will be set to
int sec = 2;
int minute = 47;
int hour = 14; //Set things in 24 hour mode
int date = 2;
int month = 3;
int year = 2020;
int weekday = 2;

In the setup, this code selects either compiler time or custom time:

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

//Uncomment the below code to set the RTC to your own time
/*if (rtc.setTime(sec, minute, hour, weekday, date, month, year) == false) {
Serial.println("Something went wrong setting the time");
}*/

If everything goes correctly here your RTC's internal clock will either be set to the compiler time or your custom time using the variables defined earlier in the sketch. Open the Arduino Serial Monitor, set the baud rate to 115200 and the code will print out over serial whether or not this was successful. If you have never worked with the Arduino Serial Monitor or other serial terminal programs, check out our Serial Terminal Basics tutorial. You can check the accuracy of the time set here by running the second example.

Note: The compiler time is not set every time the code compiles. In order to ensure the proper time is loaded, re-open the IDE and then upload the code. Also note that due to upload times, the compiler time may be off by several seconds/hundredths of seconds. The Set Hundredths examples below can help with more accurate time-keeping.

Example 2 - Print Time

This example shows how to request the time from the RTC after it has been set. The code starts by initializing the RV-8803 on the I2C bus then attempts to to move the values from the RV-8803's time registers to the microcontroller's _time array using the updateTime(); function. If that retrieval is successful, the code prints the time data (date, hour, mins, etc.) over serial. Open up the Serial Monitor and set the baud to 115200 and watch the time fly by, literally!

The code defaults to printing the date in the US format (mm/dd/yyyy) so if you'd like to switch it to the more commonly used dd/mm/yyyy format, adjust this section of the code:

language:c
String currentDate = rtc.stringDateUSA(); //Get the current date in mm/dd/yyyy format
//String currentDate = rtc.stringDate()); //Get the current date in dd/mm/yyyy format
Note: If you are modifying or writing your own code remember the updateTime(); function must be called before attempting to read the time from the RV-8803.

Example 3 - Set Hundredths

We have split this example into two "sub-examples" to demonstrate the ways to reset the hundredths register. The hundredths register is read only so we cannot write to it like the other time variables (seconds, minutes, etc.). Instead, we "set" this register by writing to the RESET bit on the RV-8803. This function is covered in more detail in section 4.13 of the RV-8803 Application Note.

Example 3A - Set Hundredths (Software)

This example initializes the RV-8803 and then configures the RTC to reset the hundredths register on a serial prompt to the microcontroller. After uploading the code, open up the serial monitor (with the baud set to 115200 like the previous examples) and send an "r". Your microcontroller will write to the RESET bit on the RV-8803 to "set" the hundredths register to 00. If you want to reset the hundredths register again, simply send another "r" through your serial monitor.

Example 3B - Set Hundredths (Hardware)

This example is near identical to the Software example above but also enables resetting the hundredths register using the RV-8803's EVI pin along with resetting it via serial commands. The EVI pin can be toggled either through the on board button or by controlling the EVI pin with a GPIO pin on your microcontroller (or other external control mechanism). Resetting the hundredths register using the EVI pin is enabled by this line of code:

language:c
rtc.setEVICalibration(ENABLE);

Enabling this bit tells the RV-8803 to reset the hundredths register when it sees a LOW event on the EVI pin. This event can either be triggered by pressing the button or pulling the EVI pin LOW. The code will print the RV-8803 is ready for a button press or other event on the EVI pin. When that pin is triggered it prints out the the hundredths value pulled from the RV-8803's time register over serial. If you want to verify the register is set, open the serial monitor and toggle the EVI pin and the code should print out: Hundredths set to: 00.

The code also toggles the RESET bit back to 0 so it is ready for another event if you want to set the hundredths register back to 00 again.

Example 4 - Interrupts

Since the RV-8803 has several types of interrupts, we have split the interrupt examples into sub-examples as well. Each one will enable and configure a different interrupt and demonstrate how to use it. To integrate any of these examples to your project, just tie the INT pin to a GPIO on your microcontroller that is usable for external interrupts to trigger whatever behavior you would like when one of these alarms or timers are triggered. If you have never worked with processor interrupts before, we have a tutorial covering how to work with them in Arduino here.

Example 4A - Alarm Interrupt

This example configures the Alarm Interrupt function. The code first defines the variables the RV-8803 will look to match to trigger the Alarm Interrupt and selects which of these variables the RTC will look to match to trigger the alarm. To set it to a different time simply edit these values:

language:c
uint8_t minuteAlarmValue = 55; //0-60
uint8_t hourAlarmValue = 0; //0-24
uint8_t weekdayAlarmValue = 0; //0-6
uint8_t dateAlarmValue = 0; //1-31

#define MINUTE_ALARM_ENABLE true
#define HOUR_ALARM_ENABLE false
#define WEEKDAY_ALARM_ENABLE false
#define DATE_ALARM_ENABLE false

Setting the the various Alarm Enable variables (e.g. MINUTE_ALARM_ENABLE) to true will configure the RV-8803 to check to match that variable to trigger an alarm and, as expected, setting it to false prevents the RV-8803 from matching the variable for the alarm interrupt. The example defaults to trigger an alarm every hour when the minutes value reaches 55.

With the variables defined and enabled/disabled, the code initializes the RV-8803, configures it to trigger an alarm and the calls the values for each time variable (minutes, hours, etc.). The main loop checks if the alarm interrupt flag (FLAG_ALARM) has been triggered using the 'getInterruptFlag` function and, if the alarm is triggered, drives the INT pin LOW and prints over serial the alarm has been triggered.

Lastly, it clears the alarm flag to reset the RTC for the next alarm trigger. If you want to clear the entire flag register on an alarm trigger, uncomment this line:

language:c
//rtc.clearAllInterruptFlags();

Example 4B - Countdown Interrupt

This example demonstrates how to configure a periodic signal interrupt based on a countdown timer and explains how to calculate the proper values for the countdown timer. The countdown timer values require some math to calculate how many clock ticks (0-4095) we want to count along with the length of those ticks (4096 Hz, 64 Hz, 1 Hz, 1/60 Hz) in order to designate the period of the countdown timer. Click the button below to take a look at the table for more information on how the countdown timer interval is calculated:


After initializing the RV-8803, the example configures a ~3.5 second interrupt. To do this, we first choose 60 Hz as our timer frequency since we want our timer longer than 1 second but still want a small enough time range (or resolution) to easily set the interrupt to fire at 3.5 secs and not 3 or 4 seconds. Next, we'll convert 3.5 seconds to 3500 mS since our resolution @60 Hz is 15.625mS/LSB. Finally, to figure out how many ticks are needed for a 3.5 sec interval, we divide the time we want by the resolution of the clock frequency: 3500 / 15.625 = 224 Clock Ticks. With everything calculated, our code configuring the Countdown Timer Interrupt looks like this:

language:c
rtc.disableAllInterrupts();
rtc.setCountdownTimerFrequency(COUNTDOWN_TIMER_FREQUENCY_64_HZ);
rtc.setCountdownTimerClockTicks(224);
rtc.enableHardwareInterrupt(TIMER_INTERRUPT);
rtc.setCountdownTimerEnable(ENABLE); 

lastInterruptTime = millis(); //Change millis() to micros() if you end up using the 4096 Hz counter

The loop checks if the countdown interrupt flag (FLAG_TIMER) has been updated using the getInterruptFlag function. If it has, it clears that flag and prints the time between interrupts (in milliseconds) over serial.

Note: If you select the 4096 Hz counter, make sure to switch all calls to the millis function to call the micros function instead.

Example 4C - Periodic Interrupt

The last interrupt example demonstrates how to generate a periodic pulse from the RV-8803. This is very similar to the previous example but instead of setting a custom time between interrupts, we configure the RV-8803 to pulse the interrupt pin every second or every minute using the setPeriodicTimeUpdateFrequency(); function. The code defaults to a 1 second period but you can change to 1 minute by editing this line:

language:c
rtc.setPeriodicTimeUpdateFrequency(TIME_UPDATE_1_SECOND); //Can also use TIME_UPDATE_1_MINUTE 

The loop checks if the periodic interrupt flag (FLAG_UPDATE) has been updated using the getInterruptFlag function. If it has, it clears that flag and prints the time between interrupts (in milliseconds) over serial.

Example 5 - Timestamp

This example demonstrates how to get a timestamp of an event generated on the EVI pin either by pressing the button on the RTC or toggling the EVI pin from a microcontroller-generated event. First, just like the other examples, we need to initialize the RV-8803 on the I2C bus. Next, we enable and configure the timestamp function:

language:c
rtc.setEVIEventCapture(ENABLE); /
rtc.setEVIDebounceTime(EVI_DEBOUNCE_256HZ); 
//rtc.setEVIEdgeDetection(RISING_EDGE); // Uncomment to set event detection to button release instead of press

The main loop waits for the FLAG_EVI register to update from an external event on the EVI pin using the getInterruptFlag(); function like the other interrupt examples. If that flag is updated and cleared, we capture the date and time stamp of the interrupt and print that data over serial.

Example 6 - Fine Tuning

In order to follow this example you will need an oscilloscope or logic analyzer. If you have never used either of these tools, take a look at these tutorials to get started:

How to Use an Oscilloscope

February 25, 2014

How to work the dials and buttons on an oscilloscope, and a glossary of the o-scope lexicon.

Using the USB Logic Analyzer with sigrok PulseView

June 25, 2018

A quick primer on using the sigrok signal analysis software with our 8-channel, 24MHz USB logic analyzer.

This last example demonstrates how to calibrate the RV-8803's oscillator using the Clock Output pin. Again, we first initialize the RV-8803 on the I2C bus. Next, we zero out any calibration settings that may be present and set the clock output to a 1 Hz square wave:

language:c
rtc.disableAllInterrupts();
rtc.setCalibrationOffset(0); //Zero out any calibration settings we may have
rtc.setPeriodicTimeUpdateFrequency(CLOCK_OUT_FREQUENCY_1_HZ); //Set our clockout to a 1 Hz square wave,
rtc.enableHardwareInterrupt(UPDATE_INTERRUPT); //Enable the interrupt

Next, we'll use our oscilloscope or logic analyzer to look at exactly how precise the 1 HZ square wave is (It could be off by a few microseconds, which can add up over time). In order to do this, you'll need to time the output of the INT pin. Once you have the RTC's output frequency measured carefully, go ahead and replace the "dummy" frequency that we've put in the example by default (1.0000012 Hz) with the one that you've just measured. We then take the difference between this measured frequency and the desired 1 Hz clock signal, and multiply it by 1,000,000 to get the Parts Per Million (PPM) offset that we must give to our oscillator.

language:c
float measuredFrequency = 1.0000012; //Measured frequency in Hz (CHANGE THIS TO YOUR MEASURED VALUE)
float newPPM = (measuredFrequency - 1) * 1000000; //Calculate PPM difference between measuredFrequency and our desired 1 Hz wave

Once we've replaced our measuredFrequency, we can uncomment the below line that actually places this new setting into the RTC to change the offset for the crystal. Make sure you don't do this until you've changed your measuredFrequency. From here, you should be able to upload code and see the square wave oscillator closer to a perfect 1 Hz. If not, recomment the below line, upload, and try again.

language:c
//rtc.setCalibrationOffset(newPPM); //Uncomment this line after you have changed the value of measuredFrequency to load the new calibration into the RTC

Troubleshooting

Resources and Going Further

Now that your Real Time Clock Module RV-8803 (Qwiic) is up and keeping track of time it's time to integrate it into your next time-keeping project!

For more information about the Real Time Clock Module RV-8803 Breakout (Qwiic), take a look at the resources below:

Not sure what type of project you can use your RV-8803 in? Take a look at these tutorials for some inspiration for time-keeping projects:

Getting Started with the Teensy

Basic intro to the Teensy line of products, with soldering and programming suggestions.

Real Time Clock Module Hookup Guide

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

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

Find out what time it is, even after the power's been out on your project for a while with the Qwiic Real Time Clock (RTC) module.

SparkFun gator:RTC Hookup Guide

The gator:RTC is an I2C based, real-time clock (RTC) for keeping time while your micro:bit isn't powered. This tutorial will get you started using the gator:RTC with the micro:bit platform.

Or check out some of these blog posts for project ideas:


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


SparkFun Top pHAT Hookup Guide

$
0
0

SparkFun Top pHAT Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Drum roll please... Introducing, the Top pHAT! The pHAT for the top of all your other HATs. Ta-da!!! It makes the perfect GIF(t).

Grammys GIF
Source: GIPHY

Haha... all jokes aside, this pHAT comes bundled with multiple goodies to begin your Raspberry Pi adventure; including a 2.3" TFT screen, which would be a shame to cover up other HATs.

SparkFun Top pHAT for Raspberry Pi

SparkFun Top pHAT for Raspberry Pi

DEV-16301
$49.95

Additionally, on the Top pHAT you will find the following components:

  • 6 addressable WS2812 RGB LEDs
  • 2 MEMS microphones
  • A mono speaker
  • A 5-way tactile switch
  • 2 momentary buttons
  • A Qwiic connector
  • There are dozens of applicable projects for this product, you can even use it to get started with your machine learning applications. The limits are up to you.

    Required Materials

    The required materials will depend on your project. However, at minimum, users will need a Raspberry Pi, an SD card, and a power supply (or power source). Users can include additional accessories and peripherals for their setup.

    Raspberry Pi

    Each of the models of the Raspberry Pi that we offer have a unique facets that separate them from each other.

    Raspberry Pi 3 B+

    Raspberry Pi 3 B+

    DEV-14643
    $39.95
    31
    Raspberry Pi 4 Model B (4 GB)

    Raspberry Pi 4 Model B (4 GB)

    DEV-15447
    $59.95
    4
    Raspberry Pi 4 Model B (2 GB)

    Raspberry Pi 4 Model B (2 GB)

    DEV-15446
    $39.95
    2
    Raspberry Pi 3 A+

    Raspberry Pi 3 A+

    DEV-15139
    $29.95
    1
    Raspberry Pi Zero W (with Headers)

    Raspberry Pi Zero W (with Headers)

    DEV-15470
    $14.00
    1
    Note: When using the Raspberry Pi 3 or Pi 4, a compatible header that provides enough clearance and interfaces with the Top pHAT is required. This is especially important for a Raspberry Pi 4 with heat sink case, which may require multiple headers to allow air flow for thermal dissipation.

    SD Cards

    These SD cards in our catalog are tested and known to work with all the models of the Raspberry Pi. For first time users, we recommend using the NOOBS version as it has the required OS pre-installed.

    microSD Card with Adapter - 64GB (Class 10)

    microSD Card with Adapter - 64GB (Class 10)

    COM-14833
    $29.95
    microSD Card - 16GB (Class 10)

    microSD Card - 16GB (Class 10)

    COM-15051
    $19.95
    microSD Card with Adapter - 32GB (Class 10)

    microSD Card with Adapter - 32GB (Class 10)

    COM-14832
    $24.95
    SparkFun Noobs Card for Raspberry Pi (16GB)

    SparkFun Noobs Card for Raspberry Pi (16GB)

    COM-15052
    $19.95

    Power Supplies

    These power supplies in our catalog are tested and known to work with the Raspberry Pi models in our catalog.

    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
    Raspberry Pi Wall Adapter Power Supply - 5.1VDC, 3.0A, 15.3W (USB-C)

    Raspberry Pi Wall Adapter Power Supply - 5.1VDC, 3.0A, 15.3W (USB-C)

    TOL-15448
    $8.00

    ⚡ Note:

    The Raspberry Pi 3 and Zero models require a micro-USB power supply. We recommend using the 5.1V 2.5A power supply.

    The Raspberry Pi 4 models require a USB-C power supply.We recommend using the Official Raspberry Pi power supply to avoid this issue.

    Extension Header

    As noted in a previous section, a header is required for the Raspberry Pi 3 and Pi 4 to provided enough clearance between the Top pHAT and Raspberry Pi.

    Raspberry Pi GPIO Tall Header - 2x20

    Raspberry Pi GPIO Tall Header - 2x20

    PRT-14017
    $1.95
    Raspberry Pi GPIO Ribbon Cable - 40-pin, 6" (RPi 3, RPi2, B+)

    Raspberry Pi GPIO Ribbon Cable - 40-pin, 6" (RPi 3, RPi2, B+)

    CAB-13028
    $2.50
    Raspberry Pi GPIO Male Header - 2x20

    Raspberry Pi GPIO Male Header - 2x20

    PRT-14275
    $0.95
    Pimoroni pHAT Stack - Fully Assembled Kit

    Pimoroni pHAT Stack - Fully Assembled Kit

    DEV-16303
    $16.95

    This is especially important for a Raspberry Pi 4 with heat sink case, which may require multiple headers to allow air flow for thermal dissipation. There are some alternatives for that, listed above.

    Peripherals

    For users looking to use the desktop graphical user interface (GUI), they will also need the following:

    • TV, Display, or Monitor
    • Compatible HDMI Cable
    • USB Keyboard and Mouse
    Displays

    For beginners we recommend using a modern TV (i.e. with an HDMI input) or computer monitor, as it will undoubtedly be easier and more intuitive for users to setup.

    Compatible HDMI Cable

    If you don't have an HDMI cable (and possible adapter), these have been tested to work with following Raspberry Pi models:

    Raspberry Pi Zero W model:
    Mini HDMI Cable - 3ft

    Mini HDMI Cable - 3ft

    CAB-14274
    $4.95
    2
    Raspberry Pi 3 A+/B+ models:
    HDMI Cable - 6ft

    HDMI Cable - 6ft

    CAB-11572
    $4.95
    1
    Raspberry Pi 4 models:
    Micro HDMI Cable - 3ft

    Micro HDMI Cable - 3ft

    CAB-15796
    $5.95

    Note: If your display doesn't have an HDMI input, you will need to source an appropriate adapter. There are DVI and VGA to HDMI adapters, that will work on older computer monitors. Unfortunately, we don't have any adapters or a list of optional products for more outdated inputs (i.e. RCA, S-video, Component, or coaxial inputs).

    USB Keyboard and Mouse

    If you don't already have a USB keyboard and mouse, we do offer a multimedia keyboard that has been tested as a plug-and-play option for the Raspberry Pi models in our catalog.

    Multimedia Wireless Keyboard

    Multimedia Wireless Keyboard

    WIG-14271
    $29.95
    3

    Note: This keyboard is similar to a smaller laptop form factor in the button layout. Users with the Raspberry Pi Zero W models will need an additional USB (OTG) cable.

    Raspberry Pi Kits

    Additionally, we do offer Raspberry Pi kits, which will include some of the accessories first-time users may already need.

    Raspberry Pi 3 B+ Starter Kit

    Raspberry Pi 3 B+ Starter Kit

    KIT-15361
    $91.95
    SparkFun Raspberry Pi 4 Basic Kit - 4GB

    SparkFun Raspberry Pi 4 Basic Kit - 4GB

    KIT-16384
    $89.95
    SparkFun Raspberry Pi Zero W Basic Kit

    SparkFun Raspberry Pi Zero W Basic Kit

    KIT-14298
    $39.95
    3
    SparkFun Raspberry Pi 4 Basic Kit - 2GB

    SparkFun Raspberry Pi 4 Basic Kit - 2GB

    KIT-16383
    $74.95

    Suggested Reading

    Note: First time users should also head over to the Raspberry Pi Foundation website and check out their quickstart guides:

    We have also listed a few additional resources for users to familiarize themselves with the Raspberry Pi:

    Below are some of our Raspberry Pi related tutorials that may be of interest to beginners:

    Serial Peripheral Interface (SPI)

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

    Logic Levels

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

    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.

    SD Cards and Writing Images

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

    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.

    Headless Raspberry Pi Setup

    Configure a Raspberry Pi without a keyboard, mouse, or monitor.

    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.

    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.

    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.

    Hardware Overview

    Below, is an overview of all the hardware included on the Top pHAT.

    Dimensions

    The overall dimensions of the Top pHAT are 56mm x 85mm. Don't forget to account for the small overhang of the display's ribbon cable, which wraps around the left edge of the board. For more details, users can check out the layout in the Eagle files.

    Dimensions
    Dimensions of the Top pHAT. (Click to enlarge)

    GPIO Connections

    As the Top pHAT is also intended to integrate with other HATs, it is important to know all of the pin being utilized to avoid conflicts. Below is a layout of all the GPIO pins being utilized by the hardware on the Top pHAT.

    Top pHAT GPIO
    GPIO header connection on the bottom of the Top pHAT. (Click to enlarge)

    Raspberry Pi GPIO Map

    GPIO PinsStandard GPIO layout on the Raspberry Pi.

    Power Connections

    Power to the Top pHAT is supplied through the GPIO pins; both 5V and 3.3V are utilized.

    Pin #GPIO
    13.3V
    173.3V
    25V
    45V
    6GND
    9GND
    Pin #GPIO
    14GND
    20GND
    30GND
    34GND
    39GND

    WM8960 Stereo CODEC (I2S)

    Pin #GPIOFunction
    12GPIO 18 (PCM_CLK)BCLK
    35GPIO 19 (PCM_FS)DAC-LRC
    38GPIO 20 (PCM_DIN)ADC-DAT
    40GPIO 21 (PCM_DOUTDAC-DAT

    WS2812 RGB LEDs

    Pin #GPIOFunction
    32GPIO 12 (PWM0)Data In

    2.4” TFT LCD Display (SPI)

    Pin #GPIOFunction
    15GPIO 22Backlight
    16GPIO 23RESET
    18GPIO 24DC
    19GPIO 10 (MOSI)SDI
    21GPIO 09 (MISO)SDO
    23GPIO 11 (SCLK)SCK
    24GPIO 08 (CE0)CS

    Qwiic (I2C)

    Qwiic Connector
    Pin #GPIOFunction
    3GPIO 02 (SDA)Qwiic (SDA)
    5GPIO 03 (SCL)Qwiic (SCL)


    Button Controller (I2C)
    Pin #GPIOFunction
    3GPIO 02 (SDA)Qwiic (SDA)
    5GPIO 03 (SCL)Qwiic (SCL)
    22GPIO 25Button Interrupt

    Audio (I2S)

    There are four audio components on the Top pHAT; an audio codec, two MEMs microphones, and a speaker. They controlled by the Raspberry Pi using an I2S protocol. The WM8960 stereo codec is the driver behind the audio components. It is used to both drive the speaker output and to control the microphone interface. The MEMs microphones and speaker are used as the input and output components of the audio interface.

    Top pHAT Audio
    Audio components on the Top pHAT.

    2.4" TFT LCD Display (SPI)

    The screen on the Top pHAT is most prevalent component on the Top pHAT. The 2.4" TFT LCD Display has a native resolution of 240 x 320 pixels and is backlit by four LEDs. The screen can be replaced using the 40 Pin 0.5mm FPC connector on the bottom of the Top pHAT. (*When replacing the screen, users should verify the replacement has the appropriate connections, driver, and configured in the operating system.)

    Top pHAT ScreenScreen on the Top pHAT.
    Top pHAT Screen CableFPC connector for the screen on the bottom of the Top pHAT.
    Note: On the initial released of this product, users may notice that the ribbon cable looks different than what is pictured. That is due to a supply issue; users will have the 2.4" TFT LCD (Touch) Display. This is a drop in replacement screen with an added touch capacity. (The touch is not functional as pins are not broken out.)

    WS2812 RGB LEDs

    There are six addressable RGB WS2812 LEDs on the board. These can be used as indicators, for when you might be too far way to read the screen, but it is still in your line of sight. These LEDs can get very bright; therefore, we recommend using a lower brightness setting.

    Top pHAT LEDs
    ⚡ Note: The LEDs can draw a decent amount of current at full brightness; ~50mA each for a total of 300mA. This is important as users can brown out their Raspberry Pi if the total current draw exceeds the capacity of the power supply.

    Qwiic (I2C)

    Qwiic is the name of our simple to use connector for I2C devices. It provides a simple, solderless, and polarized connection that should be impossible to mess up. (In case you were wondering, Qwiic is a play on words between quick and I2C.)

    Button Controller

    Although not an official Qwiic device, the button controller is accessed through the I2C interface. The controller is an ATtiny84, which emulates an I2C slave device and is used to read the 5-way switch and two momentary buttons. An interrupt pin is available for more immediate responses.

    Top pHAT Buttons

    Qwiic Connector

    A connector is provided for attaching other Qwiic devices.

    Top pHAT Qwiic Connector
    Note: While most of our Qwiic devices should be compatible with the Raspberry Pi, not all have a supported Python package.

    Hardware Assembly

    Assembly for the Top pHAT is fairly straight forward. It plugs directly into the GPIO pins of a Raspberry Pi. Most importantly, users need pay attention to the orientation of the pHAT and double check that the pin are lined up properly. below are a few examples for users to follow.

    Pi3A with Top pHAT
    Top pHAT on Pi 3 Model A+.
    Pi3B with Top pHAT
    Top pHAT on Pi 3 Model B.
    Pi4B with Top pHAT
    Top pHAT on Pi 4 Model B.
    (Click images to enlarge)

    If the clearance between the pHAT and the Raspberry Pi components (including things like a case or heat sink) becomes and issue, a header can be used to increase the spacing.

    Adding header
    Adding header to extend clearance between Top pHAT and other components. (Click to enlarge)

    Header on Pi3B
    Header on Pi 3 Model B. (Click to enlarge)
    Header on Pi4B
    Header on Pi 4 Model B. (Click to enlarge)

    To configure the Raspberry Pi for use with the Top pHAT, the PIXEL desktop is recommended. It will be the most convenient for users, but users can still use other methods like SSH to remotely access the Raspberry Pi. To utilize the desktop, users will need to add peripherals like a monitor and keyboard.

    Pi3B desktop setup
    Pi 3 Model B setup to access the PIXEL desktop.
    Pi4B desktop setup
    Pi 4 Model B setup to access the PIXEL desktop.
    (Click images to enlarge)

    OS Configuration: Part 1

    Configuring the Raspbian OS for the Top pHAT is relatively simple. The SPI and I2C interfaces need to be enabled along with the overscan disabled. (Users wishing to use the screen on boot will also need to configure the OS to boot to the CLI and run the frame buffer mapping script on startup. Directions will be laid out in OS Configuration: Part 2; however, users should do this last.)

    Configuration Methods

    There are 2 primary methods for configuring the Raspbian OS. Within the Raspberry Pi PIXEL desktop, the graphical Raspberry Pi Configuration application from the Preferences menu is the most user friendly option. Users can also make changes through the console based raspi-config application.

    configuration app

    Raspberry Pi Configuration application. (Click to enlarge)

    raspi-config tool

    raspi-config application. (Click to enlarge)

    (*For more details on the operating system configuration, check out the Raspberry Pi Foundation website.)

    Disable Overscan

    Users will want to disable overscan through the System or Advanced Options menus.

    Raspberry Pi Configuration Application

    On the main System tab, disable the Overscan and then move on to the next section to enable the SPI and I2C interfaces.

    config app system menu
    Disabling the overscan through the Raspberry Pi Configuration application.

    Raspi-Config Application

    From the 7 Advanced Options menu, select the A2 Overscan option and then follow the prompts to disable the overscan. Move on the next section to enable the SPI and I2C interfaces.

    raspi-config advanced options menu
    Selecting the Advanced Options menu in the console based raspi-config application. (Click to enlarge)

    raspi-config disable overscan
    Selecting the Overscan option to disable it, using the prompts. (Click to enlarge)

    Enable SPI and I2C

    Users will need to enable both the SPI and I2C interfaces through the Interface menu.

    Raspberry Pi Configuration Application

    From the Interfaces tab, enable both the SPI and I2C interfaces.

    config app interface menu
    Enabling the SPI and I2C interfaces through the Raspberry Pi Configuration application.

    Once done, click the OK button. Reboot the Raspberry Pi when prompted.

    Raspi-Config Application

    From the 5 Interfaces Options menu, select the P4 SPI option and then follow the prompts to enable the interface.

    raspi-config interface menu
    Selecting the Interfaces Options menu in the console based raspi-config application. (Click to enlarge)

    enable spi
    Selecting the SPI option to enable the interface, using the prompts. (Click to enlarge)

    Repeat the previous steps, but select the P5 I2C option; again, following the prompts to enable the interface.

    enable i2c
    Selecting the I2C option to enable the interface, using the prompts. (Click to enlarge)

    Once completed, use the Tab key to select the <Finish> button. Reboot the Raspberry Pi when prompted.

    Button Controller

    Note: This tutorial assumes you are using the latest version of Python 3. If this is your first time using Python or I2C hardware on a Raspberry Pi, please checkout our tutorial on Python Programming with the Raspberry Pi and the Raspberry Pi SPI and I2C Tutorial.

    We've written a Python package to easily get setup and take readings from the button controller on the Top pHAT. There are two methods for installing the Python package for the button controller.

    1. Install the all inclusive SparkFun Qwiic Python package.
    2. Independently install the SparkFun Top pHAT Button Python package.

    The all inclusive SparkFun Qwiic Python package, is recommended as is also installs the required I2C driver as well.

    Note: Don't forget to double check that the hardware I2C connection is enabled on your Raspberry Pi or other single board computer.

    SparkFun Qwiic Package

    This repository is hosted on PyPi as the sparkfun-top-phat-button package. On systems that support PyPi installation via pip3 (use pip for Python 2) is simple, using the following commands:

    For all users (note: the user must have sudo privileges):

    language:bash
    sudo pip3 install sparkfun-qwiic
    

    For the current user:

    language:bash
    pip3 install sparkfun-qwiic
    

    Independent Installation

    You can install the sparkfun-top-phat-button Python package independently, which is hosted by PyPi. However, if you prefer to manually download and install the package from the GitHub repository, you can grab them here (*Please be aware of any package dependencies. You can also check out the repository documentation page, hosted on ReadtheDocs.):

    PyPi Installation

    This repository is hosted on PyPi as the sparkfun-top-phat-button package. On systems that support PyPi installation via pip3 (use pip for Python 2) is simple, using the following commands:

    For all users (note: the user must have sudo privileges):

    language:bash
    sudo pip3 install sparkfun-top-phat-button
    

    For the current user:

    language:bash
    pip3 install sparkfun-top-phat-button
    

    Local Installation

    To install, make sure the setuptools package is installed on the system.

    Direct installation at the command line (use python for Python 2):

    language:bash
    python3 setup.py install
    

    To build a package for use with pip3:

    language:bash
    python3 setup.py sdist
    

    A package file is built and placed in a subdirectory called dist. This package file can be installed using pip3.

    language:bash
    cd dist
    pip3 install sparkfun_top_phat_button-<version>.tar.gz
    

    Python Package Operation

    Before we jump into getting readings, let's take a closer look at the available functions in the Python package. Below, is a description of the basic functionality of the Python package. This includes the package organization, built-in methods, and their inputs and/or outputs. For more details on how the Python package works, check out the source code, the firmware, and package documentation.

    Dependencies

    This Python package has a very few dependencies in the code, listed below:

    language:python
    from __future__ import print_function
    import qwiic_i2c
    

    Default Variables

    The default variables, in the code, for this Python package are listed below:

    language:python
    # Some devices have multiple availabel addresses - this is a list of these addresses.
    # NOTE: The first address in this list is considered the default I2C address for the
    # device.
    _AVAILABLE_I2C_ADDRESS = [0x71]
    
    # Register codes for the Joystick
    BUTTON_ID               = 0x00
    BUTTON_VERSION1         = 0x01
    BUTTON_VERSION2         = 0x02
    BUTTON_PRESSED          = 0x03
    BUTTON_CLICKED          = 0x04
    BUTTON_INTERRUPT        = 0x05
    BUTTON_DEBOUNCE         = 0x06
    BUTTON_CHANGE_ADDREESS  = 0x1F
    
    # Define the bit positions of the buttons and interrupt flag
    A                     = 0
    B                     = 1
    UP                    = 2
    DOWN                  = 3
    LEFT                  = 4
    RIGHT                 = 5
    CENTER                = 6
    EVENT_AVAILABLE       = 7
    
    # Define the positions of the Interrupt Enable Bits
    CLICKED_INTERRUPT_ENABLE        = 0
    PRESSED_INTERRUPT_ENABLE        = 1
    

    Class

    ToppHATButton() or ToppHATButton(address)
    This Python package operates as a class object, allowing new instances of that type to be made. An __init__() constructor is used that creates a connection to an I2C device over the I2C bus using the default or specified I2C address.

    The Constructor

    A constructor is a special kind of method used to initialize (assign values to) the data members needed by the object when it is created.

    __init__(address=None, i2c_driver=None):

    Input: value
    The value of the device address. If not defined, the Python package will use the default I2C address (0x71) stored under _AVAILABLE_I2C_ADDRESS variable.
    Input: i2c_driver
    Loads the specified I2C driver; by default the Qwiic I2C driver is used: qwiic_i2c.getI2CDriver(). Users should use the default I2C driver and leave this field blank.

    Functions

    A function that is an attribute of the class, which defines a method for instances of that class. In simple terms, they are objects for the operations (or methods) of the class.

    .is_connected()
    Determines if the button controller device is connected to the system.

    Output: Boolean

    True: Connected to I2C device on the default (or specified) address.
    False: No device found or connected.

    .begin()
    Initialize the operation of the button controller. (Basically tests the connection to the button controller.)

    Output: Boolean

    True: The initialization was successful.
    False: Initialization failed.

    .get_button_pressed()
    Updates and returns buffer for all buttons and whether or not they are pressed as well as the pressed interrupt flag.

        Reading this register also clears it.
        7(MSB)  6    5    4    3    2    1    0(LSB)
          INT  CTR  RGT  LFT  DWN   UP   B    A
    

    Returns 1 bit when a button is currently being pressed, based on the mapping above. The interrupt must be cleared by the user.

    Output: Integer

    0: No interrupt; no buttons currently pressed.
    1: No interrupt; only Button A is currently being pressed.
    2: No interrupt; only Button B is currently being pressed.
    3: No interrupt; Button A and Button B are currently being pressed./br>...195: Interrupt; Button A and Button B are currently being pressed. The 5-way switch is currently being pressed with the Center pad.196-255: Are not possible as the 5-way switch cannot indicate multiple directions.

    .get_button_clicked()
    Updates and returns buffer for all buttons and whether or not they have been clicked as well as the clicked interrupt flag.

        Reading this register also clears it.
        7(MSB)  6    5    4    3    2    1    0(LSB)
          INT  CTR  RGT  LFT  DWN   UP   B    A
    

    Returns 1 when a button has received a full click cycle (press and release). The interrupt must be cleared by the user.

    Output: Integer

    0: No interrupt; no buttons were clicked.
    1: No interrupt; only Button A was clicked.
    2: No interrupt; only Button B was clicked.
    3: No interrupt; Button A and Button B were clicked....254: Interrupt; Button B was clicked. The 5-way switch, was clicked in all directions, including the Center pad.255: Interrupt; Button A and Button B were clicked. The 5-way switch, was clicked in all directions, including the Center pad.

    .get_version()
    Returns a string of the firmware version number.

    Output: String

    The firmware version

    .get_pressed_interrupt()
    Returns the status of the pressed interrupt enable.

    Output: Boolean

    The value of the interrupt enable bit.

    .set_pressed_interrupt(bit_setting)
    Sets the status of the pressed interrupt enable bit.

    Input: Boolean

    0: The pressed interrupt enable bit.
    1: The pressed interrupt enable bit.

    Output: Boolean

    0: I2C transaction failed, the interrupt enable bit wasn't set.
    1: I2C transaction succeeded, the interrupt enable bit was set.

    .get_clicked_interrupt()
    Returns the status of the clicked interrupt enable.

    Output: Boolean

    The value of the clicked interrupt enable bit.

    .set_clicked_interrupt(bit_setting)
    Sets the status of the clicked interrupt enable bit.

    Input: Boolean

    0: The clicked interrupt enable bit.
    1: The clicked interrupt enable bit.

    Output: Boolean

    0: I2C transaction failed, the interrupt enable bit wasn't set.
    1: I2C transaction succeeded, the interrupt enable bit was set.

    Upgrading the Python Package

    In the future, changes to the Python package might be made. Updating the installed packages has to be done individually for each package (i.e. sub-modules and dependencies won't update automatically and must be updated manually). For the sparkfun-top-phat-button Python package, use the following command (use pip for Python 2):

    For all users (note: the user must have sudo privileges):

    language:bash
    sudo pip3 install --upgrade sparkfun-top-phat-button
    

    For the current user:

    language:bash
    pip3 install --upgrade sparkfun-top-phat-button
    

    Python Examples

    There are two examples written for the Top pHAT using this Python package. They can be found in the GitHub repository or viewed in the ReadtheDocs documentation

    Example 1

    Example 1 utilizes the interrupt for more immediate responses.

    #!/usr/bin/env python
    #-----------------------------------------------------------------------------
    # top_phat_button_ex1.py
    #
    # Polling example for the Top pHAT Buttons
    #------------------------------------------------------------------------
    #
    # Written by  SparkFun Electronics, April 2020
    # 
    # This python library supports the SparkFun Electroncis qwiic 
    # qwiic sensor/board ecosystem on a Raspberry Pi (and compatable) single
    # board computers. 
    #
    # More information on qwiic is at https://www.sparkfun.com/qwiic
    #
    # Do you like this library? Help support SparkFun. Buy a board!
    #
    #==================================================================================
    # Copyright (c) 2019 SparkFun Electronics
    #
    # Permission is hereby granted, free of charge, to any person obtaining a copy 
    # of this software and associated documentation files (the "Software"), to deal 
    # in the Software without restriction, including without limitation the rights 
    # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
    # copies of the Software, and to permit persons to whom the Software is 
    # furnished to do so, subject to the following conditions:
    #
    # The above copyright notice and this permission notice shall be included in all 
    # copies or substantial portions of the Software.
    #
    # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
    # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
    # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
    # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
    # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
    # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 
    # SOFTWARE.
    #==================================================================================
    # Example 1
    #
    
    from __future__ import print_function
    import top_phat_button
    import time
    import sys
    
    myButtons = top_phat_button.ToppHATButton()
    
    def runExample():
    
        print("\nSparkFun Top pHAT Button  Example 1\n")
    
        if myButtons.is_connected() == False:
            print("The Top pHAT Button device isn't connected to the system. Please check your connection", \
                file=sys.stderr)
            return
    
        myButtons.pressed_interrupt_enable = False
        myButtons.clicked_interrupt_enable = False
    
        while True:
            myButtons.button_pressed #These functions must be called to update button variables to their latest setting
            myButtons.button_clicked #These functions must be called to update button variables to their latest setting  
            if myButtons.a_pressed == True:
                print("A Pressed")
            if myButtons.a_clicked == True:
                print("A Released")
            if myButtons.b_pressed == True:
                print("B Pressed")
            if myButtons.b_clicked == True:
                print("B Released")
            if myButtons.up_pressed == True:
                print("Up Pressed")
            if myButtons.up_clicked == True:
                print("Up Released")
            if myButtons.down_pressed == True:
                print("Down Pressed")
            if myButtons.down_clicked == True:
                print("Down Released")
            if myButtons.left_pressed == True:
                print("Left Pressed")
            if myButtons.left_clicked == True:
                print("Left Released")
            if myButtons.right_pressed == True:
                print("Right Pressed")
            if myButtons.right_clicked == True:
                print("Right Released")
            if myButtons.center_pressed == True:
                print("Center Pressed")
            if myButtons.center_clicked == True:
                print("Center Released")
    
            time.sleep(.1)
    
    
    if __name__ == '__main__':
        try:
            runExample()
        except (KeyboardInterrupt, SystemExit) as exErr:
            print("\nEnding Example 1")
            sys.exit(0)
    

    Example 2

    Example 2 doesn't utilize the interrupt and must constantly ping the button controller for updates on potential actions performed on the buttons.

    #!/usr/bin/env python
    #-----------------------------------------------------------------------------
    # top_phat_button_ex2.py
    #
    # Interrupt example for the Top pHAT Buttons
    #------------------------------------------------------------------------
    #
    # Written by  SparkFun Electronics, April 2020
    # 
    # This python library supports the SparkFun Electroncis qwiic 
    # qwiic sensor/board ecosystem on a Raspberry Pi (and compatable) single
    # board computers. 
    #
    # More information on qwiic is at https://www.sparkfun.com/qwiic
    #
    # Do you like this library? Help support SparkFun. Buy a board!
    #
    #==================================================================================
    # Copyright (c) 2019 SparkFun Electronics
    #
    # Permission is hereby granted, free of charge, to any person obtaining a copy 
    # of this software and associated documentation files (the "Software"), to deal 
    # in the Software without restriction, including without limitation the rights 
    # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
    # copies of the Software, and to permit persons to whom the Software is 
    # furnished to do so, subject to the following conditions:
    #
    # The above copyright notice and this permission notice shall be included in all 
    # copies or substantial portions of the Software.
    #
    # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
    # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
    # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
    # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
    # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
    # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 
    # SOFTWARE.
    #==================================================================================
    # Example 2
    #
    
    from __future__ import print_function
    import top_phat_button
    import time
    import sys
    import RPi.GPIO as GPIO
    
    INTERRUPT_PIN = 25
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(INTERRUPT_PIN, GPIO.IN)
    
    myButtons = top_phat_button.ToppHATButton()
    
    def interruptCallback(channel):
        myButtons.button_pressed
        myButtons.button_clicked #Both interrupts are configured, so we need to read both registers to clear the interrupt and update our button data.   
        if myButtons.a_pressed == True:
            print("A Pressed")
        if myButtons.a_clicked == True:
            print("A Released")
        if myButtons.b_pressed == True:
            print("B Pressed")
        if myButtons.b_clicked == True:
            print("B Released")
        if myButtons.up_pressed == True:
            print("Up Pressed")
        if myButtons.up_clicked == True:
            print("Up Released")
        if myButtons.down_pressed == True:
            print("Down Pressed")
        if myButtons.down_clicked == True:
            print("Down Released")
        if myButtons.left_pressed == True:
            print("Left Pressed")
        if myButtons.left_clicked == True:
            print("Left Released")
        if myButtons.right_pressed == True:
            print("Right Pressed")
        if myButtons.right_clicked == True:
            print("Right Released")
        if myButtons.center_pressed == True:
            print("Center Pressed")
        if myButtons.center_clicked == True:
            print("Center Released")
    
    GPIO.add_event_detect(INTERRUPT_PIN, GPIO.FALLING, callback=interruptCallback, bouncetime=5)
    
    def runExample():
    
        print("\nSparkFun Top pHAT Button  Example 1\n")
    
        if myButtons.is_connected() == False:
            print("The Top pHAT Button device isn't connected to the system. Please check your connection", \
                file=sys.stderr)
            return
    
        myButtons.pressed_interrupt_enable = True
        myButtons.clicked_interrupt_enable = True #Enable both hardware interrupts
    
        while True:
    
            time.sleep(.1)
    
    
    if __name__ == '__main__':
        try:
            runExample()
        except (KeyboardInterrupt, SystemExit) as exErr:
            print("\nEnding Example 1")
            sys.exit(0)
    

    WS2812B LEDs

    Note: This tutorial assumes you are using the latest version of Python 3. If this is your first time using Python or I2C hardware on a Raspberry Pi, please checkout our tutorial on Python Programming with the Raspberry Pi and the Raspberry Pi SPI and I2C Tutorial.

    For the addressable LEDs, we will be using Adafruit's neopixel python package. The adafruit-circuitpython-neopixel Python package is hosted on PyPi.

    PyPi Installation

    On systems that support PyPi installation via pip3 (use pip for Python 2) is simple, using the following commands:

    For all users (note: the user must have sudo privileges):

    language:bash
    sudo pip3 install adafruit-circuitpython-neopixel
    

    For the current user:

    language:bash
    pip3 install adafruit-circuitpython-neopixel
    
    Note: Based on our experience, for users to access the GPIO functionality, they will need to install the python package using the sudo command.

    Python Examples

    Before users jump into operating the LEDs, it is recommended that they review the the Read the Docs documentation for the Python package and datasheet for the WS2812B LEDs. Below are a few examples for using the LEDs on the Top pHAT; don't forget that the LEDs are attached to pin 12 and

    Note: Based on our experience, users should start with a brightness setting of around 10. The LEDs are fairly bright and can leave users "seeing spots" at full brightness.

    Example 1

    This is a basic example setting the first, fourth, and fifth LEDs. The array is RGB, with the value indicating the brightness magnitude (0-255).

    language:python
    # Import Dependencies
    import board
    import neopixel
    
    # Create the class object
    pixels = neopixel.NeoPixel(board.D12, 6, auto_write=False)
    
    # Set Pixel Configuration
    pixels[0] = (10, 0, 0)
    pixels[3] = (0, 10, 0)
    pixels[4] = (0, 0, 10)
    
    # Display Configuration
    pixels.show()
    

    Example 2

    This is a basic example cycles through the LEDs individually setting them green.

    language:python
    # Import Dependencies
    import board
    import neopixel
    import time
    
    # Create the class object
    pixels = neopixel.NeoPixel(board.D12, 6)
    
    while True:
        for i in range(6):
            # Clear previous LED
            if i == 0:
                pixels[5] = (0,0,0)
            else:
                pixels[i-1]=(0,0,0)
    
            # Set LED green
            pixels[i]=(0,10,0)
    
            # Delay
            time.sleep(.2)
    

    WM8690 Audio Codec

    Getting the audio components up an operational involves two steps; installing the driver for the WM8960 audio codec and configuring the default sound card in the OS. We will be following the installation instructions from Waveshare for their Audio HAT.

    Audio Codec Driver

    To install the driver for the WM8960 audio codec, enter the following lines into the terminal or CLI.

    language:bash
    git clone https://github.com/waveshare/WM8960-Audio-HAT
    cd WM8960-Audio-HAT
    sudo ./install.sh
    sudo reboot
    

    If the installation is done properly, the output in the terminal should look like this:

    language:bash
    pi@raspberrypi:~ $ git clone https://github.com/waveshare/WM8960-Audio-HAT
    Cloning into 'WM8960-Audio-HAT'...
    remote: Enumerating objects: 3, done.
    remote: Counting objects: 100% (3/3), done.
    remote: Compressing objects: 100% (3/3), done.
    remote: Total 51 (delta 0), reused 0 (delta 0), pack-reused 48
    Unpacking objects: 100% (51/51), done.
    
    pi@raspberrypi:~ $ cd WM8960-Audio-HAT
    
    pi@raspberrypi:~ $ sudo ./install.sh
    
    pi@raspberrypi:~/WM8960-Audio-HAT $ sudo ./install.sh
    Get:1 http://archive.raspberrypi.org/debian stretch InRelease [25.4 kB]
    Get:2 http://raspbian.raspberrypi.org/raspbian stretch InRelease [15.0 kB]
    Get:3 http://archive.raspberrypi.org/debian stretch/main armhf Packages [220 kB]
    Get:4 http://raspbian.raspberrypi.org/raspbian stretch/main armhf Packages [11.7 MB]
    Fetched 11.9 MB in 17s (699 kB/s)
    Reading package lists... Done
    Building dependency tree
    Reading state information... Done
    52 packages can be upgraded. Run 'apt list --upgradable' to see them.
    Reading package lists... Done
    Building dependency tree
    Reading state information... Done
    raspberrypi-kernel is already the newest version (1.20190819~stretch-1).
    raspberrypi-kernel-headers is already the newest version (1.20190819~stretch-1).
    0 upgraded, 0 newly installed, 0 to remove and 52 not upgraded.
    1 not fully installed or removed.
    After this operation, 0 B of additional disk space will be used.
    Setting up python-sense-emu (1.1) ...
    Traceback (most recent call last):
      File "/usr/bin/pycompile", line 35, in <module>
        from debpython.version import SUPPORTED, debsorted, vrepr, \
      File "/usr/share/python/debpython/version.py", line 24, in <module>
        from ConfigParser import SafeConfigParser
    ImportError: No module named 'ConfigParser'
    dpkg: error processing package python-sense-emu (--configure):
     subprocess installed post-installation script returned error exit status 1
    Errors were encountered while processing:
     python-sense-emu
    E: Sub-process /usr/bin/dpkg returned an error code (1)
    Reading package lists... Done
    Building dependency tree
    Reading state information... Done
    dkms is already the newest version (2.3-2).
    i2c-tools is already the newest version (3.1.2-3).
    i2c-tools set to manually installed.
    Suggested packages:
      git-daemon-run | git-daemon-sysvinit git-doc git-el git-email git-gui gitk gitweb git-arch git-cvs git-mediawiki
      git-svn
    The following NEW packages will be installed:
      libasound2-plugins
    The following packages will be upgraded:
      git
    1 upgraded, 1 newly installed, 0 to remove and 51 not upgraded.
    1 not fully installed or removed.
    Need to get 3,462 kB of archives.
    After this operation, 293 kB of additional disk space will be used.
    Get:1 http://mirror.sjc02.svwh.net/raspbian/raspbian stretch/main armhf git armhf 1:2.11.0-3+deb9u5 [3,389 kB]
    Get:2 http://mirror.sjc02.svwh.net/raspbian/raspbian stretch/main armhf libasound2-plugins armhf 1.1.1-1 [72.9 kB]
    Fetched 3,462 kB in 1s (2,536 kB/s)
    apt-listchanges: Reading changelogs...
    (Reading database ... 141372 files and directories currently installed.)
    Preparing to unpack .../git_1%3a2.11.0-3+deb9u5_armhf.deb ...
    Unpacking git (1:2.11.0-3+deb9u5) over (1:2.11.0-3+deb9u4) ...
    Selecting previously unselected package libasound2-plugins:armhf.
    Preparing to unpack .../libasound2-plugins_1.1.1-1_armhf.deb ...
    Unpacking libasound2-plugins:armhf (1.1.1-1) ...
    Setting up python-sense-emu (1.1) ...
    Traceback (most recent call last):
      File "/usr/bin/pycompile", line 35, in <module>
        from debpython.version import SUPPORTED, debsorted, vrepr, \
      File "/usr/share/python/debpython/version.py", line 24, in <module>
        from ConfigParser import SafeConfigParser
    ImportError: No module named 'ConfigParser'
    dpkg: error processing package python-sense-emu (--configure):
     subprocess installed post-installation script returned error exit status 1
    Setting up libasound2-plugins:armhf (1.1.1-1) ...
    Setting up git (1:2.11.0-3+deb9u5) ...
    Errors were encountered while processing:
     python-sense-emu
    E: Sub-process /usr/bin/dpkg returned an error code (1)
    
    Creating symlink /var/lib/dkms/wm8960-soundcard/1.0/source ->
                     /usr/src/wm8960-soundcard-1.0
    
    DKMS: add completed.
    
    Kernel preparation unnecessary for this kernel.  Skipping...
    
    Building module:
    cleaning build area....
    make -j4 KERNELRELEASE=4.19.66-v7+ -C /lib/modules/4.19.66-v7+/build M=/var/lib/dkms/wm8960-soundcard/1.0/build............
    cleaning build area....
    
    DKMS: build completed.
    
    snd-soc-wm8960:
    Running module version sanity check.
     - Original module
       - No original module exists within this kernel
     - Installation
       - Installing to /lib/modules/4.19.66-v7+/kernel/sound/soc/codecs/
    
    snd-soc-wm8960-soundcard.ko:
    Running module version sanity check.
     - Original module
       - No original module exists within this kernel
     - Installation
       - Installing to /lib/modules/4.19.66-v7+/kernel/sound/soc/bcm/
    
    depmod....
    
    DKMS: install completed.
    Created symlink /etc/systemd/system/sysinit.target.wants/wm8960-soundcard.service → /lib/systemd/system/wm8960-soundcard.service.
    ------------------------------------------------------
    Please reboot your raspberry pi to apply all settings
    Enjoy!
    ------------------------------------------------------
    
    pi@raspberrypi:~ $ sudo reboot
    

    Driver Installation Verification

    To verify that the audio driver installation was successful and the kernel was rebuilt, use the sudo dkms status command in the terminal or CLI. Users should a response similar to:

    language:bash
    wm8960-soundcard, 1.0, 4.19.66-v7+, armv7l: installed
    

    Playback Devices

    For further verification, users can list the playback devices using the aplay -l command in the terminal or CLI. Users should a response similar to:

    language:bash
    **** List of PLAYBACK Hardware Devices ****
    card 0: wm8960soundcard [wm8960-soundcard], device 0: bcm2835-i2s-wm8960-hifi wm8960-hifi-0 []
      Subdevices: 1/1
      Subdevice #0: subdevice #0
    card 1: ALSA [bcm2835 ALSA], device 0: bcm2835 ALSA [bcm2835 ALSA]
      Subdevices: 7/7
      Subdevice #0: subdevice #0
      Subdevice #1: subdevice #1
      Subdevice #2: subdevice #2
      Subdevice #3: subdevice #3
      Subdevice #4: subdevice #4
      Subdevice #5: subdevice #5
      Subdevice #6: subdevice #6
    card 1: ALSA [bcm2835 ALSA], device 1: bcm2835 IEC958/HDMI [bcm2835 IEC958/HDMI]
      Subdevices: 1/1
      Subdevice #0: subdevice #0
    card 1: ALSA [bcm2835 ALSA], device 2: bcm2835 IEC958/HDMI1 [bcm2835 IEC958/HDMI1]
      Subdevices: 1/1
      Subdevice #0: subdevice #0
    card 2: vc4hdmi [vc4-hdmi], device 0: MAI PCM vc4-hdmi-hifi-0 []
      Subdevices: 1/1
      Subdevice #0: subdevice #0
    

    The important information users need to identify is the card number listed for the WM8960:

    card 0:wm8960soundcard [wm8960-soundcard], device 0: bcm2835-i2s-wm8960-hifi wm8960-hifi-0 []

    Capture Devices

    For further verification, users can also list the capture devices using the arecord -l command in the terminal or CLI. Users should a response similar to:

    language:bash
    **** List of CAPTURE Hardware Devices ****
    card 0: wm8960soundcard [wm8960-soundcard], device 0: bcm2835-i2s-wm8960-hifi wm8960-hifi-0 []
      Subdevices: 1/1
      Subdevice #0: subdevice #0
    

    The important information users need to identify is the card number listed for the WM8960:

    card 0:wm8960soundcard [wm8960-soundcard], device 0: bcm2835-i2s-wm8960-hifi wm8960-hifi-0 []

    Test

    To test that the speaker and microphone are working with the WM8960 audio codec, use the sudo arecord -f cd -D hw:0 | aplay -D hw:0 command in the terminal or CLI. This will cause the microphones to record and playback the audio to the mono speaker in real time. The entries for the hardware (hw:0) should correspond with the card number for the playback and capture devices. Users can also use the following commands to record and play files:

    • Record File: sudo arecord -D hw:0 -f S32_LE -r 16000 -c 2 test.wav
    • Play File: sudo aplay -D hw:0 test.wav

    Configure Default Sound Card

    The last part of the installation process requires the default sound card to be configured, using the sudo alsamixer command in the terminal or CLI. From the system menu, use the F6 key to list devices and note the number indicating the WM8960 sound card.

    List ALSA devices
    Listing the ALSA mixer devices with the F6 key. (Click to enlarge)

    To modify and configure the default sound card, use the sudo nano /usr/share/alsa/alsa.conf command in the terminal or CLI. In the alsa.conf file, users will modify the following lines to the number indicating the WM8960 sound card device value:

    language:bash
    defaults.ctl.card 0
    defaults.pcm.card 0
    defaults.pcm.device 0
    

    ALSA configuration
    Configuring the ALSA mixer defaults. (Click to enlarge)

    Note: Users may need to test the values for defaults.pcm.device between with 0 or 1. If they run into the following error:

    ALSA lib pcm_dmix.c:1108:(snd_pcm_dmix_open) unable to open slave
    Traceback (most recent call last):
      File "playwav.py", line 59, in 
        device = alsaaudio.PCM(device="default")
    alsaaudio.ALSAAudioError: No such file or directory [default]

    when running the Python playback code sudo python playwav.py test2.wav in the examples below.

    Once these modifications have been made, users should go back an verify that the modifications have taken effect, using the sudo alsamixer command in the terminal or CLI.

    ALSA configured
    ALSA mixer default device configured. (Click to enlarge)

    Python Examples

    In order to use the Python examples provided by Waveshare, users will need to install the libasound2-dev ALSA library and the pyalsaaudio Python package.

    • ALSA Library: sudo apt-get install libasound2-dev
    • Python Package: sudo pip3 install pyalsaaudio

    Users will need to download example code from the Waveshare website and extract the files:

    language:bash
    wget https://www.waveshare.com/w/upload/1/19/WM8960_Audio_HAT_Code.tar.gz
    tar -xzf WM8960_Audio_HAT_Code.tar.gz
    

    Once extracted, users will need to change the directory into the extracted folder. There they can use the following sample codes to record and play .wav files.

    • Record to File: sudo python3 recordwav.py test2.wav
    • Play File: sudo python3 playwav.py test2.wav

    Note: Users may run into a type error, when running the Python playback code sudo python playwav.py test2.wav:

    Traceback (most recent call last):
      File "playwav.py", line 61, in 
        play(device, f)
      File "playwav.py", line 35, in play
        device.setperiodsize(periodsize)
    TypeError: integer argument expected, got float

    The issue is in line 35 of the playwav.py file, which needs to be modified to periodsize = int(f.getframerate() / 8).

    2.4" TFT Display

    There are two steps for the modules required for the 2.4" TFT Screen; adding the driver modules and then a module configuration.

    Add Driver Modules

    Use your preferred text editor to add the required modules to /etc/modules. The example below uses nano with the following command: sudo nano /etc/modules.

    Add the following lines in the file:

    spi-bcm2835
    fbtft_device
    

    Add modules
    Adding modules for the screen. (Click to enlarge)

    Module Configuration

    Again, use your preferred text editor to add the required modules to /etc/modprobe.d/fbtft.conf.

    Add the following text to the file:

    options fbtft_device name=fb_ili9341 gpios=reset:23,dc:24 speed=16000000 bgr=1 rotate=180 custom=1

    Configure module
    Configuration for fbtft module. (Click to enlarge)

    Once these changes have been made, reboot the Raspberry Pi with the sudo reboot command for the changes to take effect.

    Screen Operation

    To utilize the screen, users will call the con2fbmap command. The command is followed by two inputs; the terminal to be displayed and the frame buffer, in that order.

    List Frame Buffer

    Get the input for the frame buffer, use the cat /proc/fb, it will list what the fb numbers are.

    Show frame buffers
    Listing frame buffers. (Click to enlarge)

    List Users and their Terminals

    To list the active users and their terminals, the who command can be used.

    List user terminals
    Listing active user terminals. (Click to enlarge)
    Note: Users cannot display a hardware terminal like the serial console on the screen.

    Examples

    Below is are some examples for using the screen. (*Don't forget to reboot the Raspberry Pi for the previous configurations to take effect.)

    • Display terminal on the TFT using the con2fbmap 1 1 command in the terminal or CLI. Then exit to the virtual terminal using Ctrl + Alt + F1.
    • To swap between the display and the HDMI output, use the startx command in the terminal or CLI initiate the PIXEL desktop through the HDMI output. To revert back to the display, click on Raspberry Pi icon -> Shutdown -> Exit to Commandline.
    • In order to utilize the display on startup, users can modify the /etc/rc.local file using the sudo nano /etc/rc.local command in the terminal or CLI. Users will need to add the con2fbmap 1 1 command just above the exit 0 entry.

    Screen operational
    Screen operating from boot. (Click to enlarge)
    Note: The HDMI can be hot plugged into a Raspberry Pi 3 only. On the Pi 4, an HDMI cable must be plugged in before booting.

    OS Configuration: Part 2

    Boot to CLI

    Users will want to configure the OS to boot to the console through the System or Boot Options menus, in order to utilize the screen on power up.

    Raspberry Pi Configuration Application

    config app system menu
    Configuring Boot to CLI through the Raspberry Pi Configuration application.

    Raspi-Config Application

    raspi-config boot options menu
    Selecting the Boot Options menu in the console based raspi-config application. (Click to enlarge)

    raspi-config Desktop/CLI menu
    Selecting the Desktop/CLI menu in the console based raspi-config application. (Click to enlarge)

    raspi-config Console Autologin option
    Selecting the Console Autologin option to configure the system to boot to the CLI. (Click to enlarge)

    Troubleshooting

    For comprehensive information or troubleshooting issues, on the Raspberry Pi, users should check out the Raspberry Pi Foundation website and their forum.

    As a general guideline, users should use the following resources when looking for technical information or assistance that is specifically related to the Raspberry Pi itself:

    1. Raspberry Pi FAQ
    2. Raspberry Pi Beginner's Subforum
    3. Raspberry Pi Documentation and Help Guides
    4. Raspberry Pi Forum

    For users looking for technical assistance, click on the link. There you will find, basic troubleshooting tips and instructions to get started with posting a topic in our forums. Our technical support team will do their best to assist you.

    Resources and Going Further

    Product Information

    Raspberry Pi Resources:

    Raspberry Pi Help Guides & Documentation:


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

    Raspberry Pi Safe Reboot and Shutdown Button

    $
    0
    0

    Raspberry Pi Safe Reboot and Shutdown Button a learn.sparkfun.com tutorial

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

    Introduction

    Pulling the plug on your Raspberry Pi... is a bad idea! This can result in a corrupt microSD card and file system. Normally, we can use the menu bar from the GUI or type a command in the terminal window to safely shutdown the Pi. If you are looking for a quicker solution (especially if you are using a headless setup), have no fear! You can safely reboot or shut down your Raspberry Pi using a general purpose button and a Python script!

    Configure the pHAT V2.0 GPIO Button to Safely Reboot and Shutdown Your Raspberry Pi

    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 and your setup. Add it to your cart, read through the guide, and adjust the cart as necessary.

    SparkFun Raspberry Pi 4 Basic Kit - 4GB

    SparkFun Raspberry Pi 4 Basic Kit - 4GB

    KIT-16384
    $89.95
    1
    Raspberry Pi LCD - 7" Touchscreen

    Raspberry Pi LCD - 7" Touchscreen

    LCD-13733
    $64.95
    41
    SparkFun Qwiic pHAT v2.0 for Raspberry Pi

    SparkFun Qwiic pHAT v2.0 for Raspberry Pi

    DEV-15945
    $5.95
    Multimedia Wireless Keyboard

    Multimedia Wireless Keyboard

    WIG-14271
    $29.95
    3

    Suggested Reading

    We would also recommend taking a look at the following tutorials if you aren't familiar with them.

    Raspberry Pi 4 Kit Hookup Guide

    March 14, 2020

    Guide for hooking up your Raspberry Pi 4 Model B basic kit together.

    Qwiic pHAT for Raspberry Pi Hookup Guide

    May 23, 2019

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

    Serial Terminal Basics

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

    Raspberry gPIo

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

    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.

    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.

    Hardware Hookup

    The connection is quick. If you have not already, simply stack the Qwiic pHAT v2.0 on top of your Raspberry Pi's GPIO header. If you are using an enclosure, you may need to have additional pair of stackable headers for a secure connection. The image below shows the pHAT v2.0 connecting to a Pi 3 with the help of stackable headers.

    Qwiic pHAT v2.0 stacked on Raspberry Pi

    For the scope of this tutorial, we'll using a desktop setup with a monitor, keyboard, and mouse to easily configure your Raspberry Pi. If you have not already, connect the necessary peripherals and power up your Pi!

    Example 1: Safe Shutdown

    For those familiar with the text based command line, we can shutdown the Pi using the following command.

    language:bash
    sudo shutdown -h -now
    

    The following example loads a Python script at startup and safely shuts down the Raspberry Pi using that command when the button connected to GPIO17 is pressed.

    Example Code

    On your Raspberry Pi, download the Python script by pressing the button below.

    You can also copy the code and paste it in a text editor. Just make sure to name this file as safe_shutdown_Pi.py and remember the location that the file was saved.

    language:python
    # safe_shutdown_Pi.py
    #
    # -----------------------------------------------------------------------------
    #                 Raspberry Pi Safe Shutdown Python Script
    # -----------------------------------------------------------------------------
    # WRITTEN BY: Ho Yun "Bobby" Chan
    # @ SparkFun Electronics
    # DATE: 3/31/2020
    #
    # Based on code from the following blog and tutorials:
    #
    #    Kevin Godden
    #    https://www.ridgesolutions.ie/index.php/2013/02/22/raspberry-pi-restart-shutdown-your-pi-from-python-code/
    #
    #    Pete Lewis
    #    https://learn.sparkfun.com/tutorials/raspberry-pi-stand-alone-programmer#resources-and-going-further
    #
    #    Shawn Hymel
    #    https://learn.sparkfun.com/tutorials/python-programming-tutorial-getting-started-with-the-raspberry-pi/experiment-1-digital-input-and-output
    #
    # ==================== DESCRIPTION ====================
    #
    # This python script takes advantage of the Qwiic pHat v2.0's
    # built-in general purpose button to safely reboot/shutdown you Pi:
    #
    #    1.) If you press the button momentarily, the Pi will shutdown.
    #
    # ========== TUTORIAL ==========
    #  For more information on running this script on startup,
    #  check out the associated tutorial to adjust your "rc.local" file:
    #
    #  https://learn.sparkfun.com/tutorials/
    #
    # ========== PRODUCTS THAT USE THIS CODE ==========
    #
    #   Feel like supporting our work? Buy a board from SparkFun!
    #
    #        Qwiic pHAT v2.0
    #        https://www.sparkfun.com/products/15945
    #
    #   You can also use any button but you would need to wire it up
    #   instead of stacking the pHAT on your Pi.
    #
    # LICENSE: This code is released under the MIT License (http://opensource.org/licenses/MIT)
    #
    # Distributed as-is; no warranty is given
    #
    # -----------------------------------------------------------------------------
    
    import time
    import RPi.GPIO as GPIO
    
    # Pin definition
    shutdown_pin = 17
    
    # Suppress warnings
    GPIO.setwarnings(False)
    
    # Use "GPIO" pin numbering
    GPIO.setmode(GPIO.BCM)
    
    # Use built-in internal pullup resistor so the pin is not floating
    GPIO.setup(shutdown_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    
    # modular function to shutdown Pi
    def shut_down():
        print "shutting down"
        command = "/usr/bin/sudo /sbin/shutdown -h now"
        import subprocess
        process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
        output = process.communicate()[0]
        print output
    
    # Check button if we want to shutdown the Pi safely
    while True:
    
        # For troubleshooting, uncomment this line to output buton status on command line
        #print GPIO.input(shutdown_pin)
        if GPIO.input(shutdown_pin)== False:
            shut_down()
    

    Setting Up the Path

    This will be saved in your Downloads folder. Once downloaded, you'll need to move the Python script to the /home/pi. To do that, open the command line. Move to the Downloads folder with the following command.

    language:bash
    cd Downloads
    

    using a command in the terminal to navigate to the downloads

    We'll use the mv Linux command to move the file to a certain location (in this case /home/pi) with the following command:

    language:bash
    mv shutdown_Pi.py /home/pi
    

    using a command in the terminal move python file to a different location

    Just to make sure that the file was moved correctly, use the change directory command to move back up a level:

    language:bash
    cd ..
    

    using a command in the terminal to move to the location of the file that was just moved

    Followed by the list command to see what's in the path. If you look closely at the images above, it was used to verify what was in the location. You should notice the shutdown_Pi.py file in the location.

    language:bash
    ls
    

    verifying that the file is in the correct path in the terminal

    Modify rc.local

    With the terminal still open, type the following command:

    language:bash
    sudo nano /etc/rc.local
    

    configuring the rc.local file

    Scroll down using the button on your keyboard, and just before the exit 0 line, enter the following:

    language:bash
    python /home/pi/safe_shutdown_Pi.py &
    

    add the following line in the rc.local file

    Save and exit by pressing CTRL + X on your keyboard, followed by y when prompted, and then hit Enter. To ensure that the changes take effect, type the following command.

    language:bash
    sudo reboot
    

    reboot to ensure the changes are saved

    What You Should See

    After rebooting, hit the GPIO17 button on the Qwiic pHAT v2.0. This should shutdown the Pi. You'll notice the monitor disconnect if you have one attached but make sure to give it a few more seconds to finish shutting down before removing power. The green status LED on the Pi will stop blinking when it is completely shutdown.

    Shutdown Button Safely Safely Turning Off Raspberry Pi

    You can now safely remove power from the Pi. To power your Pi again, just insert the power connector back into the Pi.

    Power Being Removed After Safely Shutting Down

    Example 2: Safe Reboot and Shutdown

    Sweet. But what if you wanted more functionality from just one button? How about we add a condition to distinguish between a momentary button press to reboot or when it is pressed for a certain period of time to shutdown? We can reboot the Pi by switching from the halt (-h) to reboot (-r) command.

    language:bash
    sudo shutdown -r -now
    

    The following example loads another Python script on startup. The Raspberry Pi will safely reboot or shutdown with the commands depending on how long we press on the button connected to GPIO17.

    Example Code

    On your Raspberry Pi, download the Python script by clicking on the button below.

    You can also copy the code and paste it in a text editor. Just make sure to name this file as safe_restart_shutdown_Pi.py and remember the location that the file was saved.

    language:python
    # safe_restart_shutdown_Pi.py
    #
    # -----------------------------------------------------------------------------
    #                 Raspberry Pi Safe Restart and Shutdown Python Script
    # -----------------------------------------------------------------------------
    # WRITTEN BY: Ho Yun "Bobby" Chan
    # @ SparkFun Electronics
    # DATE: 3/31/2020
    #
    # Based on code from the following blog and tutorials:
    #
    #    Kevin Godden
    #    https://www.ridgesolutions.ie/index.php/2013/02/22/raspberry-pi-restart-shutdown-your-pi-from-python-code/
    #
    #    Pete Lewis
    #    https://learn.sparkfun.com/tutorials/raspberry-pi-stand-alone-programmer#resources-and-going-further
    #
    #    Shawn Hymel
    #    https://learn.sparkfun.com/tutorials/python-programming-tutorial-getting-started-with-the-raspberry-pi/experiment-1-digital-input-and-output
    #
    # ==================== DESCRIPTION ====================
    #
    # This python script takes advantage of the Qwiic pHat v2.0's
    # built-in general purpose button to safely reboot/shutdown you Pi:
    #
    #    1.) If you press the button momentarily, the Pi will reboot.
    #    2.) Holding down the button for about 3 seconds the Pi will shutdown.
    #
    # ========== TUTORIAL ==========
    #  For more information on running this script on startup,
    #  check out the associated tutorial to adjust your "rc.local" file:
    #
    #  https://learn.sparkfun.com/tutorials/
    #
    # ========== PRODUCTS THAT USE THIS CODE ==========
    #
    #   Feel like supporting our work? Buy a board from SparkFun!
    #
    #        Qwiic pHAT v2.0
    #        https://www.sparkfun.com/products/15945
    #
    #   You can also use any button but you would need to wire it up
    #   instead of stacking the pHAT on your Pi.
    #
    # LICENSE: This code is released under the MIT License (http://opensource.org/licenses/MIT)
    #
    # Distributed as-is; no warranty is given
    #
    # -----------------------------------------------------------------------------
    
    import time
    import RPi.GPIO as GPIO
    
    # Pin definition
    reset_shutdown_pin = 17
    
    # Suppress warnings
    GPIO.setwarnings(False)
    
    # Use "GPIO" pin numbering
    GPIO.setmode(GPIO.BCM)
    
    # Use built-in internal pullup resistor so the pin is not floating
    GPIO.setup(reset_shutdown_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    
    # modular function to restart Pi
    def restart():
        print "restarting Pi"
        command = "/usr/bin/sudo /sbin/shutdown -r now"
        import subprocess
        process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
        output = process.communicate()[0]
        print output
    
    # modular function to shutdown Pi
    def shut_down():
        print "shutting down"
        command = "/usr/bin/sudo /sbin/shutdown -h now"
        import subprocess
        process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
        output = process.communicate()[0]
        print output
    
    while True:
    
        # For troubleshooting, uncomment this line to output buton status on command line
        #print GPIO.input(reset_shutdown_pin)
        if GPIO.input(reset_shutdown_pin) == False:
            counter = 0
    
            while GPIO.input(reset_shutdown_pin) == False:     
                counter += 1
                time.sleep(0.5)
    
                # long button press
                if counter > 4:
                    shut_down()
    
            #if short button press, restart!
            restart()
    

    Setting Up the Path

    This will be saved in your Downloads folder again. Once downloaded, you'll need to move the Python script to the /home/pi. To do that, open the command line. Move to the Downloads folder with the following command.

    language:bash
    cd Downloads
    

    using a command in the terminal to navigate to the downloads

    We'll use the mv Linux command to move the file with the following command once again:

    language:bash
    mv safe_restart_shutdown_Pi.py /home/pi
    

    using a command in the terminal move python file to a different location

    Just to make sure that the file was moved correctly, use the change directory command to move back up a level:

    language:bash
    cd ..
    

    using a command in the terminal to move to the location of the file that was just moved

    Followed by the list command:

    language:bash
    ls
    

    verifying that the file is in the correct path in the terminal

    Modify rc.local

    With the terminal still open, type the following command again:

    language:bash
    sudo nano /etc/rc.local
    

    configuring the rc.local file

    Scroll down using the button on your keyboard, and just before the exit 0 line, adjust the file name for safe_restart_shutdown_Pi.py:

    language:bash
    python /home/pi/safe_restart_shutdown_Pi.py &
    

    add the following line in the rc.local file

    Save and exit by pressing CTRL + X on your keyboard, followed by y when prompted, and then hit Enter

    To ensure that the changes take effect, type the following command.

    language:bash
    sudo reboot
    

    reboot to ensure the changes are saved

    What You Should See

    After rebooting, hit the GPIO17 button momentarily on the qwiic pHAT v2.0. This should reboot the Pi.

    Shot button press for reboot

    Press and hold GPIO17 button a little longer to initiate the shutdown command. You'll need to give it a few seconds for the Pi to shutdown. You'll notice the monitor disconnect first if you have one attached. At this point, you should be good to remove your finger off the button. Again, you will want to observe the green status LED on the Pi. The LED will stop blinking when the Pi is completely shutdown. You can now safely remove power from the Pi.

    Long button press for shutdown

    Resources & Going Further

    For more resources, check out the links below:

    • eLinux.org Wiki: Wake from Halt - For certain versions, you can wake the Pi up by shorting pins together rather than disconnecting the power supply. However, caution is advised as these GPIO pins are adjacent to the power pins.

    Need some inspiration for your next project? Check out the Pi AVR Programmer! We implement a shutdown code after programming and testing boards.

    Raspberry Pi Stand-Alone Programmer

    March 8, 2018

    This tutorial will show you how to use a headless Raspberry Pi to flash hex files onto AVR microcontrollers as a stand-alone programmer. It also tells the story about production programming challenges, how SparkFun came to this solution, and all the lessons learned along the way.

    Pi AVR Programmer HAT Hookup Guide

    July 26, 2018

    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.

    Or check out some of these related tutorials:

    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.

    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.

    Qwiic Atmospheric Sensor (BME280) Hookup Guide

    Measure temperature, humidity, barometric pressure with the SparkFun Atmospheric Sensor Breakout BME280 (Qwiic).

    Basic Servo Control for Beginners

    An introductory tutorial demonstrating several ways to use and interact with servo motors!

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

    Arduino Shields v2

    $
    0
    0

    Arduino Shields v2 a learn.sparkfun.com tutorial

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

    Introduction

    Update: This is an updated version of our original Arduino Shields tutorial to expand and update on it as many of the shields highlighted in the original tutorial are no longer carried by SparkFun. If you are looking for the original tutorial it can be found here: Arduino Shields

    What is a Shield?

    Shields[1] are modular circuit boards that piggyback onto your Arduino to instill it with extra functionality. Want to connect your Arduino to the Internet and post to Twitter? There's a shield for that. Want to make your Arduino an autonomous rover? There are shields for that. There are a LOT of shields out there, all of which can add all sorts of customizations to enhance your Arduino's functionality.

    Instagram - Table Full of Shields

    A blast from the past! Former SparkFun catalog manager RobertC. in awe of an extravagant platter of shields.

    Many Arduino shields are stackable. You can connect multiple shields together to create a stack of Arduino modules. You could, for example, combine a SparkFun RedBoard with a Weather Shield and a WiFi Shield - ESP8266 to create a wireless weather station similar to this Weather Station project.

    Shields are often supplied with either an example sketch, or a library. So, not only do they just simply plug into your Arduino, but all you usually need to do to make them work is upload up some example code to the Arduino.

    [1] Note: In general, these are called "daughter boards." The terminology and layout depends on the environment platform and form factor. Shields for Arduino typically use the Arduino Uno R3 footprint. However, shields can have a different layout depending on the architecture. Stackable PCBs for the Raspberry Pi are referred to as HATs or pHATs while the BeagleBone refers to them as Capes. We'll focus on the Arduino shields with the R3 footprint throughout this tutorial.

    Shield Form Factor

    Every Arduino shield must fit the same form factor as the Arduino it mates to.

    Shields designed to work on the Arduino Uno R3 form factor have power and ground pins on one eight (previously six) pin header, and analog pins on a six-pin header next to that. DiAgital pins cover the other edge on the opposite side, an eight-pin header separated from a 10-pin by that weird 0.5" spacing. Some shields also require a connection to the Arduino's ICSP header (the 2x3 programming header on the end).

    Shield Pinout

    Pin Functionality

    Some shields use nearly every available pin on the Arduino, while others only use a couple. Some shields communicate with the Arduino via SPI, I2C, or Serial. Other shields use the Arduino's interrupts, analog inputs, and PWM. When stacking shields it's important to make sure they don't use overlapping pins.

    Serial Communication

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

    Serial Peripheral Interface (SPI)

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

    Analog to Digital Conversion

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

    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.

    Processor Interrupts with Arduino

    What is an interrupt? In a nutshell, there is a method by which a processor can execute its normal program while continuously monitoring for some kind of event, or interrupt. There are two types of interrupts: hardware and software interrupts. For the purposes of this tutorial, we will focus on hardware interrupts.

    Additionally, you will also want to ensure that shield pins are compatible with your development board. If a shield was designed with the ATmega328p in mind, the pin functionality may be in a different location. For example, the XBee shield was designed for the Arduino Uno R3 (an ATmega328P-based board). If you were to use the Arduino Leonardo (an ATmega32U4-based board) or the Arduino Mega 2560 (an ATmega2560-based board), you would need to reroute the connection and redefine the pin definitions. For more information, check out the XBee Shield Hookup guide.

    Pins Rerouted for Arduino Mega 2560 R3Pins Rerouted for Arduino Leonardo w/ ATmega32U4
    XBee Shield Pins Rerouted for ATmega2560-Based ArduinoXBee Shield Pins Rerouted for ATmega32U4-Based Arduino

    Logic Levels

    Also note that there are several Arduino development boards available now that fit the R3 form factor but run at a different logic level than the standard Uno/RedBoard. For example, the Arduino Uno R3 runs at 5V logic where the RedBoard Artemis runs at 3.3V. Quite a few shields can function just fine with a board running at either logic level but you may run into some erratic behavior with level shifting circuits set up to work best with a 5V system. Another potential issue you may run across with a 3.3V logic Arduino is if the shield pulls any of the pins to a 5V reference voltage through something like a pull up resistor.

    Logic Levels

    June 3, 2013

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

    Other Shield Form Factors

    There is a great variety of Arduino shields out there -- too many to ever include in this tutorial. While most adhere to the standard Arduino Uno R3 form factor, some shield designs can vary depending on the development board's footprint and environment. Some of these designs include the Thing Plus, Pro Mini, Pro Micro, Arduino Nano, Arduino MKR, and Teensy footprints.

    In the next section, we'll go over a handful of the more popular and unique shields designed for the R3 form factor that SparkFun carries.

    A Plethora of Shields

    The list below describes some of the R3 form factor shields SparkFun carries separated into some loose categories based on their unique functionality. This is not an exhaustive list of all Arduino shields but it will cover most of what SparkFun has to offer. If you want to browse all the shields SparkFun carries, check out the Arduino Shields Category.

    Prototyping & More

    Prototyping shields usually do not augment the functionality of the Arduino like other shields but they help in other ways. Prototyping shields do things like breaking out various pins to screw terminals or create a space to build and test a circuit on the shield.

    • ProtoShield Kit - The self-titled star of this category. The ProtoShield includes a large prototyping area in the center. Half of this area has solder jumper pads on the bottom you can close to make it function more like a breadboard while the other half functions as a standard prototyping/perfboard area. There is quite a lot going on in this shield so for a full rundown on everything included in the ProtoShield Kit and how to use it, check out the ProtoShield Hookup Guide!
    • ProtoScrew Shield - Like the ProtoShield, but each pin is also broken out to a screw terminal. Handy for connecting to external motors, heavy-duty sensors or creating a strong connection to each pin that is not as permanent as a solder connection.
    • Qwiic Shield - The perfect way to integrate your Arduino with SparkFun's Qwiic System! This shield has four Qwiic connectors on it along with a level-shifting circuit to easily connect to and communicate with Qwiic I2C breakouts. The shield also has a large prototyping area that includes a few neat features to help with prototyping. Take a look at the Qwiic Shield Hookup Guide to get started with this shield and the Qwiic system.

    The Qwiic Shield in action with several Qwiic breakouts attached
    • Joystick Shield Kit - This makes your Arduino a bare-bones controller. With a joystick and four buttons added to it, this shield works great for a simple robot controller.
    • microSD Shield - A lot of Arduinos have limited storage space, but this easy-to-use shield (along with the SD library) allows for plenty of extra storage for things like data logging.
    • Mux Shield II - This shield from Mayhew Labs is a great way to add up to 48 analog and digital inputs or digital outputs to an Arduino using the R3 layout. Mayhew Labs also has an Arduino Library with built-in examples to help you get started. That, along with information on how to use the Mux Shield II can be found in their user guide.

    IoT and Wireless Technology Shields

    These shields add different types of wireless technologies to your Arduino. They range from connecting to the Internet for your next IoT Arduino project to receiving and logging the GPS coordinates of your Arduino-based robot and much more!

    • WiFi Shield (ESP8266) - This shield uses Espressif's ESP8266 SoC to add WiFi connectivity to an Arduino using the R3 layout. The shield comes with pre-flashed AT-command firmware so it works as a serially-controlled WiFi gateway out of the box but it also breaks out the I/O pins of the ESP8266 so you can access those as well and even re-program the ESP8266 with your own custom firmware. To get started with the WiFi Shield (ESP8266) take a look through our Hookup Guide.

    SparkFun WiFi Shield mounted on a RedBoard
    • Arduino Ethernet Shield 2 - Looking to access the Internet but would prefer a hard-wired option? The Ethernet Shield is for you! Getting started with the Ethernet Shield 2 is easy using the Arduino Ethernet Library. The shield also includes an on-board microSD slot to store larger files to send over your network.
    • LTE CAT M1/NB-IoT Shield (SARA-R4) - This shield adds wireless, high-bandwidth cellular functionality to your IoT project. We've written an Arduino Library with some examples to get you started sending SMS messages or communicating with servers over a TCP/IP connection. All you need to get started is a compatible SIM card or you can get the version of this shield that includes a Hologram SIM card here. Check out the Hookup Guide for detailed information on how to get started with this shield.
    • XBee Shield - XBee's are great RF modules that work on multiple wireless protocols (802.15.4, Digi's Zigbee specification and BLE). Simply pair an XBee radio on the shield with another XBee and you're well on your way to creating a robot controlled by gestures!
    • GPS Logger Shield - With this shield you can log the position, speed and altitude of your Arduino using the on-board GP3906-TLP GPS Module. Take a look at the Hookup Guide to start logging.

    Music and Sound

    • MP3 Player Shield - Turn your Arduino into an MP3 player. Just plug in a µSD card with some MP3 files on it, add some speakers, upload the example code, and you can make your very own MP3 Playing Music Box!

    Music Box Circuit Diagram
    • MIDI Shield - Assemble this shield to give your Arduino access to the MIDI communication protocol. Along with MIDI-In and OUT ports, the shield also includes two potentiometers to control things like pitch, volume or tone. For assembly instructions and examples using the MIDI Shield, check out the Hookup Guide!
    • Spectrum Shield - This takes an stereo audio input to the shield and splits it into 7-bands per channel and reads the amplitude of each channel using the ADC on your Arduino. Use that data to control anything from LEDs, motors or even fire!
    • EasyVR 3 Plus Shield - This shield adds voice recognition technology to your Arduino using the EasyVR module so you can create your own voice controlled project. You can download the Arduino Library as well as learn how to get started with the EasyVR 3 in the User Guide.

    Motor Drivers

    • Ardumoto Shield Kit - With this kit you can use the Ardumoto shield to create a basic robot with the included DC motors.

    Ardumoto Robot using a SparkFun box.
    • Monster Moto Shield - If you need to drive beefier motors than the Ardumoto Shield can handle, this is the next step up.
    • Wireless Motor Driver Shield - Looking for something more versatile than the two shields above? The Wireless Motor Driver Shield can control two DC motors and also breaks out pins to power and control several servos and even has an XBee socket to easily add wireless control to your motor project! This shield has a lot going on so take a look through the Hookup Guide to get started.

    Miscellaneous Shields

    These shields do not really fit into any of the above categories but we'd still like to highlight them in this list as they add some neat, unique functionality to your Arduino.

    • CAN-Bus Shield - This allows your Arduino to talk to your car or other CAN application. It also has a µSD slot to log data and has connectors for a GPS connection and LCD to log and report data. Check out the Hookup Guide for more info and example code to get started.
    • Vernier Interface Shield - This shield has four British Telecom connectors (2 Analog and 2 Digital) to interface with all sorts of Vernier sensors.
    • Simultaneous RFID Reader - Add some item tracking to your Arduino using Radio Frequency Identification (RFID). The M6E Nano module on this board reads and writes to EPCglobal Gen 2 UHF RFID tags and can read multiple tags at the same time. Our RFID Arduino Library has a bunch of examples to get your next RFID project started.
    • Weather Shield - Want to create your own weather station? The Weather Shield is a great place to start. The shield has sensors to monitor temperature, humidity, barometric pressure and luminosity as well as ports to connect a GPS module along with weather meters to monitor wind speed, direction and rainfall!
    • EL Escudo Dos - Electroluminescent wire is awesome! Use this shield to add up to eight strands of EL wire to your project. Check out these EL Wire Tutorials for some inspiration for your own EL project.
    • Cthulhu Shield - One of the most unique and nifty shields SparkFun carries. The Cthulhu Shield can output to and take input from an electrode array placed on your tongue! For some neat experiment ideas pairing this shield with some sensors, take a look at this blog post and get started with some sensory substitution and augmentation.

    Using the GridEYE IR sensor for some IR target practice.

    Pair the Cthulhu Shield with a Grid-EYE IR Array Breakout for some IR target practice!

    Installing Headers (Preparation)

    Many shields come without any headers attached. This keeps their final fate open to your interpretation (maybe you'd rather use straight male headers, instead of the usual stackable headers). The following pages will explain how you can turn your drab, header-less shield into a fully functional, ready-to-plug-in module.

    Shield before and after headers

    Shield assembly requires soldering. Solder helps make a good physical and electrical connection. Without solder, your shield and Arduino will almost certainly not work properly. If it manages to work at all it will be erratic and intermittent at best. If this is your first time soldering, consider checking out our How to Solder: Through-Hole Soldering Tutorial prior to assembling your shield:

    How to Solder: Through-Hole Soldering

    September 19, 2013

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

    Required Materials

    With your shield (or shields) chosen, the only other required materials are a compatible Arduino development board and some headers. The SparkFun RedBoard and Arduino Uno R3 are great options that will work with nearly any Arduino shield with no issues:

    SparkFun RedBoard - Programmed with Arduino

    SparkFun RedBoard - Programmed with Arduino

    DEV-13975
    $19.95
    46
    Arduino Uno - R3

    Arduino Uno - R3

    DEV-11021
    $22.95
    131

    And here are some recommended header options:

    Break Away Headers - Straight

    Break Away Headers - Straight

    PRT-00116
    $1.50
    20
    Arduino Stackable Header Kit - R3

    Arduino Stackable Header Kit - R3

    PRT-11417
    $1.50
    12
    Arduino Stackable Header Kit

    Arduino Stackable Header Kit

    PRT-10007
    $1.50
    3

    Required Tools

    You will also need at least a soldering iron and some solder to assemble your shield. Below are a few soldering iron and solder options along with a couple of kits that will have all the tools necessary to start soldering:

    SparkFun Beginner Tool Kit

    SparkFun Beginner Tool Kit

    TOL-14681
    $54.95
    Soldering Iron - 30W (US, 110V)

    Soldering Iron - 30W (US, 110V)

    TOL-09507
    $9.95
    7
    Solder Lead Free - 15-gram Tube

    Solder Lead Free - 15-gram Tube

    TOL-09163
    $3.50
    2
    Brass Sponge

    Brass Sponge

    TOL-08964
    $2.95
    4

    Along with these required tools, these accessories can help make your soldering experience a little easier:

    SparkFun Third Hand Kit

    SparkFun Third Hand Kit

    TOL-11784
    $34.95
    55
    Chip Quik No-Clean Flux Pen  - 10mL

    Chip Quik No-Clean Flux Pen - 10mL

    TOL-14579
    $7.95
    2
    Solder Wick #2 5ft. - Generic

    Solder Wick #2 5ft. - Generic

    TOL-09327
    $2.49
    4
    Soldering Iron Stand

    Soldering Iron Stand

    TOL-09477
    $5.95
    3

    What Kind of Header Should You Use?

    There are all kinds of headers, but there are only two that we recommend for installing on shields: stackable or male.

    Header options - male or stackable

    A straight male header (left) and a stackable header (right).

    Stackable headers are especially great for stacking shields. They also maintain your ability to plug a jumper wire into any of the Arduino's pins. This tutorial will primarily explain how to install stackable headers. Stackable headers are available individually in 6-pin, 8-pin, and 10-pin varieties (there are other stackable header options for development boards that use different footprints/form factors), or you can buy the headers in packs like the ones shown in the Required Materials section above.

    Simple straight male headers are also an option for connecting a shield to an Arduino. Male headers are beneficial in that they create a lower-profile stack when connected to an Arduino. If you plan to stuff your Arduino/shield combo into an enclosure, you may need to consider using male headers. This tutorial focuses on stackable header installation, check the Tips and Tricks section for male header assembly instructions.

    Do not install female headers, right-angle male headers, swiss machine-pinned headers, round headers, or a variety of other headers that may exist out there. You really should only use headers that have straight, rectangular, male pins.


    Now then, plug in and start warming up those soldering irons. It's time to get soldering!

    Installing Headers (Assembly)

    Step 1: Insert All Four Headers

    Plug all four headers into the shield. Make sure you insert them in the correct direction. The male pins of the header should enter the top side of the shield and extend out the bottom. This orientation is of utmost importance. Don't solder anything until you've got the headers going the right way!

    Headers inserted, not yet soldered

    Headers inserted, aligned as well as possible, ready to solder.

    With the headers inserted, flip the shield on its top-side to rest on the black, female side of the headers. Hopefully you've got a nice flat workspace to lay it on. Try to align all headers so they're precisely perpendicular to the shield PCB.

    Step 2: Solder One Pin On Each Header

    Finally it's soldering time! It's important that each of the headers is at a nice, 90° angle to the PCB. This will ensure that the shield slides straight onto your Arduino and you won't have to bend any pins in doing so.

    In order to guarantee that each header is straight start by soldering just a single pin on each. That way if they're at a weird angle it will be much easier to re-heat just a single pin while adjusting the alignment.

    Soldering the first pins

    One pin down, one in progress, two to go. Soldering one pin on each header.

    Four solder joints down, only 24 (to 28) to go!

    Step 3: Check Header Alignment

    With those four pins soldered, try plugging the shield partially into your Arduino to test the header's alignment. Make sure your Arduino is not powered while you do this alignment check.

    Alignment check

    Temporarily plugging the shield in to check that all pins line up.

    Does everything line up? No pins bending? If not, find the guilty header and try to re-align it. Warm the joint back up with your iron, and slightly move and adjust the header alignment. Also, be careful when pulling the partially soldered shield out of the Arduino. Since all the headers are not soldered, you could easily bend them as you pull it out of the Arduino's female headers.

    Step 4: Solder All Remaining Pins

    If your headers are all lined up, you can attack the remaining unsoldered header pins. When you're done, you should have 32 shiny volcanoes of solder.

    Shield with all headers soldered

    That's a beautiful sight. Everything's soldered up.

    Step 5: Check For Shorts or Cold Joints

    With everything soldered, double check for bad solder joints. Did any of your joints stray into another creating a short? If so, you can take some solder wick to the joint, or just try re-heating the short and "pushing" the solder where you want it.

    Shorted solder joints

    Well, that's just egregious! Watch out for shorted solder joints like that.

    Also check for cold solder joints - a joint that's got some solder on it, but isn't quite connecting the two solder points together. Cold joints aren't always the easiest to see; look out for joints that aren't as shiny, or pins that still seem loose.

    Cold solder joint

    That last pin could use a bit more solder. It doesn't quite look like a connection's been made.

    To fix a cold joint, re-heat the solder on the pin, and add just a bit more.

    Step 6: Plug It In!

    It's usually best practice to power down (unplug) your Arduino before you connect a shield to it. Hopefully all of the pins are still well-aligned and the shield just slides right into the Arduino. Take care not to bend any pins while inserting, and make sure they all go into their mating female headers.

    The Ardumoto Shield plugged into  a SparkFun RedBoard.

    That satisfying feeling as the shield slides straight into your Arduino

    Assembly Tricks

    The previous assembly section should detail everything you need to know about simple shield header installation. There are, however, a few tricks we've picked up along the way...

    Use An Old Shield to Aid Alignment

    The easiest place to mess up shield assembly is in aligning each of those headers. It's best to avoid soldering the stackable headers while the shield's connected to the Arduino, so the method described in the assembly section is usually best. If you've got a spare shield lying around you can take advantage of another little trick by using it as a header-alignment-jig.

    Begin by plugging all of the headers into your spare shield jig.

    Stackable headers inserted into shield-jig

    The green shield will be used as our jig. First, insert the stackable headers into it.

    Then insert the headers into your to-be-soldered shield, and solder them all up. Assuming the spare shield is aligned properly (you may want to check that first), your headers will line up perfectly with your Arduino.

    Shield to be soldered inserted into jig. Ready to solder.

    The jig should correctly align all of the headers. Solder away!

    Installing Male Headers

    If you value a smaller profile shield installation over the ability to stack shields and connect jumper wires, male headers are an option.

    In a way, male headers are actually easier to align and install because you can use your Arduino as a jig. Begin by inserting the headers into your Arduino.

    Redboard jigging male headers

    RedBoard's make an especially special jig for aligning male headers.

    Then line up and plug in the shield, and solder away.

    Shield inserted into jig

    Shield with headers, ready for soldering. We can trust the RedBoard to line the male headers up for us.

    Be somewhat careful using this method. Don't leave the iron on the pins for too long or you risk burning the Arduino's headers underneath. If you're especially worried about burning your Arduino's female headers, you can solder just a single pin on each header, remove the shield, and solder the rest.

    Holding Headers Against the Shield

    Don't have an extra shield around or your development board does not have any header pins soldered on yet? For those that have the dexterity, you can install a row of headers by holding the pins against the board! You can even try to use tape and sticky tack. Below is an example of installing female headers on the ProtoShield. However, you can follow along with male headers or use this technique to solder headers on development boards as well.

    Grab a female stackable header and slide it from the top side of a shield. With your soldering hand, pull the header with your index finger and thumb toward the edge of the board. Using your other hand, push against the header using your index finger and grip the board with your thumb. Hold the header down with your middle finger. Make sure to avoid touching any header pins where the soldering iron will touch.

    Grab the soldering iron with your soldering hand and tack on one pin. Repeat for each header. After tacking one pin for each header, you will want to ensure that the pins are straight and perpendicular to your board. If they are not, you can try to reheat the header pin and adjust the header's alignment.

    Tack on One Pin on the Header and Repeat

    If the headers are aligned, you can solder the rest of the header pins on the board to finish installing the headers on the shield!

    Installing Headers on Other Shields with a Breadboard

    If you are using a shield that does not use the R3 form factor, you may be able to use a breadboard to help solder headers. Below is an example with male headers being soldered on the TeensyView shield for a Teensy and MiniGen shield for a Pro Mini. The Teensy and Pro Mini form factors use breadboard compatible pins on the edge of the board without the weird 0.5" spacing.

    Installing male headers on TeensyView shield for the Teensy with a breadboard.v
    Installing male headers on TeensyView shield for the Teensy with a breadboard.Installing long male headers on the MiniGen shield for the Pro Mini with a mini-breadboard.

    When using a breadboard, you will also want to be careful soldering the pins to the shield. If you leave the iron on the pins for too long, you will also run the risk of melting the plastic breadboard holding the metal rails as well.

    Resources and Going Further

    Now that you've got this knowledge under your belt, you can bend just about any Arduino shield to your will! If you're interested in further exploring the world of shields, check out our Arduino Shield category.

    Are you just getting started with Arduino or interested in exploring more about using the Arduino IDE? Consider checking out some of these guides to help you get started:

    Looking for some project inspiration for your Arduino shield? Here are some fun project tutorials focused on using an Arduino shield:

    MP3 Player Shield Music Box

    Music Box Project based on the Dr. Who TARDIS.

    Weather Station Wirelessly Connected to Wunderground

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

    XBee Shield Hookup Guide

    How to get started with an XBee Shield and Explorer. Create a remote-control Arduino!

    Simultaneous RFID Tag Reader Hookup Guide

    A basic guide to getting started with the RFID Tag Reader breakout and how to read and write multiple RFID tags over multiple feet!

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

    Working with Qwiic on a Jetson Nano through Jupyter Notebooks

    $
    0
    0

    Working with Qwiic on a Jetson Nano through Jupyter Notebooks a learn.sparkfun.com tutorial

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

    Introduction

    Let’s face it... SSH or VNC can be frustrating and a barrier to entry at times for people looking to get started with remote computing. Luckily, services like Project Jupyter help make remote computing a little more accessible. Jupyter Notebooks have been around for a while and a number of people use them for a variety of applications; from data visualization to teaching and learning computer science.

    https://raw.githubusercontent.com/jupyter/design/master/logos/Rectangle%20Logo/rectanglelogo-greytext-orangebody-greymoons/rectanglelogo-greytext-orangebody-greymoons.png

    In a nutshell you can think of Jupyter Notebooks as an IDE and documentation repository in one platform that is accessible remotely through a web browser. Jupyter then grants access to the file directories of the host computer, a terminal to run Linux commands to install software on it as well as run required commands and processes. The “Notebooks” are files where you can create interactive Python scripts through intermixing markdown documentation with code so that your Notebook is both a “Notebook” and the program you end up running. Common applications for Jupyter Notebooks include building data visualization displays or GUI interfaces.

    Jupyter Notebooks are accessed through a web browser interface. From a client computer on the same network you can access the Notebooks and edit, run and/or modify the Python scripts that are hosted as well as create new ones. This makes working with a single board computer much easier and cleaner in terms of required hardware peripherals, but it also lowers the barrier of entry in terms of those who are new to the topic and feel overwhelmed.

    Jupyter Notebooks for SparkFun Qwiic on the Jetson Nano

    A great example of using Jupyter Notebooks as both a development and a learning platform is the NVIDIA Jetson Nano.

    We carry two kits: the DLI Course Kit and JetBot AI Kit that can use Jupyter Notebooks as a way to deliver tutorial content to get users up and running easily as well as empower them to go further with those products. Jupyter Notebooks are especially helpful with topics and projects that can be mentally taxing and hard to understand such as Machine Learning and Computer Vision.

    SparkFun DLI Kit for Jetson Nano

    SparkFun DLI Kit for Jetson Nano

    KIT-16308
    $174.95
    SparkFun JetBot AI Kit v2.0 Powered by Jetson Nano

    SparkFun JetBot AI Kit v2.0 Powered by Jetson Nano

    KIT-16390
    1

    This tutorial covers a set of Jupyter Notebooks that we created for our Python supported Qwiic boards and their use with the NVIDIA Jetson Nano!

    With Python support for the ever growing catalog of SparkFun Qwiic boards we thought that a Jupyter Notebook collection built around using our Qwiic boards with the NVIDIA Jetson Nano would be a good idea. We have created eight different notebooks that give you a “Hello World” example for each of the currently supported boards. Each Notebook breaks down the Python script into manageable chunks giving explanation and context to what is happening and in the end we get you enough knowledge to be dangerous!

    alt text

    When you feel comfortable and want to dig into creating your own Python scripts for a project, you can create your own Notebook and execute the code right from Jupyter Notebooks. You can even try your hand at integrating some of the sensors into a Machine Learning project as all of the Qwiic libraries will be installed on your Jetson Nano!

    This tutorial will get you up and running on an NVIDIA Jetson Nano and Jupyter Notebooks using SparkFun Qwiic Boards!

    Hardware Overview and Assembly

    We will obviously need an NVIDIA Jetson Nano (we recommend starting with the DLI Course Kit) as well as some Qwiic hardware. We recommend starting with the SparkFun Qwiic Kit for Raspberry Pi but we have Python packages for many Qwiic boards. The most up to date list of Python-supported Qwiic boards can be found in the Qwiic Py GitHub Repository.


    qwiic kit

    Hooking up your Qwiic kit to the NVIDIA Jetson Nano is straight forward. The kit comes with our Qwiic pHAT which plugs in to the Jetson Nano via the 2x20 GPIO header.


    Qwiic pHAT connected to the Jetson Nano

    The orientation of the pHAT is very important here. It should hang off the Jetson Nano Developer Kit carrier board and not over the top of the heat sync. Think “spoiler” for your Jetson Nano and you will get it!

    Once the pHAT is in place we can now add the distance sensor and environmental combo board as well as the micro OLED display using the Qwiic cables included in the kit.


    Qwiic breakouts connected to the pHAT on the Nano

    You can configure your hookup of the Qwiic boards in any combination you like as long as you have both boards connected to the pHAT. Personally, I like to daisy chain them together but you can go with the flavor that suits you and your needs.

    Software Setup and Installation

    Once you have everything connected to the pHAT, it is now time to get the Python libraries and Jupyter Notebooks installed.

    This tutorial assumes you have already gone through the process of burning an OS image to a microSD card, ran initial setup and have your Nano connected to the internet either through Ethernet or WiFi. If you are just opening the box at this point take a moment to set your board up by going through the following tutorials:

    Note: We will be working from a DLI Course image with network connection already setup. If you are looking for a shortcut, using our JetBot Image with your Jetson Nano will get you the drivers for the Edimax USB adapter and Qwiic Python libraries installed for you!

    Navigating to Jupyter Notebooks

    To access Jupyter Notebooks on your Jetson Nano you will need to know its IP address. There are a number of ways to find it. The most straightforward way is to hook the Jetson Nano up to a monitor and keyboard, open a terminal and type the following:

    ifconfig[Enter]

    This command will list off all of your network connections and the IP address for that connection. If you have followed the instructions for the WiFi setup tutorial linked above we will assume you know your IP address and have your Jetson Nano connected to your network.

    Open a browser window and type the following in the address bar: http://[IP ADDRESS]:8888 with [IP ADDRESS] being your Jetson Nanos IP Address.

    The first time you connect it may take a bit of time for Jupyter Notebooks to load, but you should be greeted by a loading page and then a sign-in page asking for a password. The password for the DLI image is dlinano and the password for the Jetbot image is jetbot.


    Screenshot showing Jupyter Notebook Launcher

    Once you are logged into Jupyter Notebooks you will need to open a new terminal window to download the Jupyter Notebooks for the Qwiic Boards as well as install the Qwiic Python libraries.


    Terminal opened and command to download Qwiic Jupyter entered
    Having trouble seeing details in the image? Click on it for a larger view!

    Once you open the terminal window from the Launcher window, navigate to the DLI-Nano Notebooks directory by typing the following command:

    cd nvdli-nano[Enter]

    You can then download the SparkFun Qwiic Jupyter Notebooks from GitHub with the following command:

    sudo git clone https://github.com/d1runberg/qwiic-jupyter-nb.git[Enter]

    This command will download a folder with the contents of our Jupyter Notebooks as well as the assets required to display images, etc. You should now be able to see the SparkFun Qwiic Notebooks directory in the directory tree on the left side of Jupyter Notebooks!

    Once the SparkFun Qwiic Notebooks downloads you need to install the Qwiic Python libraries before digging in and using them.

    Installing Qwiic Libraries

    With the terminal window in Jupyter Notebooks still opened you can install the SparkFun Qwiic Python libraries through pip by typing the following command:

    sudo pip3 install sparkfun-qwiic[Enter]

    This will install the entire Qwiic Py package with libraries for the Qwiic boards that are supported in Python.


    alt text

    Once the installation is complete, you should be good to go and can close the terminal window.

    Running an Example in Jupyter Notebooks

    With our Qwiic boards connected to the Jetson Nano we have two different options of Notebooks to choose from! For the sake of simplicity I chose the OLED notebook to walk you through, but once you run the first Notebook the other will be simple enough to run as well. Open the SparkFun Qwiic Notebooks directory by double clicking on it. Find the OLED.ipynb notebook file and open it by double clicking it as well.


    Screenshot of SparkFun Qwiic OLED Notebook

    Notebooks work in Jupyter Notebooks by running your code in a kernel which you need to start and stop. It is a good habit to make sure that you are not running other Notebook kernels before starting one. To check if any kernels are running select the small running man icon on the far left toolbar. Any kernels that are running will be listed here and you can click “SHUTDOWN” to close any that are open.


    Screenshot showing SHUTDOWN for Jupyter Notebooks

    To run the OLED Notebook we need to specify what type of kernel we want to run it as. In the upper right hand corner there is a small text box next to a circle. It should say “Python 3”, but if it says “No Kernel” click on it and select Python 3 from the options provided. We can now run the python code in the Notebook!


    Screenshot showing selecting the Kernel

    Next, interact with the Notebook by clicking on the first cell which is the product description for the OLED and then click the "Play" button in the top menu bar. This play button steps you through each cell (either text or code) and moves you to the next one.


    Screenshot showing the Play button

    You may notice that each cell has a box next to it. For code cells there will be an ‘*’ in that box while the code is executing and when it completes its execution the asterisk will turn to a number. So, you can follow through the Notebook by clicking the Play button as code executes combined with reading the explanation through the tutorial text.

    In the end your OLED should display some text on it.


    The OLED displaying text

    The code cells in the Notebook are interactive and you can make changes. So changing the string that the display changes is as simple as double clicking on that code cell and changing the string to your name for example. You then need to reselect the code cell and re-run it.

    Resources and Going Further

    With that you have installed our Jupyter Notebooks for our Qwiic boards that are currently supported in Python. With these examples at your fingertips, explore different boards and use them with your Jetson Nano and even take a crack at integrating the OLED or the distance sensor with any of the other Notebook examples for the Jetson Nano. I tried my hand at creating a small widget to accept text in small text box and then send that to the OLED display! Check it out... In your Notebooks it is called button_oled.ipybb


    Screenshot of button_oled Notebook

    If you aren't up to tackling something around Machine Learning yet, check out the different widgets from the Jupyter Notebook Python libraries. These widgets are a simple way to create GUI dashboards and graphic displays for your Qwiic Boards! You can find more on the widget API here.

    For more information and resources about the NVIDIA Jetson Nano and Project Jupyter, check out the links below:


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

    Adding WiFi to the NVIDIA Jetson

    $
    0
    0

    Adding WiFi to the NVIDIA Jetson a learn.sparkfun.com tutorial

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

    Introduction

    Nearly every computer needs an internet connection these days, and more and more of those connections are via WiFi to keep things from being tethered to a router switch or the wall. A wireless internet connection is particularly helpful for single board computers that many applications need to be mobile. The NVIDIA Jetson Nano Developer Kit is no exception to that trend in terms of keeping the board as mobile as possible, but still maintaining access to the internet for software updates, network requests and many other applications. Unfortunately, it doesn't come with WiFi built in so we need to add it ourselves.

    There are a number of WiFi solutions that work with the Jetson Nano out there but we will focus on the Edimax N150 2-in-1 Combo Adapter we sell on its own and is included in our JetBot AI Kit. This adapter is small, low power and relatively cheap, but it does take a little bit of elbow grease to get working from a fresh OS image install or if you are looking to add WiFi once you have completed the DLI Course provided by NVIDIA. No matter, let’s take a look and get your Jetson Nano on the web!

    Edimax 2-in-1 WiFi and Bluetooth 4.0 Adapter

    Edimax 2-in-1 WiFi and Bluetooth 4.0 Adapter

    WRL-15449
    $19.95

    Hardware Overview and Assembly

    Edimax N150

    The Edimax N150 that we carry is specially model E-7611ULB USB WiFi / Bluetooth combination adapter.

    edimax

    The Edimax 2-in-1 WiFi and Bluetooth 4.0 Adapter (EW-7611ULB) is a nano-sized USB WiFi adapter with Bluetooth 4.0 that supports WiFi up to 150Mbps while allowing users to connect to all the latest Bluetooth devices such as mobile phones, tablets, mice, keyboards, printers and more. Supporting the latest Bluetooth 4.0 version with Bluetooth Smart Ready, this adapter offers ultra-low power consumption with Bluetooth Low Energy (BLE) while transferring data or connecting devices. And with a tiny nano-size design you can easily plug it in without blocking any surrounding USB ports which makes it perfect for adding a WiFi connection to the NVIDIA Jetson Nano

    Hardware Assembly

    First up we need to connect our network peripherals to the Jetson Nano. The WiFi adapter is a USB key, but we will need an Ethernet cable and of course our NVIDIA Jetson Nano Developer Kit as well as a 5V 4A power supply. If you are looking for these parts, our DLI Course Kit for the Jetson Nano is a great place to get all of the parts in one purchase! But, we do sell all of the parts of the kit individually as well.

    Before you get started plugging things in, we recommend as a best practice to disconnect your power supply to Jetson Nano Developer Kit while connecting any peripheral devices to it to prevent any potential damage to the Dev Kit or peripheral device.


    Edimax Adapter and Jetson Nano

    Unpackage the adapter from its box and insert it into one of the four USB 2.0 ports on your NVIDIA Jetson Nano Developer kit. Your preference as to which port is up to you, but we recommend one of the bottom ports here as you will probably never remove this adapter and it will not block visibility or access to other USB ports in the future.


    Edimax Adapter plugged in to USB port.

    Next, connect your Jetson to an open port on your router with your Ethernet cable. Now that everything is connected, you can power the board using the 5V 4Amp barrel jack power supply included with the DLI Course Kit.


    Ethernet cable and WiFi adapter plugged in and Jetson powered on

    OS Update and Upgrade

    The driver installation and setup for the Edimax N150 is pretty straightforward, but it does require some housekeeping before we can download and install it. If your Operating System is already up to date, go ahead and skip to "Driver Installation".

    We will need to update and upgrade the Linux OS that is on the board before doing anything else and that is where the hardwired Ethernet connection we established in the previous section comes into play.

    There are two ways to access your Jetson Nano once it is connected to your network via Ethernet:

    1. Keyboard, Mouse and Monitor - Though clunky it is probably the easiest way to work with your Jetson Nano outside their Jupyter Notebooks USB access.

    2. SSH into your Nano - Find your Nano on your network and SSH into its IP address. For more information on how to do this on a Jetson Nano please see this tutorial from jetsonhacks.com here.

    If you are using the DLI Course image for the Jetson Nano the username and password will both be: dlinano

    Note: For the sake of this tutorial we will assume you will be using a keyboard, mouse and monitor but will still install everything via command line so if you are using SSH all commands should be the same.

    Once you have established connection and are working on your Jetson Nano you will need to update your and upgrade your OS.

    Open a terminal window and type the following: sudo apt-get update. The terminal should prompt you for your password. Type in: dlinano if you are using the DLI course image and hit [Enter] (If you have changed your password or your image uses a different password, enter that instead). This will update all of the updated package information for the version of Ubuntu running on the Jetson Nano. Your terminal should print out something similar to the screenshot below.

    Terminal printout after retrieving OS update package information

    Once the command line prompt is returned to you it is now time to upgrade your system. This will take a significant amount of time if this is the first time running this command. The OS will download all of the updated packages and install them for you, essentially getting everything up to date with where your image “should be”. To upgrade your system type the following: sudo apt-get upgrade. The prompt will again ask for your password and will also ask for permission to install all of the packages. Type y and hit [Enter].

    Now you get to wait and watch the install process fly by on your screen. Or, play a game, respond to email or eat lunch as this will take some time.

    Note: The update and upgrade processes can take a considerable amount of time. Patience is key and it is recommended that you do not walk away from your Nano for extended periods of time while this is happening.

    Once your Jetson Nano has completed its upgrade (assuming you did not receive any errors during the process), reboot your Nano by typing the following: sudo reboot now[Enter].

    Your Nano will reboot itself. If you are using SSH you will need to reestablish a connection with the Nano (The IP address should still be the same)

    Driver Installation

    With your operating system up to date and after your NVIDIA Jetson Nano has rebooted, it is time to download and install the drivers for the Edimax N150 WiFi adapter. We will cover how to do that in detail in this section.

    Download the N150 Drivers

    You can download the appropriate drivers by opening a terminal and entering the following command:

    git clone https://github.com/lwfinger/rtl8723bu.git[Enter]

    Once the download is complete you can navigate into the drivers directory with the following command:

    cd rtl8723bu and then [Enter]

    You are now in the the directory (folder) to start the install process for the drivers!

    Installing the Drivers

    There are a couple of methods to install these drivers on a single board computer or really any other Linux computer. You can check out the README file of the GitHub repository to compile and install them from scratch, but we are going to install them through Dynamic Kernel Module Support (DKMS). These instructions can be found at the bottom of the README for the drivers, but we will reiterate them here.

    Assuming you are still in the driver directory named “rtl8723bu” type the following command:

    source dkms.conf[Enter]

    Once you get the command prompt back (which should almost be instantaneous) type the following command to create a working project directory:

    sudo mkdir /usr/src/$PACKAGE_NAME-$PACKAGE_VERSION[Enter]

    With the directory created, type the following to move a number of files to your working project directory:

    sudo cp -r core hal include os_dep platform dkms.conf Makefile rtl8723b_fw.bin /usr/src/$PACKAGE_NAME-$PACKAGE_VERSION[Enter]

    We finally add those files to DKMS with by executing the following command:

    sudo dkms add $PACKAGE_NAME/$PACKAGE_VERSION[Enter]

    Now that everything is ready and in its place we can finally install the drivers by typing the following command:

    sudo dkms autoinstall $PACKAGE_NAME/$PACKAGE_VERSION[Enter]

    DKMS will take a number of actions to install the drivers including cleaning up after itself and deleting unnecessary files and directories. Once the DKMS completes the installation you should get a positive confirmation of the installation!

    With the installation complete it is a good idea to reboot your Nvidia Jetson Nano with this command:

    sudo reboot now[Enter]

    Note: If you are accessing your Nano via SSH you will still need your Ethernet connection for the next steps, but if you are using a keyboard and mouse with a monitor you may disconnect your Ethernet cable and put it away at this time!

    Connecting to Your Network

    Upon reboot of your system, you should now have WiFi connection available to you! Open a command prompt to verify a succefful driver installation by checking if you have a wireless network device installed. Open a terminal and type the following command:

    ifconfig wlan0[Enter]

    You should get a response similar to the screen capture below. Notice that we have two wlan connections... wlan0 and wlan1 with only one connected and an IP address assigned to it.


    alt text

    To set up your connection from the command prompt you can use the NetworkManager tool from Ubuntu as outlined here. First, we will list all of our possible network connections by typing the following command:

    nmcli d[Enter]

    You should get a connection listing similar to something like this screen capture:


    alt text

    Next we will make sure that the WiFi module is turned on by typing the following command:

    nmcli r wifi on[Enter]

    Now we can scan and list off all visible WiFi networks available to us by typing the following command:

    nmcli d wifi list[Enter]

    You should get a list of possible networks available to you including current status in terms of signal strength, data rate, channel, security, etc.


    alt text

    Make sure that you see the wireless network that you are going to connect to.

    To connect to a given network make sure you have its SSID and password ready. Both are case sensitive! Type the following command with [SSID] being your SSID and [PASSWORD] being the password for that network:

    nmcli d wifi connect [SSID] password [PASSWORD][Enter]

    If all goes according to plan, you should get a connection confirmation!

    Note: If you are using SSH it is now your turn to untether yourself from the Ethernet cable and put it away. For future SSH connections make sure that your laptop or computer that you are accessing the Nano with over SSH is on the same wireless network that you just setup for your Nano in the previous steps.

    Testing Your Connection

    With your WiFi adapter connected to the internet you can now test it! Obviously in desktop mode with a keyboard and mouse you can open your browser and navigate to your favorite website.

    If you are using SSH and able to connect SSH over WiFi and your laptop, you have also scored a win in terms of the WiFi adapter and its connection. Either way you can also test your Nano's connection and ability to access the internet with a simple ping command pointed at Google. Run the following command from the terminal on your Nano:

    ping 8.8.8.8[Enter]

    You should get a response every few seconds reporting the data that comes back from the ping. You should be looking for packets both sent and received. If received packets is returned as 0, you do not have a connection established to the internet and should repeat the process of connecting above.

    Troubleshooting

    If you experience intermittent WiFi connection through this adapter open a terminal window and enter the following command to turn Power Saving Mode off:

    sudo iw dev wlan0 set power_save off[Enter]

    You may also have a second wireless device present when using the Edimax WiFi adapter. This will show up as wlan1. Repeat the command for wlan1 as well if the issue continues:

    sudo iw dev wlan1 set power_save off[Enter]

    Then reboot your Jetson Nano:

    sudo reboot now[Enter]

    If you try this and a number of the Troubleshooting methods, try burning our JetBot image to your SD Card. This image already has the drivers for the USB WiFi adapter installed and should work out of the box. For detailed instructions on how to install the JetBot image, please read through the Troubleshooting steps in this section of our JetBot Assembly Guide.

    Still Stuck?

    Resources and Going Further

    Now that your Jetson Nano is connected wirelessly to your network, it's time to incorporate it into your project!

    If you are looking for a little more power and bandwidth in terms of WiFi for your Jetson Nano check out the Intel dual band wireless card here.

    For more information, check out the resources below:


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

    SparkFun Auto pHAT Hookup Guide

    $
    0
    0

    SparkFun Auto pHAT Hookup Guide a learn.sparkfun.com tutorial

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

    Introduction

    Introducing, the Auto pHAT! The *perfect GIF(t) to get that HAT moving...

    dor-15 GIF

    Source: Youtube Doris from Disney's Meet the Robinsons

    Terrible pun aside, this product isn't capable of creating DOR-15 (aka Doris), but it will get you started on your robotics adventure.

    SparkFun Auto pHAT for Raspberry Pi

    SparkFun Auto pHAT for Raspberry Pi

    ROB-16328
    $29.95

    This device combines a few of our existing products onto a single pHAT. On the Auto pHAT you will find the following components:

    • 4 Channel Servo Controller
    • A 9-DoF IMU
    • USB-C Power Input
  • Qwiic Motor Driver
  • Rotary Encoder Input
  • A Qwiic connector
  • There are dozens of applicable projects for this product, you can even use it to get started with your rover and robotics applications. Its limits are up to you.

    Required Materials

    The required materials will depend on your project. However, at minimum, users will need:

    • A single board computer (SBC)
      • Must have a 40-pin Raspberry Pi compatible header
    • An SD card
    • Power supply (or power source)
    • Additional accessories:
      • Servos
      • Motors
      • Encoders
      • Chassis and Wheels
      • Header (optional)
    • Tools:
      • Small Flathead Screw Driver

    Single Board Computers

    Each of the SBCs that we offer have a unique facet that separates it from the others. There is a 40-pin Raspberry Pi compatible header on each of the SBCs.

    Raspberry Pi 3 B+

    Raspberry Pi 3 B+

    DEV-14643
    $39.95
    31
    NVIDIA Jetson Nano Developer Kit (V3)

    NVIDIA Jetson Nano Developer Kit (V3)

    DEV-16271
    $99.00
    5
    Raspberry Pi 4 Model B (4 GB)

    Raspberry Pi 4 Model B (4 GB)

    DEV-15447
    $59.95
    5
    Raspberry Pi 4 Model B (2 GB)

    Raspberry Pi 4 Model B (2 GB)

    DEV-15446
    $39.95
    2
    Raspberry Pi 3 A+

    Raspberry Pi 3 A+

    DEV-15139
    $29.95
    1
    Raspberry Pi Zero W (with Headers)

    Raspberry Pi Zero W (with Headers)

    DEV-15470
    $14.00
    1
    Note: When using the Raspberry Pi 4 with heat sink case, a compatible header that provides enough clearance and interfaces with the Auto pHAT is required.

    SD Cards

    These SD cards in our catalog are tested and known to work with all the models of the Raspberry Pi and the Jetson Nano (excluding the NOOBS card).

    microSD Card - 16GB (Class 10)

    microSD Card - 16GB (Class 10)

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

    microSD Card with Adapter - 64GB (Class 10)

    COM-14833
    $29.95
    SparkFun Noobs Card for Raspberry Pi (16GB)

    SparkFun Noobs Card for Raspberry Pi (16GB)

    COM-15052
    $19.95
    microSD Card with Adapter - 32GB (Class 10)

    microSD Card with Adapter - 32GB (Class 10)

    COM-14832
    $24.95
    Note: For first time Raspberry Pi users, we recommend using the NOOBS version as it has the required OS pre-installed.

    Power Supplies

    Use the appropriate power supply for the SCB you choose. The battery pack and USB-C cable are specifically for the Auto pHAT to supplement the current draw of the motor driver and servo controller.

    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
    Raspberry Pi Wall Adapter Power Supply - 5.1VDC, 3.0A, 15.3W (USB-C)

    Raspberry Pi Wall Adapter Power Supply - 5.1VDC, 3.0A, 15.3W (USB-C)

    TOL-15448
    $8.00
    Power Supply - 5V, 4A

    Power Supply - 5V, 4A

    TOL-15352
    $12.95
    Low Current Lithium Ion Battery Pack - 2.5Ah (USB)

    Low Current Lithium Ion Battery Pack - 2.5Ah (USB)

    TOL-15204
    $9.95
    1
    USB 3.1 Cable A to C - 3 Foot

    USB 3.1 Cable A to C - 3 Foot

    CAB-14743
    $4.95
    2

    Servos

    The Auto pHAT has 4 available servo channels. This is perfect if for users looking to add a pan-tilt bracket for their camera, a claw, or any other servo or PWM related mechanism (like a robotic arm).

    Pan/Tilt Bracket Kit (Single Attachment)

    Pan/Tilt Bracket Kit (Single Attachment)

    ROB-14391
    $6.95
    5
    Standard Gripper Kit A - Channel Mount

    Standard Gripper Kit A - Channel Mount

    ROB-13174
    $9.95
    4
    Standard Gripper Kit B - Straight Mount

    Standard Gripper Kit B - Straight Mount

    ROB-13175
    $9.95
    1

    Chassis, Motor, and Wheels

    The motor driver on the Auto pHAT has 2 H-Bridge drive channels for DC motors.

    Hobby Motor - Gear

    Hobby Motor - Gear

    ROB-11696
    $1.95
    4
    Micro Gearmotor - 90 RPM (6-12V)

    Micro Gearmotor - 90 RPM (6-12V)

    ROB-12285
    $12.95
    5
    Hobby Motor and Encoder Kit

    Hobby Motor and Encoder Kit

    ROB-13260
    $19.95
    4
    Planetary Gearmotor - 140RPM

    Planetary Gearmotor - 140RPM

    ROB-15277
    $5.95
    Note: Users looking to add brushless DC motors, which are usually driven by an ESC, shouldn't be using the H-Bridge. ESCs are controlled through a PWM signal and required a specific power source. The servo/PWM controller may work, but users should also consider the arming process.

    Besides a motor, users will also need a chassis or some kind of structure to assemble all the components on. You can't really call it a vehicle, if all you have is a motor.

    Robotics Shield Kit for Arduino - Parallax

    Robotics Shield Kit for Arduino - Parallax

    ROB-11494
    $139.95
    1
    GoPiGo Beginner Starter Kit

    GoPiGo Beginner Starter Kit

    ROB-14801
    $199.99
    Rover 5 Robot Platform

    Rover 5 Robot Platform

    ROB-10336
    $67.95
    2
    Circular Robotics Chassis Kit (Three-Layer)

    Circular Robotics Chassis Kit (Three-Layer)

    ROB-14339
    $19.95
    Actobotics Kit - ActoBitty 2

    Actobotics Kit - ActoBitty 2

    ROB-13047
    3
    STS-Pi - Build a Roving Robot!

    STS-Pi - Build a Roving Robot!

    DEV-15735

    Wheels... these are pretty self explanatory. If you don't have them, then you can't get rolling (or tracks for "track-tion").

    Wheel - 65mm (Rubber Tire, Pair)

    Wheel - 65mm (Rubber Tire, Pair)

    ROB-13259
    $2.95
    2
    Mecanum Wheels - 65mm, LEGO Compatible (4 Pack)

    Mecanum Wheels - 65mm, LEGO Compatible (4 Pack)

    ROB-15536
    $39.95

    Header

    This is an optional item. For users looking to stack HATs, a header might be required for additional clearance between boards or components.

    Note: Unfortunately, at this time, we do not have a compatible header. However, we are working on it. Users shouldn't use the Raspberry Pi GPIO Tall Header, as the (male) pins on the header aren't quite long enough to reach into the (female) socket on the Auto pHAT.

    Screw Driver

    To tighten and loosen the screw terminals, users will need a small flathead screw driver. The head will need to be ~1.5mm; anything around 2mm will most likely be too large.

    Tool Kit - Screwdriver and Bit Set

    Tool Kit - Screwdriver and Bit Set

    TOL-10865
    $9.95
    6
    iFixit Essential Electronics Toolkit

    iFixit Essential Electronics Toolkit

    TOL-15256
    $24.99
    Magnetic Screwdriver Set (20 Piece)

    Magnetic Screwdriver Set (20 Piece)

    TOL-15003
    $6.95
    1
    Electric Hobby Screwdriver Set

    Electric Hobby Screwdriver Set

    TOL-15548
    $39.95

    Click the button above to toggle a list of additional accessories that are available from our catalog.

    Peripherals

    For users looking to use the desktop graphical user interface (GUI), they will also need the following:
    • TV, Display, or Monitor
    • Compatible HDMI Cable
    • USB Keyboard and Mouse
    Displays
    For beginners we recommend using a modern TV (i.e. with an HDMI input) or computer monitor, as it will undoubtedly be easier and more intuitive for users to setup.
    Compatible HDMI Cable
    If you don't have an HDMI cable (and possible adapter), these have been tested to work with following Raspberry Pi models:
    Raspberry Pi Zero W model:
    Mini HDMI Cable - 3ft

    Mini HDMI Cable - 3ft

    CAB-14274
    $4.95
    2
    Raspberry Pi 3 A+/B+ models:
    HDMI Cable - 6ft

    HDMI Cable - 6ft

    CAB-11572
    $4.95
    1

    Note: If your display doesn't have an HDMI input, you will need to source an appropriate adapter. There are DVI and VGA to HDMI adapters, that will work on older computer monitors. Unfortunately, we don't have any adapters or a list of optional products for more outdated inputs (i.e. RCA, S-video, Component, or coaxial inputs).

    USB Keyboard and Mouse
    If you don't already have a USB keyboard and mouse, we do offer a multimedia keyboard that has been tested as a plug-and-play option for the Raspberry Pi models in our catalog.
    Multimedia Wireless Keyboard

    Multimedia Wireless Keyboard

    WIG-14271
    $29.95
    3

    Note: This keyboard is similar to a smaller laptop form factor in the button layout. Users with the Raspberry Pi Zero W models will need an additional USB (OTG) cable.

    SBC Kits

    Additionally, we do offer single board computer kits, which will include some of the accessories first-time users may already need.
    Raspberry Pi 3 B+ Starter Kit

    Raspberry Pi 3 B+ Starter Kit

    KIT-15361
    $91.95
    SparkFun JetBot AI Kit v2.0 Powered by Jetson Nano

    SparkFun JetBot AI Kit v2.0 Powered by Jetson Nano

    KIT-16390
    1
    SparkFun DLI Kit for Jetson Nano

    SparkFun DLI Kit for Jetson Nano

    KIT-16308
    $174.95
    SparkFun Raspberry Pi Zero W Basic Kit

    SparkFun Raspberry Pi Zero W Basic Kit

    KIT-14298
    $39.95
    3

    Suggested Reading

    Note: First time Raspberry Pi users should also head over to the Raspberry Pi Foundation website and check out their quickstart guides:

    We have also listed a few additional resources for users to familiarize themselves with the Raspberry Pi:

    Below are some of our related tutorials that may be of interest to beginners:

    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.

    Serial Terminal Basics

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

    SD Cards and Writing Images

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

    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.

    Headless Raspberry Pi Setup

    Configure a Raspberry Pi without a keyboard, mouse, or monitor.

    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.

    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.

    Hardware Overview

    Below, is an overview of the major hardware components on the Auto pHAT.

    Dimensions

    The overall dimensions of the Auto pHAT are 57mm x 65mm. For more details, users can check out the layout in the Eagle files. The board also features two cut-outs for the camera and display ribbon connections.

    Dimensions
    Dimensions of the Auto pHAT. (Click to enlarge)

    GPIO Connections

    As the Auto pHAT is also intended to integrate with other HATs, it is important to know all of the pin being utilized to avoid conflicts. Below is a layout of all the GPIO pins being utilized by the hardware on the Auto pHAT. (*Click the following links, for more information on the GPIO mapping of the Raspberry Pi or Jetson Nano.)

    GPIO Top
    GPIO header connection on the top of the Auto pHAT.
    GPIO Bottom
    GPIO header connection on the bottom of the Auto pHAT.
    (Click to enlarge)

    Raspberry Pi GPIO Map

    GPIO PinsStandard GPIO layout on the Raspberry Pi.

    Power Connections

    Power to the Auto pHAT is supplied through the GPIO pins; both 5V and 3.3V are utilized.

    Pin #GPIO
    13.3V
    173.3V
    25V
    45V
    6GND
    9GND
    Pin #GPIO
    14GND
    20GND
    30GND
    34GND
    39GND

    Qwiic (I2C)

    IMU (I2C)
    Pin #GPIOFunction
    3GPIO 02 (SDA)Qwiic (SDA)
    5GPIO 03 (SCL)Qwiic (SCL)
    26GPIO 7Interrupt


    Encoder (I2C)
    Pin #GPIOFunction
    3GPIO 02 (SDA)Qwiic (SDA)
    5GPIO 03 (SCL)Qwiic (SCL)
    7GPIO 4Interrupt
    Motor Driver (I2C)
    Pin #GPIOFunction
    3GPIO 02 (SDA)Qwiic (SDA)
    5GPIO 03 (SCL)Qwiic (SCL)
    Servo Controller (I2C)
    Pin #GPIOFunction
    3GPIO 02 (SDA)Qwiic (SDA)
    5GPIO 03 (SCL)Qwiic (SCL)
    Qwiic Connector
    Pin #GPIOFunction
    3GPIO 02 (SDA)Qwiic (SDA)
    5GPIO 03 (SCL)Qwiic (SCL)

    Servo Controller

    The servo controller utilizes the same PCA9685 IC used on the Pi Servo pHAT; however, only the first 4 PWM channels are broken out. The PCA9685 provides I2C control over the 16-channels of 12-bit pulse width modulation (PWM); although only the first 4-channels are available on the Auto pHAT. The default I2C address for the servo controller on the Auto pHAT is 0x40.

    PCA9685
    The PCA9685 16-channel PWM controller IC and output headers.
    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 8 available hardware configurable addresses
    • Configuration Jumpers: 0x40 to 0x47
    • Default: 0x40
    4 programmable addresses to allow simultaneous groups control of multiple devices:
    • 1- General All Call address.
    • 3- Sub Call addresses.
    Note: For more details on the PCA9685 and its utilization as a servo controller, check out the following hookup guides on the Pi Servo pHATs:

    Pi Servo Hat Hookup Guide

    September 14, 2017

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

    Pi Servo pHAT (v2) Hookup Guide

    July 11, 2019

    This hookup guide will get you started with connecting and using the Pi Servo pHAT on a Raspberry Pi.

    Motor Driver

    The motor driver consists of the same PSoC4245 and DRV8835 as the Serial Controlled Motor Driver and Qwiic Motor Driver. The DRV8835 H-Bridge provides two drive outputs, each capable of 1.2A at steady state. The default I2C address for the motor driver on the Auto pHAT is 0x5D.

    PSoc4245 and DRV8835
    The PSoc4245 microcontroller, DRV8835 H-Bridge, and screw terminal outputs.
    CharacteristicDescription
    Operating Voltage (VDD)3 V to 11 V (Hardwired: 5V)
    Drive Channels2 Channels
    Drive Strength 1.5A per channel (max.)
    1.2A (steady state)
    Drive Control 127 levels of control
    Direction inversion on a per motor basis
    Global Drive enable
    I2C Address 10 available hardware configurable addresses
    • Configuration Jumpers: 0x58 to 0x61
    • Default: 0x5D

    Thermal Management

    An important consideration for the motor driver is the thermal load due to the current draw of the motors. In order to dissipate the heat, users can use our Theragrip Thermal Tape to attach Small Heat Sinks across the thermally conductive area on the bottom of the board. As the thermal plane doesn't promote natural convection well, users can add a fan to help dissipate the energy, as well.

    Thermally conductive area
    Thermally conductive area on the bottom of the Auto pHAT.
    Temp to Current Load Curve
    Temperature to total driver load curve.
    (Click to enlarge)

    Note: For more details on the Serial Controller Motor Driver or Qwiic Motor Driver and its utilization, check out the following hookup guides on the Pi Servo pHATs:

    Serial Controlled Motor Driver Hookup Guide

    November 17, 2016

    Hookup guide for the Serial Controlled Motor Driver

    Hookup Guide for the Qwiic Motor Driver

    September 19, 2019

    Drive things "qwiic"-ly with the SparkFun Qwiic Motor Driver!

    Encoder Reader

    At the heart of the encoder reader is an ATtiny84, which is utilized on our pseudo I2C devices. The encoder reader is based off of the Qwiic Twist, but is capable of reading two, separate quadrature encoders. The default I2C address for the servo controller on the Auto pHAT is 0x73.

    ATtiny84 encoder reader
    The ATtiny84 dual encoder reader and screw terminal inputs.

    9-DoF IMU

    The 9-DoF (degree of freedom) IMU is the same ICM20948 IC used on the 9DoF IMU Breakout. It provides 10 unique measurements: 3 axes of acceleration, rotational rate, and magnetic strength data, as well as, internal temperature. Users should note the location of the IMU and the orientation of the axes (labeled on the board), when taking measurements. The default I2C address for the IMU on the Auto pHAT is 0x69.

    ICM20948
    The ICM20948 9-DoF IMU.
    CharacteristicDescription
    Operating Voltage (VDD)1.71 V to 3.6 V (Hardwired: 1.8V)
    Operating Temperature-40°C to 85°C
    Gyroscope
    Full Scale Ranges:
    • &PlusMinus;250 dps
    • &PlusMinus;500 dps
    • &PlusMinus;1000 dps
    • &PlusMinus;2000 dps
    Sensitivity:
    • &PlusMinus;(1/131) dps
    • &PlusMinus;(1/65.5) dps
    • &PlusMinus;(1/32.8) dps
    • &PlusMinus;(1/16.4) dps
    Output Data Rate: 562.5, 1125, 9000 Hz
    Accelerometer
    Full Scale Ranges:
    • &PlusMinus;2 G
    • &PlusMinus;4 G
    • &PlusMinus;8 G
    • &PlusMinus;16 G
    Sensitivity:
    • &PlusMinus;(1/16384) G
    • &PlusMinus;(1/8192) G<
    • &PlusMinus;(1/4096) G<
    • &PlusMinus;(1/2048) G<
    Output Data Rate: 562.5, 1125, 4500 Hz
    Magnetometer Full Scale Range: &PlusMinus;4900 µT
    Sensitivity: .15 µT
    Output Data Rate: 100 Hz
    I2C Address 2 hardware configurable addresses:
    • 0x69: Jumper closed (Default)
    • 0x68: Jumper open

    Note: For more details on the ICM-20948 and its utilization as an IMU, check out the following hookup guide:

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

    June 27, 2019

    How to use the SparkFun 9DoF ICM-20948 breakout board for your motion sensing projects. This breakout is ideal for wearable sensors and IoT applications.

    Qwiic Connector

    A connector is provided for attaching other Qwiic devices.

    Auto pHAT Qwiic Connector
    Qwiic connector.

    Note: While most of our Qwiic devices should be compatible with a single board computer (SBC), not all have a supported Python package. Users who are unfamiliar with our Qwiic connect system, can check out the video below:

    Hardware Assembly

    Assembly for the Auto pHAT is fairly straight forward. It plugs directly into the GPIO pins of a Raspberry Pi. Most importantly, users need pay attention to the orientation of the pHAT and double check that the pin are lined up properly. below are a few examples for users to follow.

    Auto pHAT on Pi3 Model A+
    Auto pHAT on Raspberry Pi 3 Model A+.
    Auto pHAT on Pi3 Model B
    Auto pHAT on Raspberry Pi 3 Model B.
    (Click images to enlarge)

    Attaching Accessories

    Users will want to attach additional accessories to the Auto pHAT.

    Servos

    Servos are attached to the 3x4 right angle header. The channels and pins are indicated on the top and right of the header, when reading the silk screen. Below is an example with servos connected to channels 0 and 3. Users should pay close attention to the orientation of the servo connector, in order to match up the pin connections properly.

    Servo on channels 0 and 3
    Servos attached to channels 0 and 3.
    Close up of wiring orientation
    Verify that the connector is in the proper orientation.
    (*Hint: The signal wire is the uppermost header.)
    (Click images to enlarge)

    Note: Users who are unfamiliar with servos and their operation should check out our hobby servo and basic servo control tutorials. Additionally, here is a quick reference for common servo wiring colors.

    Hobby Servo Tutorial

    May 26, 2016

    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.

    Basic Servo Control for Beginners

    February 25, 2020

    An introductory tutorial demonstrating several ways to use and interact with servo motors!

    servo cable colors

    Annotated image of servo wiring harness. (Click to enlarge)

    Motors

    DC motors should be connected to the inner screw terminals indicated by MTRA and MTRB on the silk screen. Below, is an example of a pair of motors connected to the Auto pHAT. The orientation of the wires (between 1 or 2) shouldn't matter as the drive direction can be configured in software.

    motors attached
    DC hobby motors (with wheels attached) connected to the Auto pHAT.
    external power through USB-C
    An external power source provided by the USB-C connetor.
    (Click images to enlarge)

    Note: Users unfamiliar with DC motors should check out our motors tutorial.

    Motors and Selecting the Right One

    December 12, 2013

    Learn all about different kinds of motors and how they operate.

    Quadrature Encoders

    Connecting quadrature encoders to the Auto pHAT is relatively simple with the screw terminals. Users should use the silk screen on the board (+, A, B, and -) to match the connections for the encoder. The datasheet for the encoders should be used if the connections aren't apparent or labeled on the product.

    Note: This section is in progress while we await the arrival of the encoder embedded motors.

    Note: Users who are unfamiliar with quadrature encoders and their operation should check out our Adventures in Science blog post on encoders.

    Clearance Issues

    Another consideration is the clearance of the pHAT from other components. Users can cover the header and screw terminal through hole pins with an insulator to avoid shorting the pins. Additionally, if the clearance between the pHAT and other components (including things like a the heat sink case for the Raspberry Pi 4) becomes an issue, a header should be used to increase the spacing.

    Note: The details for this section are in progress while we await the arrival of the compatible header.

    Desktop

    To configure the Raspberry Pi for use with the Auto pHAT, the PIXEL desktop is recommended. It will be the most convenient for users, but users can still use other methods like SSH to remotely access the Raspberry Pi. To utilize the desktop, users will need to add peripherals like a monitor and keyboard.

    Desktop setup
    Pi 3 Model B setup to access the PIXEL desktop. (Click to enlarge)

    Software Configuration

    Enable the I2C Bus

    Configuring an OS for the Auto pHAT is relatively simple; the I2C interface will need to be enabled.

    Nvidia Jetson

    The I2C bus on the Nvidia Jetson is enabled by default; no configuration is necessary.

    Raspberry Pi

    On the Raspberry Pi, this is easily accomplished within the Raspberry Pi PIXEL desktop. Using the graphical Raspberry Pi Configuration application from the Preferences menu will be the most user friendly option. Users can also make changes through the console based raspi-config application.

    configuration app

    Raspberry Pi Configuration application. (Click to enlarge)

    raspi-config tool

    From the Interfaces tab, enable the I2C interface. (Click to enlarge)

    Once done, click the OK button. Reboot the Raspberry Pi when prompted.

    Install the Python Packages

    Note: This tutorial assumes you are using the latest version of Python 3. If this is your first time using Python or I2C hardware on a Raspberry Pi, please checkout our tutorial on Python Programming with the Raspberry Pi and the Raspberry Pi SPI and I2C Tutorial.

    We've written a Python packages to easily get setup and utilize the Auto pHAT. There are two methods for installing the Python packages:

    1. Install the all inclusive SparkFun Qwiic Python package.
    2. Independently install the various Python packages:
      • pi-servo-hat
        • sparkfun-qwiic-pca9685
      • sparkfun-qwiic-scmd
      • sparkfun-qwiic-dual-encoder-reader
      • sparkfun-qwiic-icm20948

    The all inclusive SparkFun Qwiic Python package, is recommended as is also installs the required I2C driver as well.

    Note: Don't forget to double check that the hardware I2C connection is enabled on your Raspberry Pi or other single board computer.

    SparkFun Qwiic Package

    This repository is hosted on PyPi as the sparkfun-qwiic package. On systems that support PyPi installation via pip3 (use pip for Python 2) is simple, using the following commands:

    For all users (note: the user must have sudo privileges):

    language:bash
    sudo pip3 install sparkfun-qwiic
    

    For the current user:

    language:bash
    pip3 install sparkfun-qwiic
    

    Upgrading the Python Package

    In the future, changes to the Python package might be made. Updating the installed packages has to be done individually for each package (i.e. sub-modules and dependencies won't update automatically and must be updated manually). For example, with the sparkfun-qwiic-scmd Python package use the following command (use pip for Python 2):

    For all users (note: the user must have sudo privileges):

    language:bash
    sudo pip3 install --upgrade sparkfun-qwiic-scmd
    

    For the current user:

    language:bash
    pip3 install --upgrade sparkfun-qwiic-scmd
    

    Python Package Examples

    Servo Controller

    Documentation and examples for utilizing the servo controller is hosted on ReadtheDocs.

    Note: The tutorials below, include other examples for the utilization of the sparkfun-pi-servo-hat Python package.

    Pi Servo pHAT (v2) Hookup Guide

    July 11, 2019

    This hookup guide will get you started with connecting and using the Pi Servo pHAT on a Raspberry Pi.

    Basic Servo Control for Beginners

    February 25, 2020

    An introductory tutorial demonstrating several ways to use and interact with servo motors!

    Setting Up the Pi Zero Wireless Pan-Tilt Camera

    September 14, 2017

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

    Demo Example

    This example is pulled from the examples in the ReadtheDocs documentation. It should be used with a 90 degree (range of rotation) servo on channel 0 of the Auto pHAT. It will swing the servo arm between 0° and 90°, in a loop.

    #!/usr/bin/env python
    #-----------------------------------------------------------------------
    # Pi Servo Hat - Example 1
    #-----------------------------------------------------------------------
    #
    # Written by  SparkFun Electronics, June 2019
    # Author: Wes Furuya
    #
    # Compatibility:
    #     * Original: https://www.sparkfun.com/products/14328
    #     * v2: https://www.sparkfun.com/products/15316
    # 
    # Do you like this library? Help support SparkFun. Buy a board!
    # For more information on Pi Servo Hat, check out the product page
    # linked above.
    #
    # This program is distributed in the hope that it will be useful, but
    # WITHOUT ANY WARRANTY without even the implied warranty of
    # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
    # General Public License for more details.
    #
    # You should have received a copy of the GNU General Public License
    # along with this program.  If not, see <http:www.gnu.org/licenses/>.
    #
    #=======================================================================
    # Copyright (c) 2019 SparkFun Electronics
    #
    # Permission is hereby granted, free of charge, to any person obtaining
    # a copy of this software and associated documentation files (the
    # "Software"), to deal in the Software without restriction, including
    # without limitation the rights to use, copy, modify, merge, publish,
    # distribute, sublicense, and/or sell copies of the Software, and to
    # permit persons to whom the Software is furnished to do so, subject to
    # the following conditions:
    #
    # The above copyright notice and this permission notice shall be
    # included in all copies or substantial portions of the Software.
    #
    # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
    # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
    # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
    # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
    # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    #=======================================================================
    
    """
    This example should be used with a 90 degree (range of rotation) servo
    on channel 0 of the Pi Servo Hat.
    
    The extended code (commented out), at the end of the example could be
    used to test the full range of the servo motion. However, users should
    be wary as they can damage their servo by giving it a position outside
    the standard range of motion.
    """
    
    import pi_servo_hat
    import time
    
    # Initialize Constructor
    test = pi_servo_hat.PiServoHat()
    
    # Restart Servo Hat (in case Hat is frozen/locked)
    test.restart()
    
    # Test Run
    #########################################
    # Moves servo position to 0 degrees (1ms), Channel 0
    test.move_servo_position(0, 0)
    
    # Pause 1 sec
    time.sleep(1)
    
    # Moves servo position to 90 degrees (2ms), Channel 0
    test.move_servo_position(0, 90)
    
    # Pause 1 sec
    time.sleep(1)
    
    # Sweep
    #########################################
    while True:
        for i in range(0, 90):
            print(i)
            test.move_servo_position(0, i)
            time.sleep(.001)
        for i in range(90, 0, -1):
            print(i)
            test.move_servo_position(0, i)
            time.sleep(.001)
    
    #########################################
    # Code below may damage servo, use with caution
    # Test sweep for full range of servo (outside 0 to 90 degrees).
    # while True:
    #     for i in range(-23, 100):
    #         print(i)
    #         test.move_servo_position(0, i)
    #         time.sleep(.001)
    #     for i in range(100, -23, -1):
    #         print(i)
    #         test.move_servo_position(0, i)
    #         time.sleep(.001)
    

    Motor Driver

    Documentation and examples for utilizing the motor driver is hosted on ReadtheDocs.

    Demo Example

    This example is pulled from the examples in the ReadtheDocs documentation. It should be used with a DC motor on MTRA of the Auto pHAT. It will increase and decrease the speed between the 20 and 254 levels, in a loop.

    #!/usr/bin/env python
    #-----------------------------------------------------------------------------
    # A simple test to speed up and slow down 1 motor.
    #------------------------------------------------------------------------
    #
    # Written by Mark Lindemer
    # SparkFun Electronics, April 2020
    # 
    # This python library supports the SparkFun Electroncis qwiic 
    # qwiic sensor/board ecosystem on a Raspberry Pi (and compatable) single
    # board computers. 
    #
    # More information on qwiic is at https://www.sparkfun.com/qwiic
    #
    # Do you like this library? Help support SparkFun. Buy a board!
    #
    #==================================================================================
    # Copyright (c) 2019 SparkFun Electronics
    #
    # Permission is hereby granted, free of charge, to any person obtaining a copy 
    # of this software and associated documentation files (the "Software"), to deal 
    # in the Software without restriction, including without limitation the rights 
    # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
    # copies of the Software, and to permit persons to whom the Software is 
    # furnished to do so, subject to the following conditions:
    #
    # The above copyright notice and this permission notice shall be included in all 
    # copies or substantial portions of the Software.
    #
    # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
    # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
    # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
    # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
    # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
    # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 
    # SOFTWARE.
    #==================================================================================
    # Example 1
    #
    
    from __future__ import print_function
    import time
    import sys
    import math
    import qwiic_scmd
    
    myMotor = qwiic_scmd.QwiicScmd()
    
    def runExample():
        print("Motor Test.")
        R_MTR = 0
        L_MTR = 1
        FWD = 0
        BWD = 1
    
        if myMotor.connected == False:
            print("Motor Driver not connected. Check connections.", \
                file=sys.stderr)
            return
        myMotor.begin()
        print("Motor initialized.")
        time.sleep(.250)
    
        # Zero Motor Speeds
        myMotor.set_drive(0,0,0)
        myMotor.set_drive(1,0,0)
    
        myMotor.enable()
        print("Motor enabled")
        time.sleep(.250)
    
    
        while True:
            speed = 20
            for speed in range(20,255):
                print(speed)
                myMotor.set_drive(R_MTR,FWD,speed)
                time.sleep(.05)
            for speed in range(254,20, -1):
                print(speed)
                myMotor.set_drive(R_MTR,FWD,speed)
                time.sleep(.05)
    
    if __name__ == '__main__':
        try:
            runExample()
        except (KeyboardInterrupt, SystemExit) as exErr:
            print("Ending example.")
            myMotor.disable()
            sys.exit(0)
    

    Encoder Reader

    Documentation and examples for utilizing the encoder reader is hosted on ReadtheDocs.

    Demo Example

    This example is pulled from the examples in the ReadtheDocs documentation. It should be used with quadrature encoders attached to both ENC1 and ENC2 on the Auto pHAT. It will read and print out the encoder position; the ticker counter range rolls up to 32767 ticks.

    #!/usr/bin/env python
    #-----------------------------------------------------------------------------
    # ex1_qwiic_dual_encoder_reader.py
    #
    # Simple Example demonstrating how to read encoder counts for the Qwiic Dual Encoder Reader (as part of the SparkFun Auto pHAT)
    #------------------------------------------------------------------------
    #
    # Written by  SparkFun Electronics, May 2019
    # 
    # This python library supports the SparkFun Electroncis qwiic 
    # qwiic sensor/board ecosystem on a Raspberry Pi (and compatable) single
    # board computers. 
    #
    # More information on qwiic is at https://www.sparkfun.com/qwiic
    #
    # Do you like this library? Help support SparkFun. Buy a board!
    #
    #==================================================================================
    # Copyright (c) 2019 SparkFun Electronics
    #
    # Permission is hereby granted, free of charge, to any person obtaining a copy 
    # of this software and associated documentation files (the "Software"), to deal 
    # in the Software without restriction, including without limitation the rights 
    # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
    # copies of the Software, and to permit persons to whom the Software is 
    # furnished to do so, subject to the following conditions:
    #
    # The above copyright notice and this permission notice shall be included in all 
    # copies or substantial portions of the Software.
    #
    # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
    # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
    # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
    # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
    # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
    # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 
    # SOFTWARE.
    #==================================================================================
    # Example 1
    #
    
    from __future__ import print_function
    import qwiic_dual_encoder_reader
    import time
    import sys
    
    def runExample():
    
        print("\nSparkFun Qwiic Dual Encoder Reader   Example 1\n")
        myEncoders = qwiic_dual_encoder_reader.QwiicDualEncoderReader()
    
        if myEncoders.connected == False:
            print("The Qwiic Dual Encoder Reader device isn't connected to the system. Please check your connection", \
                file=sys.stderr)
            return
    
        myEncoders.begin()
    
        while True:
    
            print("Count1: %d, Count2: %s" % (myEncoders.count1, \
                myEncoders.count2, \
                ))
    
            time.sleep(.3)
    
    if __name__ == '__main__':
        try:
            runExample()
        except (KeyboardInterrupt, SystemExit) as exErr:
            print("\nEnding Example 1")
            sys.exit(0)
    

    9-DoF IMU

    Documentation and an example for utilizing the IMU is hosted on ReadtheDocs.

    Demo Example

    This example is pulled from the examples in the ReadtheDocs documentation. It display the raw data in the following order: a_x, a_y, a_z, g_x, g_y, g_z, m_x, m_y, and m_z.

    #!/usr/bin/env python
    #-----------------------------------------------------------------------------
    # ex1_qwiic_ICM20948.py
    #
    # Simple Example for the Qwiic ICM20948 Device
    #------------------------------------------------------------------------
    #
    # Written by  SparkFun Electronics, March 2020
    # 
    # This python library supports the SparkFun Electroncis qwiic 
    # qwiic sensor/board ecosystem on a Raspberry Pi (and compatable) single
    # board computers. 
    #
    # More information on qwiic is at https://www.sparkfun.com/qwiic
    #
    # Do you like this library? Help support SparkFun. Buy a board!
    #
    #==================================================================================
    # Copyright (c) 2019 SparkFun Electronics
    #
    # Permission is hereby granted, free of charge, to any person obtaining a copy 
    # of this software and associated documentation files (the "Software"), to deal 
    # in the Software without restriction, including without limitation the rights 
    # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
    # copies of the Software, and to permit persons to whom the Software is 
    # furnished to do so, subject to the following conditions:
    #
    # The above copyright notice and this permission notice shall be included in all 
    # copies or substantial portions of the Software.
    #
    # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
    # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
    # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
    # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
    # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
    # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 
    # SOFTWARE.
    #==================================================================================
    # Example 1
    #
    
    from __future__ import print_function
    import qwiic_icm20948
    import time
    import sys
    
    def runExample():
    
        print("\nSparkFun 9DoF ICM-20948 Sensor  Example 1\n")
        IMU = qwiic_icm20948.QwiicIcm20948()
    
        if IMU.connected == False:
            print("The Qwiic ICM20948 device isn't connected to the system. Please check your connection", \
                file=sys.stderr)
            return
    
        IMU.begin()
    
        while True:
            if IMU.dataReady():
                IMU.getAgmt() # read all axis and temp from sensor, note this also updates all instance variables
                print(\
                 '{: 06d}'.format(IMU.axRaw)\
                , '\t', '{: 06d}'.format(IMU.ayRaw)\
                , '\t', '{: 06d}'.format(IMU.azRaw)\
                , '\t', '{: 06d}'.format(IMU.gxRaw)\
                , '\t', '{: 06d}'.format(IMU.gyRaw)\
                , '\t', '{: 06d}'.format(IMU.gzRaw)\
                , '\t', '{: 06d}'.format(IMU.mxRaw)\
                , '\t', '{: 06d}'.format(IMU.myRaw)\
                , '\t', '{: 06d}'.format(IMU.mzRaw)\
                )
                time.sleep(0.03)
            else:
                print("Waiting for data")
                time.sleep(0.5)
    
    if __name__ == '__main__':
        try:
            runExample()
        except (KeyboardInterrupt, SystemExit) as exErr:
            print("\nEnding Example 1")
            sys.exit(0)
    
    Challenge: Now that you are familiar with the basics, flew that robotics muscle. Try to implement a traction control or an anti-lock braking system (ABS) to show off your prowess.

    Troubleshooting

    Raspberry Pi

    For comprehensive information or troubleshooting issues, on the Raspberry Pi, users should check out the Raspberry Pi Foundation website and their forum.

    As a general guideline, users should use the following resources when looking for technical information or assistance that is specifically related to the Raspberry Pi itself:

    1. Raspberry Pi FAQ
    2. Raspberry Pi Beginner's Subforum
    3. Raspberry Pi Documentation and Help Guides
    4. Raspberry Pi Forum

    Nvidia Jetson Nano

    For comprehensive information or troubleshooting issues, on the Nvidia Jetson, users should check out the Nvidia website and their forum.

    As a general guideline, users should use the following resources when looking for technical information or assistance that is specifically related to the Jetson Nano itself:

    1. Jetson Support Resources
    2. Jetson Nano Getting Started Guide
    3. Developer Kit User Manual
    4. Jetson Nano Wiki
    5. Nvidia FAQ
    6. Jetson Forum
    7. Jetpack Documentation

    For users looking for technical assistance, click on the link. There you will find, basic troubleshooting tips and instructions to get started with posting a topic in our forum. Our technical support team will do their best to assist you.

    Resources and Going Further

    Product Information

    Nvidia Jetson Resources:

    Jetson Support Resources

    Raspberry Pi Resources:

    Raspberry Pi Help Guides & Documentation:


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

    Jetson Nano + Shero RVR Mash-up (PART 1)

    $
    0
    0

    Jetson Nano + Shero RVR Mash-up (PART 1) a learn.sparkfun.com tutorial

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

    Introduction

    We finally jumped on a project that we have been wanting to do for a while now: a mash-up of two robotics kits that we released over the past year! Those kits are the Advanced Autonomous kit for the Sphero RVR and our AI JetBot kit for the NVIDIA Jetson Nano. Both projects were fun to work on during launch and both products have astounding quality in their own perspective markets so we're very excited to combine them together!

    SparkFun Advanced Autonomous Kit for Sphero RVR

    SparkFun Advanced Autonomous Kit for Sphero RVR

    KIT-15303
    $164.95
    SparkFun JetBot AI Kit v2.0 Powered by Jetson Nano

    SparkFun JetBot AI Kit v2.0 Powered by Jetson Nano

    KIT-16390
    1
    Sphero RVR - Programmable Robot

    Sphero RVR - Programmable Robot

    ROB-15304
    $249.99

    We set about building this mash-up and this tutorial as a guide for you to follow along with us in building your own Jetson Nano powered Sphero RVR. We built the bot almost entirely from parts found in the two kits with and placed on top of a Sphero RVR.

    Fully assembled Jetson RVR Robot

    With all of this being said and documented if you choose to build your Nano RVR mash-up feel free to riff on what we did. There is no real right way to do this, it was us in the shop for an afternoon being creative. Your sensors, board placement and hardware choices may vary. Use this tutorial more as… “guidelines”.

    Hardware Overview

    As mentioned in the Introduction this project is a mash-up of two different kits, plus the Sphero RVR. We tried our best to source all of the parts individually for you, but many bits and pieces are used from the two original kits. Here is a wishlist of the major parts that would be required. In this case the only thing you would need to fabricate would be the camera mounting bracket if you dont have the one from the JetBot 2.1 kit.

    Most of the hardware from each kit can be found in our catalog, but with a few bits and pieces thrown in as well. If you are sourcing parts individually rather than through our kits I have included the important parts we do not carry as individual components below.

    Other Parts

    3M Dual Lock - From the Jetbot AI Kit, I use it to mount the camera and battery
    USB Battery Bank- For powering the Jetson Nano separate from the RVR, it comes with the Jetbot AI kit. If you source your own battery pack, make sure it can supply at least 3A@5V.

    Mounting the NVIDIA Jetson Nano

    Using the RVR as a platform for this robot enabled me to work with their topper plate system which makes building and fitting everything we needed onto the robot so much easier.

    Instead of working around the robot and trying to figure out how to mount something and the repetitive task of bolting something down only to remove it again later, all I had to do was remove the topper plate and as long as it fit on that plate I knew it would mount on the robot without a problem.

    Jetson Nano and Sphero RVR

    The RVR comes with a number of topper plates and one of them is specifically designed for mounting your own microcontrollers/single board computers to it. After trying a number of configurations of possible orientations of the Nano on the mounting plate I came to the conclusion that it wouldn't work for what I wanted to do. For this build I needed space to put the Nano and mount the camera while keeping wiring as clean as possible as well as space for the Servo pHAT or any other hardware connection to the GPIO headers in the rear of the robot.
    rvr topper

    With all of that in mind there was only one option: modify the stock topper plate of the RVR to mount the Jetson Nano.

    Modified topper

    Planning for Mounting Holes

    Before just going at it with a drill and making a few holes here and there, I wanted to be sure that I had all of the clearances needed underneath the build plate. I also needed to figure out what I would need to modify further so that I would have access to the UART/USB port of the RVR for hookup later.

    I placed the Jetson Nano on the topper where I wanted it, and using an awl, I carefully marked the locations of the four mounting holes. You can do this with a super fine tip sharpie as well. I used an awl so that the small mark would be used as a pilot for when I drilled the four mounting holes later.

    Marking the mounting holes on the RVR Topper

    Serial / USB Port Access

    One of the downsides of using the basic topper plate for this project is that it doesn’t have any access to the USB / UART ports on the RVR. So, I had to make my own! With the plate mounted to the RVR, I could see the port through the translucent plastic and needed to cut that section of the topper away to have access to the port.

    RVR Topper cut for USB Port

    I marked the corners as best as I could and then, using a sharpie, drew a box using the dots as my inside corners of the rectangle that I would cut out using my bandsaw. The final product isn't perfectly square, but it doesn’t need to be!

    I then cut away the area for the UART access and drilled the four mounting holes using my drill press.

    Modified Topper back on the RVR
    Yes, one hole was off by a bit and the drill bit wandered… I redrilled it and it is good enough given that the other three holes were aligned perfectly.

    Adding the Nano

    With the holes drilled in the topper plate it was now time to mount the Jetson Nano to it.

    Aluminum Standoffs from the RVR Topper Kit

    I used the aluminum standoffs from the Autonomous RVR Topper Kit as they give enough height to slide the battery bank under the Developer Kit.
    Standoffs mounted to the Jetson Nano Dev Kit

    My first inclination was to use a nut from the bottom of the topper plate and use screws from the top so that I could quickly and efficiently remove the Jetson Nano from the topper place without accessing the bottom, but the thickness of the topper plate become an issue for the stud length of the standoff. Instead, I used the screws to come up from the bottom and used nuts to hold the Developer Kit down.

    Jetson Nano secured to the RVR Topper

    With the Dev Kit mounted to the topper plate I checked the fit with the RVR. Everything seemed to fit just fine and I took a nail file to the edges that I cut in the plate to smooth them out a bit.

    Jetson Nano Peripherals

    The Jetson Nano requires a few things to get up and running before we dig too deep into building up the robot and forget about them!

    Micro SD Card and JetBot image

    Since this is a mash-up of two kits I had the JetBot image already burned to the SD card that came with that kit. This was a nice option because the image already has the JetBot software on it and running out of the box which prints out the IP address of the bot over the OLED display and also has the drivers for the included Edimax WiFi adapter already installed.

    If you are building this project from scratch I highly recommend starting with our JetBot image and burning it to an SD card. You can find our image and instructions for preparing the SD card, burning it and configuring it at the end of our JetBot Assembly Guide. You can find the Software Setup section of that guide here.

    Once you have an a microSD card with the JetBot image on it, insert it into the microSD card slot on the NVIDIA Jetson Nano. The card will give a satisfying click when inserted far enough. That’s it, you are all set!

    microSD card inserted into the Nano

    Edimax WiFi Adapter

    The JetBot requires a WiFi connection so that you can communicate with it while it is free to roam/drive around untethered.

    edimax photo

    The Edimax N150 WiFi adapter is what we use in our JetBot kit and our go-to WiFi accessory for working with the NVIDIA Jetson Nano.

    Installing the N150 is as simple as inserting it into an open USB port on the Jetson Nano. Software setup is a breeze if you are using our JetBot microSD card image. It should work out of the box.

    If you are building this project from scratch you will need to install the drivers for the WiFi adapter. You can find our tutorial for how to do that here:

    New!

    Adding WiFi to the NVIDIA Jetson

    April 23, 2020

    Step by step instructions for setting up and installing the Edimax N150 USB WiFi/BLE adapter on your NVIDIA Jetson Nano

    SparkFun Hardware

    With the Jetson Nano Dev kit mounted to the topper plate it was now time to start to build out the rest of my system's hardware. I used a combination of SparkFun hardware from both the JetBot as well as the Autonomous Kit for the RVR.

    Note: This guide covers adding the hardware needed to get JetBot functionality on top of the Sphero RVR. We know that if you have purchased both kits you also have access to other Qwiic boards such as a GPS and the Time of Flight distance sensor. Both of those boards are have a SparkFun Python library and you can integrate them into the project without a problem. In fact we may cover both of those options in the software guide for this project. But for now, we will stick to getting a functioning platform up and running!

    SparkFun Servo pHAT

    The crux of this project is the SparkFun Servo pHAT.

    SparkFun Servo pHAT

    This pHAT enables a number of things for this project. Probably the most important is that it gets us access to a 4 pin UART connection to enable clean and straightforward wiring for the UART communication wires between the Nano and the RVR.

    Servo pHAT RVR UART Header Highlighted

    It is also how we are going to provide power to the Jetson Nano through the USB-C connector as well as other peripheral hardware using the Qwiic connector on it as well.

    Servo pHAT USB C connector highlighted

    We use this connector for power rather than the USB or barrel jack power supply on the Jetson Nano Developer Kit so that we have access to raw power for both the Qwiic boards but more importantly any other hardware we want to hook up such as servo motors, etc.

    Micro OLED Breakout (Qwiic)

    Micro OLED Breakout

    If you own a JetBot kit, you know that the OLED display is a really handy part of the bot. The JetBot uses the OLED to print out important information about the JetBot's network connection, CPU and memory usage as well as its IP address. This is really handy when you need to access and program your robot through the Jupyter Notebooks application which you can access via a browser pointed at the JetBot's IP address. More on that in the programming tutorial!

    Mounting the display was a tricky problem for this project, but with some ingenuity and a few 90 degree mounting brackets I found a good place to put it that is out of the way, but still accessible and visible.

    OLED mounted to the Servo pHAT

    These 90 degree brackets are one thing that I used that was not included in one of the two kits I started with.

    Angle bracked 4-40

    With the display mounted to the Servo pHAT and connected to it via a Qwiic cable I placed the pHAT on the Jetson Nano Dev kit as shown.

    Assembled Jetson Nano and Servo pHAT on the Sphero Topper

    Camera and Camera Mount

    The camera mounting portion of this project was by far the most DIY modification and has been iterated on over time as JetBot itself has been changed up over the course of the year.

    Camera Mount

    When this project initially started, the camera mount that came with our original JetBot was made of clear acrylic and wouldn't work with how things were laid out on the RVR.

    JetBot v1 Acrylic Camera Mount

    For the machine learning aspect of JetBot to work properly the camera needed to be at a specific height, distance from the front axle of the drive wheels as well as tilt angle. So, with that information in hand I built my own camera mount from a bit of scrap MDF board and hot glue. This solution worked out well, but it does have a few downsides, one of them being that I used glue which doesn’t bode well when I need to remove or replace parts. But, for initial ideation it worked perfectly.

    Camera Mount Revision

    The advent of JetBot 2.0 and the change in chassis and how we mount the camera on it gave me an opportunity to revise my own camera mount. (Read as "a better mount to modify for our own use!")

    JetBot v2.0 Modified Camera Mount

    With the new camera mount in hand I used my disk sander to remove the tabs on the bottom of the acrylic mount so that it would sit relatively flat on the RVR.

    Camera Mount laying flat

    I positioned as accurately as it could be compared to the old DIY mount and a few reference marks were made before removing it. I also swapped out the plastic screw and nut that normally mount the camera to the bracket for a bit of 3M Dual Lock so that I could reposition the camera if needed. I drilled holes in the topper plate to run screws through and secure the new mount. Only use two of the holes as it would be more than enough for this light camera. I chose the two furthest back but feel free to use whichever holes work best for your robot.

    Camera mounted to RVR Topper

    Camera Hookup

    With the mounting bracket assembled and mounted to the topper plate I added the camera to the mounting bracket using some 3M Dual Lock rather than the plastic screws as shown in the JetBot assembly guide. The idea behind this would be to make it more adjustable if needed since it will be on the RVR chassis and not as optimally positioned as a chassis designed for it.

    Camera ribbon cable connected to Jetson Nano

    With the camera mounted, hook up is rather straightforward using the camera cable connector on the development kit carrier board. If you are using the original carrier board, you only have one choice in terms of camera connector.

    Note: If you have the updated B01 carrier with two camera connectors use the camera 0 connector. Be sure to be gentle when connecting the camera! The connectors on the carrier boards are rather fragile and can break easily!

    Final Wiring

    With the hardware assembly for the most part complete. It is now time to mount the plate with our hardware to the RVR and to do some final wiring, which is rather minimal!

    4 Pin UART Cable

    The Jetson Nano communicates with the Sphero RVR via UART and a raw UART connection on the RVR next to the USB port. This four pin connector uses a 4 wire female wiring harness to connect it to the “RVR” connector on the Servo pHAT.

    https://cdn.sparkfun.com//assets/parts/4/8/2/1/10369-01.jpg

    When connecting the pHAT to the RVR take note of the orientation of the connections. On the RVR, the UART Rx and Tx pins are oriented towards the “front” of the RVR with power (5V and GND) towards the back. You should insert the harness with the green wire pointed “forward”

    Close-up shot of the 4-pin cable

    The pHAT is the opposite of the RVR connector. The Rx and Tx connections are “forward” in this current configuration, so the harness should be connected to the pHAT with the red wire oriented “forward”.

    Showing the 4-pin cable connecting the Servo pHAT and the Sphero RVR

    USB Battery Bank

    The last thing to do before hardware assembly is completely finished is adding the USB battery bank and powering the Jetson Nano. The project uses the USB battery bank we use in our JetBot kit. It is perfect for powering the Jetson Nano and the peripherals while the RVR is powered through its own battery.

    USB Battery Bank

    Originally we wanted to mount the Jetson on four standoffs rather than three (You can probably see 4 holes in close-up shots of the topper plate), but once we went to fit the battery on the bot it would not fit between the standoffs. To fix this we removed one so the battery would fit in the proper orientation.

    The standoffs give just enough room for the battery to slide under the carrier board of the Jetson Nano. It should be snug enough that you don't need anything to keep it in place, but if you feel that you do, I highly recommend using 3M Dual Lock (we provide you with a length in our JetBot kit) or even a bit of two sided tape for just a bit of extra friction to keep it in place.

    With the battery in place add a USB-C cable from the battery pack to the USB-C port on the SparkFun Servo pHAT. If you are using the battery pack from the JetBot Kit, connect your USB cable to the orange (3A) USB port. The Jetson Nano should power up as soon as you do.

    Battery Bank connected to the Servo pHAT's USB C Connector

    In Closing and Next Steps

    With that, the basic structure of your NVIDIA Jetson Nano powered Sphero RVR is ready for software setup and programming.

    Fully assembled robot

    As we alluded to throughout this tutorial this is just the start for this robot! We wanted to give you something to start with, and be able to expand on that by adding more sensors, servo motors, etc. The expansion of this project would be a breeze using Qwiic as well as our ever growing Python libraries for our Qwiic lineup. Now, to start programming we need to get some software up and running on the Nano!

    SOFTWARE GUIDE COMING SOON!

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


    Jetson Nano + Sphero RVR Mash-up (PART 1)

    $
    0
    0

    Jetson Nano + Sphero RVR Mash-up (PART 1) a learn.sparkfun.com tutorial

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

    Introduction

    We finally jumped on a project that we have been wanting to do for a while now: a mash-up of two robotics kits that we released over the past year! Those kits are the Advanced Autonomous kit for the Sphero RVR and our AI JetBot kit for the NVIDIA Jetson Nano. Both projects were fun to work on during launch and both products have astounding quality in their own perspective markets so we're very excited to combine them together!

    SparkFun Advanced Autonomous Kit for Sphero RVR

    SparkFun Advanced Autonomous Kit for Sphero RVR

    KIT-15303
    $164.95
    SparkFun JetBot AI Kit v2.0 Powered by Jetson Nano

    SparkFun JetBot AI Kit v2.0 Powered by Jetson Nano

    KIT-16390
    1
    Sphero RVR - Programmable Robot

    Sphero RVR - Programmable Robot

    ROB-15304
    $249.99

    We set about building this mash-up and this tutorial as a guide for you to follow along with us in building your own Jetson Nano powered Sphero RVR. We built the bot almost entirely from parts found in the two kits with and placed on top of a Sphero RVR.

    Fully assembled Jetson RVR Robot

    With all of this being said and documented if you choose to build your Nano RVR mash-up feel free to riff on what we did. There is no real right way to do this, it was us in the shop for an afternoon being creative. Your sensors, board placement and hardware choices may vary. Use this tutorial more as… “guidelines”.

    Hardware Overview

    As mentioned in the Introduction this project is a mash-up of two different kits, plus the Sphero RVR. We tried our best to source all of the parts individually for you, but many bits and pieces are used from the two original kits. Here is a wishlist of the major parts that would be required. In this case the only thing you would need to fabricate would be the camera mounting bracket if you dont have the one from the JetBot 2.1 kit.

    Most of the hardware from each kit can be found in our catalog, but with a few bits and pieces thrown in as well. If you are sourcing parts individually rather than through our kits I have included the important parts we do not carry as individual components below.

    Other Parts

    3M Dual Lock - From the Jetbot AI Kit, I use it to mount the camera and battery
    USB Battery Bank- For powering the Jetson Nano separate from the RVR, it comes with the Jetbot AI kit. If you source your own battery pack, make sure it can supply at least 3A@5V.

    Mounting the NVIDIA Jetson Nano

    Using the RVR as a platform for this robot enabled me to work with their topper plate system which makes building and fitting everything we needed onto the robot so much easier.

    Instead of working around the robot and trying to figure out how to mount something and the repetitive task of bolting something down only to remove it again later, all I had to do was remove the topper plate and as long as it fit on that plate I knew it would mount on the robot without a problem.

    Jetson Nano and Sphero RVR

    The RVR comes with a number of topper plates and one of them is specifically designed for mounting your own microcontrollers/single board computers to it. After trying a number of configurations of possible orientations of the Nano on the mounting plate I came to the conclusion that it wouldn't work for what I wanted to do. For this build I needed space to put the Nano and mount the camera while keeping wiring as clean as possible as well as space for the Servo pHAT or any other hardware connection to the GPIO headers in the rear of the robot.
    rvr topper

    With all of that in mind there was only one option: modify the stock topper plate of the RVR to mount the Jetson Nano.

    Modified topper

    Planning for Mounting Holes

    Before just going at it with a drill and making a few holes here and there, I wanted to be sure that I had all of the clearances needed underneath the build plate. I also needed to figure out what I would need to modify further so that I would have access to the UART/USB port of the RVR for hookup later.

    I placed the Jetson Nano on the topper where I wanted it, and using an awl, I carefully marked the locations of the four mounting holes. You can do this with a super fine tip sharpie as well. I used an awl so that the small mark would be used as a pilot for when I drilled the four mounting holes later.

    Marking the mounting holes on the RVR Topper

    Serial / USB Port Access

    One of the downsides of using the basic topper plate for this project is that it doesn’t have any access to the USB / UART ports on the RVR. So, I had to make my own! With the plate mounted to the RVR, I could see the port through the translucent plastic and needed to cut that section of the topper away to have access to the port.

    RVR Topper cut for USB Port

    I marked the corners as best as I could and then, using a sharpie, drew a box using the dots as my inside corners of the rectangle that I would cut out using my bandsaw. The final product isn't perfectly square, but it doesn’t need to be!

    I then cut away the area for the UART access and drilled the four mounting holes using my drill press.

    Modified Topper back on the RVR
    Yes, one hole was off by a bit and the drill bit wandered… I redrilled it and it is good enough given that the other three holes were aligned perfectly.

    Adding the Nano

    With the holes drilled in the topper plate it was now time to mount the Jetson Nano to it.

    Aluminum Standoffs from the RVR Topper Kit

    I used the aluminum standoffs from the Autonomous RVR Topper Kit as they give enough height to slide the battery bank under the Developer Kit.
    Standoffs mounted to the Jetson Nano Dev Kit

    My first inclination was to use a nut from the bottom of the topper plate and use screws from the top so that I could quickly and efficiently remove the Jetson Nano from the topper place without accessing the bottom, but the thickness of the topper plate become an issue for the stud length of the standoff. Instead, I used the screws to come up from the bottom and used nuts to hold the Developer Kit down.

    Jetson Nano secured to the RVR Topper

    With the Dev Kit mounted to the topper plate I checked the fit with the RVR. Everything seemed to fit just fine and I took a nail file to the edges that I cut in the plate to smooth them out a bit.

    Jetson Nano Peripherals

    The Jetson Nano requires a few things to get up and running before we dig too deep into building up the robot and forget about them!

    Micro SD Card and JetBot image

    Since this is a mash-up of two kits I had the JetBot image already burned to the SD card that came with that kit. This was a nice option because the image already has the JetBot software on it and running out of the box which prints out the IP address of the bot over the OLED display and also has the drivers for the included Edimax WiFi adapter already installed.

    If you are building this project from scratch I highly recommend starting with our JetBot image and burning it to an SD card. You can find our image and instructions for preparing the SD card, burning it and configuring it at the end of our JetBot Assembly Guide. You can find the Software Setup section of that guide here.

    Once you have an a microSD card with the JetBot image on it, insert it into the microSD card slot on the NVIDIA Jetson Nano. The card will give a satisfying click when inserted far enough. That’s it, you are all set!

    microSD card inserted into the Nano

    Edimax WiFi Adapter

    The JetBot requires a WiFi connection so that you can communicate with it while it is free to roam/drive around untethered.

    edimax photo

    The Edimax N150 WiFi adapter is what we use in our JetBot kit and our go-to WiFi accessory for working with the NVIDIA Jetson Nano.

    Installing the N150 is as simple as inserting it into an open USB port on the Jetson Nano. Software setup is a breeze if you are using our JetBot microSD card image. It should work out of the box.

    If you are building this project from scratch you will need to install the drivers for the WiFi adapter. You can find our tutorial for how to do that here:

    New!

    Adding WiFi to the NVIDIA Jetson

    April 23, 2020

    Step by step instructions for setting up and installing the Edimax N150 USB WiFi/BLE adapter on your NVIDIA Jetson Nano

    SparkFun Hardware

    With the Jetson Nano Dev kit mounted to the topper plate it was now time to start to build out the rest of my system's hardware. I used a combination of SparkFun hardware from both the JetBot as well as the Autonomous Kit for the RVR.

    Note: This guide covers adding the hardware needed to get JetBot functionality on top of the Sphero RVR. We know that if you have purchased both kits you also have access to other Qwiic boards such as a GPS and the Time of Flight distance sensor. Both of those boards are have a SparkFun Python library and you can integrate them into the project without a problem. In fact we may cover both of those options in the software guide for this project. But for now, we will stick to getting a functioning platform up and running!

    SparkFun Servo pHAT

    The crux of this project is the SparkFun Servo pHAT.

    SparkFun Servo pHAT

    This pHAT enables a number of things for this project. Probably the most important is that it gets us access to a 4 pin UART connection to enable clean and straightforward wiring for the UART communication wires between the Nano and the RVR.

    Servo pHAT RVR UART Header Highlighted

    It is also how we are going to provide power to the Jetson Nano through the USB-C connector as well as other peripheral hardware using the Qwiic connector on it as well.

    Servo pHAT USB C connector highlighted

    We use this connector for power rather than the USB or barrel jack power supply on the Jetson Nano Developer Kit so that we have access to raw power for both the Qwiic boards but more importantly any other hardware we want to hook up such as servo motors, etc.

    Micro OLED Breakout (Qwiic)

    Micro OLED Breakout

    If you own a JetBot kit, you know that the OLED display is a really handy part of the bot. The JetBot uses the OLED to print out important information about the JetBot's network connection, CPU and memory usage as well as its IP address. This is really handy when you need to access and program your robot through the Jupyter Notebooks application which you can access via a browser pointed at the JetBot's IP address. More on that in the programming tutorial!

    Mounting the display was a tricky problem for this project, but with some ingenuity and a few 90 degree mounting brackets I found a good place to put it that is out of the way, but still accessible and visible.

    OLED mounted to the Servo pHAT

    These 90 degree brackets are one thing that I used that was not included in one of the two kits I started with.

    Angle bracked 4-40

    With the display mounted to the Servo pHAT and connected to it via a Qwiic cable I placed the pHAT on the Jetson Nano Dev kit as shown.

    Assembled Jetson Nano and Servo pHAT on the Sphero Topper

    Camera and Camera Mount

    The camera mounting portion of this project was by far the most DIY modification and has been iterated on over time as JetBot itself has been changed up over the course of the year.

    Camera Mount

    When this project initially started, the camera mount that came with our original JetBot was made of clear acrylic and wouldn't work with how things were laid out on the RVR.

    JetBot v1 Acrylic Camera Mount

    For the machine learning aspect of JetBot to work properly the camera needed to be at a specific height, distance from the front axle of the drive wheels as well as tilt angle. So, with that information in hand I built my own camera mount from a bit of scrap MDF board and hot glue. This solution worked out well, but it does have a few downsides, one of them being that I used glue which doesn’t bode well when I need to remove or replace parts. But, for initial ideation it worked perfectly.

    Camera Mount Revision

    The advent of JetBot 2.0 and the change in chassis and how we mount the camera on it gave me an opportunity to revise my own camera mount. (Read as "a better mount to modify for our own use!")

    JetBot v2.0 Modified Camera Mount

    With the new camera mount in hand I used my disk sander to remove the tabs on the bottom of the acrylic mount so that it would sit relatively flat on the RVR.

    Camera Mount laying flat

    I positioned as accurately as it could be compared to the old DIY mount and a few reference marks were made before removing it. I also swapped out the plastic screw and nut that normally mount the camera to the bracket for a bit of 3M Dual Lock so that I could reposition the camera if needed. I drilled holes in the topper plate to run screws through and secure the new mount. Only use two of the holes as it would be more than enough for this light camera. I chose the two furthest back but feel free to use whichever holes work best for your robot.

    Camera mounted to RVR Topper

    Camera Hookup

    With the mounting bracket assembled and mounted to the topper plate I added the camera to the mounting bracket using some 3M Dual Lock rather than the plastic screws as shown in the JetBot assembly guide. The idea behind this would be to make it more adjustable if needed since it will be on the RVR chassis and not as optimally positioned as a chassis designed for it.

    Camera ribbon cable connected to Jetson Nano

    With the camera mounted, hook up is rather straightforward using the camera cable connector on the development kit carrier board. If you are using the original carrier board, you only have one choice in terms of camera connector.

    Note: If you have the updated B01 carrier with two camera connectors use the camera 0 connector. Be sure to be gentle when connecting the camera! The connectors on the carrier boards are rather fragile and can break easily!

    Final Wiring

    With the hardware assembly for the most part complete. It is now time to mount the plate with our hardware to the RVR and to do some final wiring, which is rather minimal!

    4 Pin UART Cable

    The Jetson Nano communicates with the Sphero RVR via UART and a raw UART connection on the RVR next to the USB port. This four pin connector uses a 4 wire female wiring harness to connect it to the “RVR” connector on the Servo pHAT.

    https://cdn.sparkfun.com//assets/parts/4/8/2/1/10369-01.jpg

    When connecting the pHAT to the RVR take note of the orientation of the connections. On the RVR, the UART Rx and Tx pins are oriented towards the “front” of the RVR with power (5V and GND) towards the back. You should insert the harness with the green wire pointed “forward”

    Close-up shot of the 4-pin cable

    The pHAT is the opposite of the RVR connector. The Rx and Tx connections are “forward” in this current configuration, so the harness should be connected to the pHAT with the red wire oriented “forward”.

    Showing the 4-pin cable connecting the Servo pHAT and the Sphero RVR

    USB Battery Bank

    The last thing to do before hardware assembly is completely finished is adding the USB battery bank and powering the Jetson Nano. The project uses the USB battery bank we use in our JetBot kit. It is perfect for powering the Jetson Nano and the peripherals while the RVR is powered through its own battery.

    USB Battery Bank

    Originally we wanted to mount the Jetson on four standoffs rather than three (You can probably see 4 holes in close-up shots of the topper plate), but once we went to fit the battery on the bot it would not fit between the standoffs. To fix this we removed one so the battery would fit in the proper orientation.

    The standoffs give just enough room for the battery to slide under the carrier board of the Jetson Nano. It should be snug enough that you don't need anything to keep it in place, but if you feel that you do, I highly recommend using 3M Dual Lock (we provide you with a length in our JetBot kit) or even a bit of two sided tape for just a bit of extra friction to keep it in place.

    With the battery in place add a USB-C cable from the battery pack to the USB-C port on the SparkFun Servo pHAT. If you are using the battery pack from the JetBot Kit, connect your USB cable to the orange (3A) USB port. The Jetson Nano should power up as soon as you do.

    Battery Bank connected to the Servo pHAT's USB C Connector

    In Closing and Next Steps

    With that, the basic structure of your NVIDIA Jetson Nano powered Sphero RVR is ready for software setup and programming.

    Fully assembled robot

    As we alluded to throughout this tutorial this is just the start for this robot! We wanted to give you something to start with, and be able to expand on that by adding more sensors, servo motors, etc. The expansion of this project would be a breeze using Qwiic as well as our ever growing Python libraries for our Qwiic lineup. Now, to start programming we need to get some software up and running on the Nano!

    SOFTWARE GUIDE COMING SOON!

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

    SparkFun GPS Dead Reckoning NEO-M8U Hookup Guide

    $
    0
    0

    SparkFun GPS Dead Reckoning NEO-M8U Hookup Guide a learn.sparkfun.com tutorial

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

    Introduction

    The u-blox NEO-M8U is a powerful GPS units that takes advantage of untethered dead reckoning (UDR) technology for navigation. The module provides continuous positioning for vehicles in urban environments and during complete signal loss (e.g. short tunnels and parking garages). We will quickly get you set up using the Qwiic ecosystem and Arduino so that you can start reading the output!

    SparkFun GPS Dead Reckoning Breakout - NEO-M8U (Qwiic)

    SparkFun GPS Dead Reckoning Breakout - NEO-M8U (Qwiic)

    GPS-16329
    $69.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.

    USB micro-B Cable - 6 Foot

    USB micro-B Cable - 6 Foot

    CAB-10215
    $4.95
    13
    Qwiic Cable - 100mm

    Qwiic Cable - 100mm

    PRT-14427
    $1.50
    SparkFun RedBoard Qwiic

    SparkFun RedBoard Qwiic

    DEV-15123
    $19.95
    5

    Additional GPS Antenna Options

    Below are some other GPS Antenna options. Some of the options below have an SMA connector, so make sure to get the u.FL to SMA cable if you decide to use those. Link for that is below in the GPS accessories. If you want to try different chip antennas, then try the GNSS Antenna Evalutation Board listed below and make sure to get the u.FL to u.FL connector in the accessories.

    GPS/GNSS Magnetic Mount Antenna - 3m (SMA)

    GPS/GNSS Magnetic Mount Antenna - 3m (SMA)

    GPS-14986
    $12.95
    1
    GPS/GNSS Embedded Antenna - 1m (SMA)

    GPS/GNSS Embedded Antenna - 1m (SMA)

    GPS-14987
    $59.95
    GPS Embedded Antenna SMA

    GPS Embedded Antenna SMA

    GPS-00177
    $11.95
    SparkFun GNSS Chip Antenna Evaluation Board

    SparkFun GNSS Chip Antenna Evaluation Board

    GPS-15247
    $24.95
    1

    GPS Antenna Accessories

    Interface Cable SMA to U.FL

    Interface Cable SMA to U.FL

    WRL-09145
    $4.95
    3
    GPS Antenna Ground Plate

    GPS Antenna Ground Plate

    GPS-15004
    $4.95
    U.FL to U.FL Mini Coax Cable - 200mm

    U.FL to U.FL Mini Coax Cable - 200mm

    WRL-15114
    $1.95

    Other Qwiic Cable Accessories

    SparkFun Qwiic Cable Kit

    SparkFun Qwiic Cable Kit

    KIT-15081
    $7.95
    4
    Qwiic Cable - 100mm

    Qwiic Cable - 100mm

    PRT-14427
    $1.50
    Qwiic Cable - 200mm

    Qwiic Cable - 200mm

    PRT-14428
    $1.50
    Qwiic Cable - 50mm

    Qwiic Cable - 50mm

    PRT-14426
    $0.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 would also recommend taking a look at the following tutorials if you aren't familiar with them.

    GPS Basics

    The Global Positioning System (GPS) is an engineering marvel that we all have access to for a relatively low cost and no subscription fee. With the correct hardware and minimal effort, you can determine your position and time almost anywhere on the globe.

    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.

    Getting Started with U-Center for u-blox

    Learn the tips and tricks to use the u-blox software tool to configure your GPS receiver.

    Three Quick Tips About Using U.FL

    Quick tips regarding how to connect, protect, and disconnect U.FL connectors.

    What is Dead Reckoning?

    Dead Reckoning is the process of determining current position by combining previously determined positional data with speed and heading. This process can also be applied to determine future positions as well! The NEO-M8U uses what is called Untethered Dead Reckoning (UDR) which calculates speed and heading (amongst many other points of data) through the use of an internal intertial measurement unit (IMU). The addition of an IMU allows the M8U to produce more accurate readings in between GNSS data refreshes! In addition, the module can also give accurate and useful GNSS data in areas where satellite connections are difficult to maintain: areas like the dense urban environments of major cities, long tunnels, parking garages, any large UFO's that may descend from the sky, etc.

    Hardware Overview

    Power

    Power for this board is 3.3V and we have provided multiple power options. This first and most obvious is the USB-C connector. Secondly, are the Qwiic Connectors on the top and bottom of the board. Thirdly, there is a 5V pin on the PTH header along the side of the board that is regulated down to 3.3V. Make sure that power your provide to this pin does not exceed 6 volts. Finally, just below the 5V pin is a 3.3V pin that should only be provided a clean 3.3V power signal.

     Power Pins

    Battery

    The small metal disk in the upper left corner is a small lithium battery. This battery does not provide power to the IC like the 3.3V system does, but to relevant systems inside the IC that allow for a quick reconnection to satellites. The time to first fix will about ~26 seconds, but after it has a lock, that battery will allow for about a 1.5 second time to first fix. This is known as a hot start and lasts for four hours after the board is powered down. The battery provides over a years worth of power to the backup system and charges slowly when the board is powered. To charge it to full, leave your module plugged in for 48 hours.

    Battery for Hot Start

    LEDs

    There's is a red power LED just to the left of the bottom Qwiic connector and near the board's edge to indicate that the board is powered. There is another LED just above the power LED labeled PPS that is connected to the Pulse Per Second line. When connected to a satellite, this line generates a pulse that is synchronized with a GPS or UTC time grid. By default, you'll see one pulse a second.

    Status LEDs

    Jumpers

    There are four jumpers on the underside of the product, each labeled with its function. At the upper right of the picture is a three way jumper labeled I²C that connects two pull-up resistors to the I2C data lines. If you have many devices on your I2C data lines, then you may consider cutting these. On the left side of the board is a jumper labeled PWR. If you cut this trace it will disconnect the Power LED. Just below is the PPS jumper that when cut disconnects the PPS LED. Finally, there's a jumper labeled SPI which enables the SPI data bus thus disabling the UART functions on those lines. For more information, check out our tutorial on working with jumper pads and PCB traces.

    Jumpers on the Back

    U.FL Connector

    The SparkFun GPS NEO-M8U has a u.FL connector in which you can connect a patch antenna.

    Qwiic and I2C

    There are two pins labeled SDA and SCL which indicates the I2C data lines. Similarly, you can use either of the Qwiic connectors to provide power and utilize I2C. The Qwiic ecosystem is made for fast prototyping by removing the need for soldering. All you need to do is plug a Qwiic cable into the Qwiic connector and voila!

    I2C Pins and Qwiic connector

    SPI

    There are four pins on the right most header that are labeled with their corresponding SPI functionality. As mentioned in the jumpers section, you'll need to close the SPI jumper on the underside to enable SPI.

    SPI Pins

    UART

    There are two pins on the right most header labeled for their UART functionality.

    UART Pins

    Broken Out Pins

    There are four other pins broken out: Pulse per second (PPS), Reset (RST), Safeboot (SAFE), and finally the interrupt pin (INT). The first pin PPS, outputs pulse trains synchronized with the GPS or UTC time grid. The signal defaults to once per second but is configurable over a wide range. Read the u-blox Receiver Protocol Specification in the Resources and Going Further tab for more information. The reset pin resets the chip. The next pin, SAFE is used to start up the IC in safe boot mode, this could be useful if you somehow manage to corrupt the module's Flash memory. The final pin INT can be used to wake the chip from power save mode.

    Pins Broken Out

    3D IMU Orientation and Reference

    For easy reference, we've documented the IMU's vectors with 3D Cartesian coordinate axes on the top and bottom side of the board. Make sure to orient and mount the board correctly so that the NEO-M8U can accurately calculate navigation information. This is explained in detail in the Dead Reckoning Overview. Remember, it's all relative.

    Top View with the the Axis for ReferenceBottom View with the the Axis for Reference

    Board Dimension

    Overall, the board is 1.30"x1.60".

    Board Dimensions

    GPS Capabilities

    The SparkFun NEO-M8U is able to connect to up to three different GNSS constellations at a time. Below are the listed capabilities of the GPS unit taken from the datasheet when connecting to different GNSS constellations.

    ConstellationsGPS+GLOGPSLGLOBDSGAL
    Horizontal Position AccuracyAutonomus2.5m2.5m4.0m3.0mTo Be Confirmed
    with SBAS1.5m1.5m
    Max Navigation Update RatePVT25Hz25Hz25Hz25Hz25Hz
    Time-To-First-FixCold Start24s25s26s28s29s
    Hot Start2s2s2s2s2s
    SensitivityTracking and Navigation-160dBm-160dBm-160dBm-160dBm-154dBm
    Reacquisition-160dBm-159dBm-156dBm-155dBm-152dBm
    Cold Start-148dBm-147dBm-145dBm-143dBm-133dBm
    Hot Start-157dBm-156dBm-155dBm-155dBm-151dBm
    Velocity Accuracy0.05m/s0.05m/s0.05m/s0.05m/s0.05m/s
    Heading Accuracy1deg1deg1deg1deg1deg


    Dead Reckoning Overview

    As mentioned in the "What is Dead Reckoning?" section, the u-blox M8U module has an internal inertial measurement unit or IMU for short. The IMU calculates position based on the last GNSS refresh and its own movement data points. To use the SparkFun GPS Dead Reckoning Board, there are a few guidelines to orienting and mounting the module to a vehicle outlined in the u-blox ReceiverDescrProtSpec Datasheet.

    Orientation for the SparkFun Dead Reckoning

    The SparkFun Dead Reckoning adheres to two particular frames of reference: one frame of reference for the car and the second a geodetic frame of reference anchoring it to the globe. The latter, known as the local level frame uses the following as its' axes:

    • X-axis points to the North
    • Y-axis points to the East
    • Z-axis uses the right hand system by pointing down.

    This frame will be referred to by its acronym NED (North-East-Down) in the image below.

    The second frame of references is the Body-Frame reference and uses the following as its' axes.

    • X-axis points to the front of the vehicle
    • Y-axis points to the right of the vehicle
    • Z-axis uses the right hand system by pointing down.

    You can reference the Body-Frame axes directly on the SparkFun Dead Reckoning NEO-M8U silk in the corner closest to the battery.

    Top View with the the Axis for ReferenceBottom View with the the Axis for Reference

    Vehicle Attitude

    The transformation of the vehicle within these two frames are given as heading, pitch, and roll. In the datasheet these three angles are called the vehicle's attitude. Below is an image that illustrates how all of these elements fit together.

    alt text

    Mounting the SparkFun Dead Reckoning NEO-M8U

    The only guideline here is that the SparkFun Dead Reckoning is stable within 2 degrees, and of course that the X-axis points towards the front of the car as mentioned above. In the image above the SparkFun Dead reckoning is seen in the front, driver's side of the car and it may be tempting to think that this is also a necessary requirement. However, it can be mounted anywhere within the vehicle (or RC-car, or boat). Keep in mind that the pitch and roll is relative to the SparkFun Dead Reckoning's position.

    Calibration

    After you've mounted the SparkFun Dead Reckoning M8U, there is still a calibration phase to complete that must satisfy the following movements:

    • Firstly the car needs to be stopped with the engine turned on.
    • Secondly the car must do left and right hand turns.
    • Lastly the car must reach a speed over 30 km/h.

    In SparkFun's u-blox Arduino library, SparkFun has included an Example (shown below), that prints out the module's calibration status.

    Hardware Assembly

    For this example, I used a RedBoard Qwiic and associated USB cable. Connecting the boards with Qwiic cable, the assembly is very simple. Plug a Qwiic cable between the RedBoard and SparkFun NEO-M9U. Then plugged in one of our patch antennas to the u.FL connector. If you need tips on plugging in the U.FL connector, then check out our U.FL tutorial. If you're going to be soldering to the through hole pins for I2C functionality, then just attach lines to power, ground, and the I2C data lines to a microcontroller of your choice. Your setup should look similar to the image below.

    alt text

    For secure connections, you may want to thread the U.FL cable through a mounting hole before connecting. Adding tape or some hot glue will provide some strain relief to prevent the cable from disconnecting.

    alt text

    When using the NEO-M8U, you will want to orient the board according to the guidelines explained earlier. Below is a top-down view with the board pointing down. Make sure to secure the board above a vehicle's dashboard using some tape or sticky tack when prototyping and testing.

    alt text

    SparkFun u-blox Library

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

    All of our u-blox based GPS boards share the same library: this board, their predeccesors and the higher precisionu-blox cousins. The SparkFun U-blox Arduino library can be downloaded with the Arduino library manager by searching 'SparkFun Ublox' or you can grab the zip here from the GitHub repository to manually install.:

    There are 13 example sketches provided to get you up and receiving messages from space. The examples listed below highlight the additional capabilities of the SparkFun Dead Reckoning NEO-M8U and so the basic GPS polling sketches as shown in the other u-blox hookup guides are skipped.

    Example 1 - Calibrate Sensor

    Now that the SparkFun Dead Reckoning is mounted and oriented correctly with regards to the vehicle, it's time to calibrate the sensor. To do this a few movements with the vehicle must be done all while maintaining good GNSS reception.

    • Firstly the car needs to be stopped with the engine turned on.
    • Secondly the car must do left and right hand turns.
    • Lastly the car must reach a speed over 30 km/h.

    For the first example, the calibration status will be printed to the Arduino's serial monitor to indicate when calibration is ongoing and when it has completed.

    In the first code block, there's a call to myGPS.setI2COUtput(COM_TYPE_UBX) towards the bottom which turns off NMEA noise.

    language:c
    void setup()
    {
      Serial.begin(115200);
      while (!Serial); //Wait for user to open terminal
      Serial.println("SparkFun Ublox Example");
    
      Wire.begin();
    
      if (myGPS.begin() == false) //Connect to the Ublox module using Wire port
      {
        Serial.println(F("Ublox GPS not detected at default I2C address. Please check wiring. Freezing."));
        while (1);
      }
    
      myGPS.setI2COutput(COM_TYPE_UBX); //Set the I2C port to output UBX only (turn off NMEA noise)
    }
    

    In the second code block below is where the heart of the sketch lives. The code pings the module to get its' "ESF Info" (External Sensor Fusion Info), to see what Fusion Mode has been achieved. A zero indicates calibration while a one indicates calibrated.

    language:c  
    void loop()
    {
    
      if (myGPS.getEsfInfo()){
        Serial.print("Fusion Mode: ");  
        Serial.println(myGPS.imuMeas.fusionMode);  
        if (myGPS.imuMeas.fusionMode == 1)
          Serial.println("Sensor is calibrated!");  
      }
    
      delay(250);
    }
    

    Example 2 - IMU Data

    After you have your sensor calibrated (see example 1), you can now poll the internal IMU to see what data is being fed to the GNSS calculations. First, the sketch checks to see that the board is calibrated before it attempts to read IMU data.

    language:c
    void setup()
    {
      Serial.begin(115200);
      while (!Serial); //Wait for user to open terminal
      Serial.println("SparkFun Ublox Example");
    
      Wire.begin();
    
      if (myGPS.begin() == false) //Connect to the Ublox module using Wire port
      {
        Serial.println(F("Ublox GPS not detected at default I2C address. Please check wiring. Freezing."));
        while (1);
      }
    
      myGPS.setI2COutput(COM_TYPE_UBX); //Set the I2C port to output UBX only (turn off NMEA noise)
    
      if (myGPS.getEsfInfo()){
    
        Serial.print("Fusion Mode: ");  
        Serial.println(myGPS.imuMeas.fusionMode);  
    
        if (myGPS.imuMeas.fusionMode == 1){
          Serial.println("Fusion Mode is Initialized!");  
            }
            else {
          Serial.println("Fusion Mode is either disabled or not initialized - Freezing!");  
                Serial.println("Please see Example 1 description at top for more information.");
            }
      }
    }
    

    Next the sketch grabs that IMU data which is stored in a struct called imuMeas.

    language:c
    void loop()
    {
    
      if (myGPS.getEsfIns())
      {
        Serial.print("X: ");
        Serial.println(myGPS.imuMeas.xAngRate);  
        Serial.print("Y: ");
        Serial.println(myGPS.imuMeas.yAngRate);  
        Serial.print("Z: ");
        Serial.println(myGPS.imuMeas.zAngRate);  
        Serial.print("X Acceleration: ");
        Serial.println(myGPS.imuMeas.xAccel);  
        Serial.print("Y Acceleration: ");
        Serial.println(myGPS.imuMeas.yAccel);  
        Serial.print("Z Acceleration: ");
        Serial.println(myGPS.imuMeas.zAccel);  
            // These values also have "validity checks" that can be provided by the
            // ublox library, add "Vald" to values: e.g. xAngRateVald or xAccelVald. 
      }
    
      delay(250);
    }
    

    Example 4 - Vehicle Dynamics

    What happened to Example 3? It's been skipped over because its used primarily as a diagnostic sketch. What sensors are currently being used, are they functioning correctly, are the measurements being listed as bad or non-existent? Example 3 helps diagnose these various issues.

    The vehicle attitude is a termed coined by u-blox that encompasses three measurements: vehicle pitch, vehicle roll, and vehicle heading. Much like the other example sketches, this one checks to make sure that the SparkFun Dead Reckoning NEO-M8U has been calibrated before pulling data.

    language:c
    if (myGPS.getEsfInfo()){
    
        Serial.print("Fusion Mode: ");  
        Serial.println(myGPS.imuMeas.fusionMode);  
    
        if (myGPS.imuMeas.fusionMode == 1){
          Serial.println("Fusion Mode is Initialized!");  
            }
            else {
          Serial.println("Fusion Mode is either disabled or not initialized - Freezing!");  
                Serial.println("Please see Example 1 description at top for more information.");
            }
      }
    }
    

    If the SparkFun Dead Reckoning NEO-M8U has indeed been calibrated, then it next gets the relevant information by calling myGPS.getVehAtt(). As in Example 2, the data is stored within a struct called vehAtt.

    language:c
    void loop()
    {
            myGPS.getVehAtt(); // Give the sensor you want to check on. 
            Serial.print("Roll: "); 
            Serial.println(myGPS.vehAtt.roll);
            Serial.print("Pitch: "); 
            Serial.println(myGPS.vehAtt.pitch);
            Serial.print("Heading: "); 
            Serial.println(myGPS.vehAtt.heading);
            Serial.print("Roll Accuracy: "); 
            Serial.println(myGPS.vehAtt.accRoll);
            Serial.print("Pitch Accuracy: "); 
            Serial.println(myGPS.vehAtt.accPitch);
            Serial.print("Heading Accuracy: "); 
            Serial.println(myGPS.vehAtt.accHeading);
    
            delay(250);
    }   
    

    Resources and Going Further

    Now that you've successfully got your GPS receiver up and running, it's time to incorporate it into your own project! For more information, check out the resources below:

    Are you looking for a GPS receivers? Check out the following GPS boards from the SparkFun catalog!

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

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

    GPS-15136
    $219.95
    19
    SparkFun GPS-RTK-SMA Breakout - ZED-F9P (Qwiic)

    SparkFun GPS-RTK-SMA Breakout - ZED-F9P (Qwiic)

    GPS-16481
    $219.95
    SparkFun GPS Breakout - ZOE-M8Q (Qwiic)

    SparkFun GPS Breakout - ZOE-M8Q (Qwiic)

    GPS-15193
    $44.95
    3
    SparkFun GPS Breakout - NEO-M9N, U.FL (Qwiic)

    SparkFun GPS Breakout - NEO-M9N, U.FL (Qwiic)

    GPS-15712
    $64.95
    2

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

    GPS Differential Vector Pointer

    Use GPS to have two objects, a base and a target, point towards one another. This can be used to aim a directional antenna (or in the case of this project, a laser) from one object to the other object at a distance that is only limited by your ability to provide the base station with the target's GPS location.

    SparkFun GPS Breakout - XA1110 (Qwiic) Hookup Guide

    Figure out where in the world you are with the Qwiic SparkFun GPS Breakout - XA1110.

    What is GPS RTK?

    Learn about the latest generation of GPS and GNSS receivers to get 2.5cm positional accuracy!

    GPS-RTK2 Hookup Guide

    Get precision down to the diameter of a dime with the new ZED-F9P from Ublox.

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

    Spectrum Shield Hookup Guide (v2)

    $
    0
    0

    Spectrum Shield Hookup Guide (v2) a learn.sparkfun.com tutorial

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

    Introduction

    Update: This tutorial is an updated version of the original hookup guide to make use of the Serial Plotter feature of the Arduino IDE, reduce the setup complexity in the examples, and update some of the format of the content. For users looking for the original tutorial, use the following link:

    Have you ever wanted to have your project react to music? Then this is the product for you! The Spectrum Shield provides your Arduino board with the capability of measuring a stereo audio input across 7 frequency bands. By reading the amplitude of each band with the ADC of your Arduino board, the users can control how attached devices respond to the audio input.

    SparkFun Spectrum Shield

    SparkFun Spectrum Shield

    DEV-13116
    $26.95
    13

    Materials Required

    To follow along with this tutorial, we recommend the following items.

    SparkFun RedBoard Qwiic

    SparkFun RedBoard Qwiic

    DEV-15123
    $19.95
    5
    Arduino Stackable Header Kit - R3

    Arduino Stackable Header Kit - R3

    PRT-11417
    $1.50
    12
    USB Micro-B Cable - 6"

    USB Micro-B Cable - 6"

    CAB-13244
    $1.95
    3
    Audio Cable TRRS - 1ft

    Audio Cable TRRS - 1ft

    CAB-14163
    $1.50

    Required Tools

    Some assembly is required for this product. You will need a soldering iron, solder, and/or general soldering accessories to solder on headers to your Spectrum Shield.

    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
    7

    Click the button above to toggle a list of accessories that are available from our catalog.

    Additional Accessories

    Below is a sample selection of our other headers and soldering tools in our catalog that you may be interested in. For a full selection of our available Headers or Soldering Tools, click on the associated link.

    Break Away Headers - Straight

    Break Away Headers - Straight

    PRT-00116
    $1.50
    20
    Arduino Stackable Header Kit - R3

    Arduino Stackable Header Kit - R3

    PRT-11417
    $1.50
    12
    Female Headers

    Female Headers

    PRT-00115
    $1.50
    7
    Raspberry Pi GPIO Tall Header - 2x20

    Raspberry Pi GPIO Tall Header - 2x20

    PRT-14017
    $1.95
    Insulated Silicone Soldering Mat

    Insulated Silicone Soldering Mat

    TOL-14672
    $9.95
    5
    Soldering Iron - 60W (Adjustable Temperature)

    Soldering Iron - 60W (Adjustable Temperature)

    TOL-14456
    $14.95
    8
    Weller WE1010 Soldering Station

    Weller WE1010 Soldering Station

    TOL-14734
    $129.00
    1
    Solder - 1/4lb Spool (0.020") Special Blend

    Solder - 1/4lb Spool (0.020") Special Blend

    TOL-10242
    $29.95
    8

    Suggested Reading

    We recommend you be familiar with these resources before continuing on with this hookup guide.

    How to Solder: Through-Hole Soldering

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

    Serial Communication

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

    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.

    Analog to Digital Conversion

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

    What is an Arduino?

    What is this 'Arduino' thing anyway? This tutorials dives into what an Arduino is and along with Arduino projects and widgets.

    Installing Arduino IDE

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

    Integrated Circuits

    An introduction to integrated circuits (ICs). Electronics' ubiquitous black chips. Includes a focus on the variety of IC packages.

    Analog vs. Digital

    This tutorial covers the concept of analog and digital signals, as they relate to electronics.

    Hardware Overview

    Audio Connections

    Audio Jacks

    The Spectrum Shield contains two stereo audio jacks on the board. The first audio jack, is the input jack (labeled Input). This allows users to input audio from any device -- such as an MP3 player, or cellular phone -- using a basic audio cable. This connection does not have to be used, as there is another option for adding audio input, at the "Audio In" headers, described below.

    Audio Jacks

    The second audio jack is the audio output, labeled Output. This jack allows you to pass the audio back out to a speaker or other audio system, while the sound levels are being processed by the Spectrum Analyzer ICs. (*Technically, both audio jacks and the audio header are all tied together and can be used as either an input or output.)

    Audio In Header

    For some projects, you may not be piping audio from a pre-processed source such as a cell phone. For users who want to use things like a MEMS Mic Breakout or the Sound Detector as an audio source, there are three header pins that provide an alternative connection method to your shield.

    Audio In Headers

    These pins are as follows:

    • L = Left Audio Input
    • G = Ground Audio Input
    • R = Right Audio Input

    With both the left and right inputs, you can use stereo devices on these headers. The signals also passes through to the Input and Output audio jacks.

    MSGEQ7 ICs

    The real power of this shield comes from the two MSGEQ7 ICs on the board. These are CMOS chips, which are seven band graphic equalizers.

    MSGEQ7 ICs

    Upon receiving an audio signal in, these ICs split the the spectrum into seven bands, splitting it at the following frequencies:

    • 63Hz
    • 160Hz
    • 400Hz
    • 1kHz
    • 2.5kHz
    • 6.25kHz
    • 16kHZ

    For the visual learners, here's the frequency graph from the MSGEQ7 datasheet:

    Frequency_Graph

    Once the spectrum has been split into these ranges, each band is peak detected and multiplexed. The DC output is a representation of the amplitude of each frequency band. Using the strobe and reset pins on the ICs allows the user to select the DC peak output.

    Shield Connections

    There are 4 main pins that the Arduino/RedBoard or other microcontroller connect to the Spectrum Shield.

    Analog Pins - There are two analog pins connected to the MSGEQ7 ICs. A0 is the DC analog output from the first IC for the left audio channel, while A1 is the DC analog output from the second, right audio channel.

    Analog Pin Connections

    Control Pins - The control pins connect to the Strobe and Reset pins on the MSGEQ7; D4 and D5, respectively. In order to enable the Strobe pin, you must pull the Reset pin LOW. To reset the entire multiplexer, pull the Reset pin HIGH.

    Strobe and Reset Pins

    The Strobe pin, once activated, cycles through each of the channels. After the initial pulse, it starts at 63Hz, pulses each channel until 16kHz, and then repeats, starting back at 63Hz. The DC output for each channel will follow the Strobe pulse.

    Remember: The reset line for the MSGEQ7 IC is not the same as the Reset push button that resets the entire system (RedBoard + Shield).

    Reset Button

    The reset button allows you to reset your Arduino/RedBoard while the shield is inserted. Holding the reset button will pull the reset pin of the ATMega328 (or other microcontroller) low, allowing a system reset. This will restart any sketches currently running on the microcontroller.

    Reset Button

    Hardware Assembly

    Solder Headers

    As with any shield, the first step is to choose a header type. We recommend the stackable headers if you need to stack on other shields; otherwise, the (straight) male headers are the simplest to work with. Feel free to choose any connection method you prefer, but remember that his shield uses the Arduino Uno R3 form factor or footprint when selecting your headers.


    How to Solder: Through-Hole Soldering

    September 19, 2013

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

    Arduino Shields v2

    April 20, 2020

    An update to our classic Arduino Shields Tutorial! All things Arduino shields. What they are and how to assemble them.

    You will need to solder the headers to the shield, so make sure you have all the appropriate supplies before you begin. If you aren't sure how to solder on the headers to the shield, please check out our How to Solder and Arduino Shield tutorials (also linked above).

    Once completed, connect the shield to your microcontroller; if you are using Arduino Uno or SparkFun RedBoard, stack the shield on top.

    Connect Audio System

    In the following example, we will be using your computer as the audio source. Plug one end of the audio cable into the audio jack on your computer and the other end into the Input jack on the Spectrum Shield. Feel free to use the Output jack on the Spectrum shield to pass the audio out to a speaker or set of headphones.

    Note: You may need to turn up the volume to meet the threshold for the IC to respond to the audio input. This volume may be above your tolerance for "comfortable listening". If this is the case, try using a speaker with an adjustable volume knob to lower the volume to a more reasonable level.

    Connecting to the Computer

    The last thing you will need to do is attach the microcontroller to the computer (with a USB cable). If you have done everything correctly, it should resemble the image below.

    Hardware Assembly
    RedBoard with Spectrum Shield attached to a computer.

    Arduino Example Code

    Note: This tutorial 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.

    Serial Plotter Example

    Now that you have your hardware all hooked up, it's time to analyze some audio signals. Below, we will walk through the SparkFun_Spectrum_Shield_Serial_Plotter_Demo.ino sketch. To begin, download that sketch from the GitHub Repository, and upload it to your Arduino. (*The .zip folder must be extracted and the file for the sketch is located in the Spectrum_Shield>Firmware>SparkFun_Spectrum_Serial_Plotter_Demo folder.)

    Code Overview

    The start of the demo code defines the pins functionality. The Spectrum Shield pin connections to the microcontroller must be defined.

    language:c
    //Declare Spectrum Shield pin connections
    #define STROBE 4
    #define RESET 5
    #define DC_One A0
    #define DC_Two A1
    
    //Define spectrum variables
    int freq_amp;
    int Frequencies_One[7];
    int Frequencies_Two[7];
    int i;
    

    Note that we declare two arrays Frequencies_One[] and Frequencies_Two[]; these will be used to store the output of the seven frequency bands from the MSGEQ7 ICs. (*The freq_amp and i variables are counters used for iterations in the code and carry minimal significance.)

    In the setup loop, the shield pins must also be declared as OUTPUTs for the STROBE and RESET pins so we can control the shield using the RedBoard. The DC analog pins are each declared as an INPUT in the code, because the RedBoard will be reading data in from these pins. Once the pins are declared, control pins (STROBE and RESET) are set to a LOW condition/output. A delay is added for the settings to take effect, then the serial output is initialized to a 9600 bps bard rate.

    language:c
    /********************Setup Loop*************************/
    void setup() {
      //Set spectrum Shield pin configurations
      pinMode(STROBE, OUTPUT);
      pinMode(RESET, OUTPUT);
      pinMode(DC_One, INPUT);
      pinMode(DC_Two, INPUT);
    
      //Initialize Spectrum Analyzers
      digitalWrite(STROBE, LOW);
      digitalWrite(RESET, LOW);
      delay(5);
    
      Serial.begin(9600);
    }
    

    For the main section of the sketch, we loop through two user-defined functions. Read_Frequenices() and Graph_Frequencies() tell the RedBoard to read the frequencies coming off the Spectrum Shield, and serial print out the analog values, respectively.

    language:c
    /****************Main Function Loop***************************/
    void loop() {
    
      Read_Frequencies();
      Graph_Frequencies();
      delay(50);
    
    }
    

    The Read_Frequencies() function is defined next in the code. When called, the function initializes/resets the ICs by cycling the RESET pin as described earlier in the Control Pins section. Then, the function steps through each frequency band on the Spectrum Shield using the STROBE pin, reads the DC analog outputs, and stores the values into the predefined frequency arrays.

    language:c
    /*************Pull frquencies from Spectrum Shield****************/
    void Read_Frequencies() {
      digitalWrite(RESET, HIGH);
      delayMicroseconds(200);
      digitalWrite(RESET, LOW);
      delayMicroseconds(200);
    
      //Read frequencies for each band
      for (freq_amp = 0; freq_amp < 7; freq_amp++)
      {
        digitalWrite(STROBE, HIGH);
        delayMicroseconds(50);
        digitalWrite(STROBE, LOW);
        delayMicroseconds(50);
    
        Frequencies_One[freq_amp] = analogRead(DC_One);
        Frequencies_Two[freq_amp] = analogRead(DC_Two);
      }
    }
    

    The data is retrieved through the Graph_Frequencies() function. With this function, the RedBoard returns the analog value for the frequencies being read by the Spectrum Shield through the serial port.

    language:c
    /*****************Print Out Band Values for Serial Plotter*****************/
    void Graph_Frequencies() {
      for (i = 0; i < 7; i++)
      {
    //    Serial.print(Frequencies_One[i]);
    //    Serial.print("");
    //    Serial.print(Frequencies_Two[i]);
    //    Serial.print("");
        Serial.print( (Frequencies_One[i] + Frequencies_Two[i]) / 2 );
        Serial.print("");
      }
      Serial.println();
    }
    

    Code Operation

    With the sketch uploaded to your board, you are now able to analyze the different frequency bands of your audio input. Pull, up the Serial Monitor and set the baud rate to 9600. Then, using your computer play an audio sample. You should see the numbers in the columns of the Serial Monitor change with the audio.

    Note: The "strength" and quality of the audio output from your computer is dependent on the sound card/chip use by your computer. Users may need to change their audio/speaker settings; as a baseline, I recommend turning up the audio on your computer to about 65% as a starting point.

    Below, are some audio samples that users can use to test the Spectrum Shield:

    Try playing the Youtube video and using the Serial Plotter of the Arduino IDE. You should see a response curve similar to the one below. Notice how the shapes resemble the figure from the datasheet in the Hardware Overview section.

    Serial Plotter

    Additional Examples

    There are plenty of projects out there using the Spectrum Shield, so do a bit of searching if you need some more inspiration! Additionally, you can refer to the original tutorial, which provides other examples including one from Bliptronics, the collaborator on the Spectrum Shield, which works with the Spectrum Shield and an LED matrix.

    Resources and Going Further

    For more information, check out the resources below:

    Also worth checking out is this edition of Engineering Roundtable, which details how to use the Spectrum Shield to control fire!


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

    SparkFun Humidity Sensor Breakout - SHTC3 (Qwiic) Hookup Guide

    $
    0
    0

    SparkFun Humidity Sensor Breakout - SHTC3 (Qwiic) Hookup Guide a learn.sparkfun.com tutorial

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

    Introduction

    Looking to keep a log of the climate in your greenhouse, create a humidor control system or want to track temperature and humidity data for a weather station project? The SparkFun Humidity Sensor Breakout - SHTC3 (Qwiic) may be the perfect option for you! The SHTC3 is a low cost, easy-to-use, highly accurate digital humidity and temperature sensor. The SHTC3 communicates via I2C so, as you can tell by the name, we have broken out the pins on the sensor to Qwiic connectors so you can easily connect it to SparkFun's ever growing Qwiic Ecosystem.

    SparkFun Humidity Sensor Breakout - SHTC3 (Qwiic)

    SparkFun Humidity Sensor Breakout - SHTC3 (Qwiic)

    SEN-16467
    $9.95

    In this guide we will highlight some of the unique features of this breakout, how to connect and use it as well as an Arduino library with four examples to get you started with your next environmental monitoring project.

    Required Materials

    To follow along with this guide you will need a microcontroller to communicate with the SHTC3. Below are a few options that come Qwiic-enabled out of the box:

    SparkFun Qwiic Pro Micro - USB-C (ATmega32U4)

    SparkFun Qwiic Pro Micro - USB-C (ATmega32U4)

    DEV-15795
    $19.95
    SparkFun Thing Plus - ESP32 WROOM

    SparkFun Thing Plus - ESP32 WROOM

    WRL-15663
    $20.95
    2
    SparkFun RedBoard Qwiic

    SparkFun RedBoard Qwiic

    DEV-15123
    $19.95
    5
    SparkFun RedBoard Artemis

    SparkFun RedBoard Artemis

    DEV-15444
    $19.95
    2

    If your chosen microcontroller is not already Qwiic-enabled, you can add that functionality with one or more of the following items:

    SparkFun Qwiic Cable Kit

    SparkFun Qwiic Cable Kit

    KIT-15081
    $7.95
    4
    SparkFun Qwiic Shield for Arduino

    SparkFun Qwiic Shield for Arduino

    DEV-14352
    $6.95
    SparkFun Qwiic Adapter

    SparkFun Qwiic Adapter

    DEV-14495
    $1.50
    1
    SparkFun Qwiic Shield for Arduino Nano

    SparkFun Qwiic Shield for Arduino Nano

    DEV-16130
    $3.50

    You will also need at least one Qwiic cable to connect your sensor to your microcontroller.

    Qwiic Cable - 100mm

    Qwiic Cable - 100mm

    PRT-14427
    $1.50
    Qwiic Cable - 200mm

    Qwiic Cable - 200mm

    PRT-14428
    $1.50
    Qwiic Cable - 50mm

    Qwiic Cable - 50mm

    PRT-14426
    $0.95
    Qwiic Cable - 500mm

    Qwiic Cable - 500mm

    PRT-14429
    $1.95

    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. If you are using one of the Qwiic Shields listed above, you may want to read through their respective Hookup Guides as well before you get started with the SparkFun Humidity Sensor Breakout - SHTC3 (Qwiic).

    I2C

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

    Serial Terminal Basics

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

    Qwiic Shield for Arduino & Photon Hookup Guide

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

    SparkFun Qwiic Shield for Arduino Nano Hookup Guide

    Hookup Guide for the SparkFun Qwiic Shield for Arduino Nano.

    Hardware Overview

    The SHTC3 Humidity and Temperature Sensor from Sensirion is an highly accurate digital humidity and temperature sensor that communicates using the I2C protocol. It is designed to work exceptionally well in battery powered applications such as wearables or remote environmental monitoring. In this section we will cover the operating characteristics of the SHTC3 along with the hardware present on the breakout board.

    Sensor Specifications

    The table below outlines some of the SHTC3's humidity and temperature sensor specifications. For a complete list and details about recommended operating conditions, review the SHTC3 Datasheet.

    ParameterValue
    Specified Humidity Range0 to 100 %RH
    Specified Temperature Range-40 to +125 °C
    Relative Humidity Accuracy Tolerance± 2.0%RH (Typ.)
    Temperature Accuracy Tolerance± 0.2°C (Typ.)

    Power

    Power for the SHTC3 is provided over the Qwiic interface or if you would prefer you can power it with 1.62-3.6V through the pins labeled 3.3V and GND. We recommend powering the board with a regulated 3.3V source, especially if you are using it with other Qwiic boards.

    Power Input

    Qwiic and I2C Interface

    The SHTC3 communicates via I2C and these pins are broken out to the two Qwiic connectors on the board as well as the SDA and SCL pins. The SHTC3's I2C interface supports clock frequencies between 0 to 1MHz with clock stretching to match the Fast Mode Plus specification. The I2C address is 0x70 (1110000 bin) and is hardware-defined. A multiplexer/Mux is required to communicate to multiple SHTC3 sensors on a single I2C bus. If you need to use more than one SHTC3 sensor on a single bus, consider using the Qwiic Mux Breakout - 8-Channel.

    Highlighting Qwiic and I2C Interface

    Jumpers

    If you have never worked with solder jumpers and PCB traces before or would like a quick refresher, check out our How to Work with Solder Jumpers and PCB Traces tutorial for detailed instructions and tips.

    The SparkFun Humidity Sensor - SHTC3 (Qwiic) has two solder jumpers on the board labeled I2C and PWR (or PWRLED if you are looking at the schematic). The I2C jumper pulls the SDA and SCL pins to VDD (normally 3.3V) through two 2.2K Ohm resistors. If you have many slave devices on the same bus you may want to disable these by opening the jumper (assuming they are also operating at 3.3V logic).

    The PWRLED jumper connects the power LED to VDD (normally 3.3V) through a 1K Ohm resistor. To disable the power LED simply open the jumper by severing the trace between the two solder pads. This is particularly useful for lower power applications where current draw needs to be kept at a minimum.

    Highlighting the Red Tactile ButtonHighlighting the Power LED Jumper
    I2C JumperPower LED Jumper

    Board Dimensions

    This breakout is designed to our Qwiic standard 1x1" sizing to easily stack with other Qwiic products. There are four mounting holes on the board that fit a 4-40 screw.

    Board Dimensions

    Now that we have a solid understanding of the hardware present on the breakout, we'll get it hooked up in the next section and move swiftly on to programming and talking to the sensor.

    Hardware Hookup

    Using the Qwiic system, assembling the hardware is simple. All you need to do is connect your SparkFun Humidity Sensor Breakout - SHTC3 (Qwiic) to your chosen development board with a Qwiic cable or adapter cable. Otherwise, you can use the I2C pins broken out if you prefer. If you are not using a Qwiic-enabled board, make sure your input voltage and logic are either running at 3.3V or you are running both controller and SHTC3 at the same logic level.

    SHTC3 connected to a RedBoard Qwiic

    If you prefer to use the PTH pins broken out on the Humidity Sensor you will need to either solder to them or, if you want a temporary connection for prototyping, these IC Hooks are a perfect option to make that connection. If you are not familiar with through-hole soldering, take a look at this tutorial:

    How to Solder: Through-Hole Soldering

    September 19, 2013

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

    With our SHTC3 connected to our microcontroller we can move on to writing some code to start monitoring temperature and humidity.

    SHTC3 Arduino Library

    Note: This library 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.

    The SparkFun SHTC3 Arduino library can be downloaded with the Arduino library manager by searching 'SparkFun SHTC3' or you can grab the zip here from the GitHub repository:

    Once the library is installed, we can move on to working with the included example sketches and take some sensor readings.

    Example 1: Basic Readings

    Open the first example by heading to File>Examples>SparkFun SHTC3 Humidity and Temperature Sensor Library>Example1_BasicReadings. Select your board (in our case, the Arduino/Genuino Uno) and the COM port that it enumerated on. Then hit upload. Open the Arduino Serial Monitor at 115200 baud to start viewing the humidity and temperature!

    Try holding your hand over the sensor or breathe lightly on to the SHTC3 and watch the values change.

    Example 2: Verify Checksums

    This example is very similar to the Basic Readings but also enables and returns checksum data calculated by the sensor to ensure the data is valid. Open it by following the instructions for Example 1 but instead select Example2_VerifyChecksums. The checksum pass indicators are passIDcrc, passRHcrc and passTcrc for the sensor ID, relative humidity and temperature, respectively.

    Using checksums is not absolutely necessary but can be helpful for troubleshooting any I2C communication errors. Once the code is uploaded, it will print out over serial all checksum data and whether or not it has passed or failed so you can identify if something such as the device ID is not returned properly.

    Example 3: Changing Options

    The third example builds on the previous two and demonstrates how to configure the SHTC3 using the setMode function as well as selecting your Wire port and clock speed. Again, open the example by navigating to the SHTC library and selecting Example2_ChangingOptions.

    Below are the available modes available on the SHTC3:

    language:c
    SHTC3_CMD_CSE_RHF_NPM = 0x5C24,   // Clock stretching, RH first, Normal power mode
    SHTC3_CMD_CSE_RHF_LPM = 0x44DE,   // Clock stretching, RH first, Low power mode
    SHTC3_CMD_CSE_TF_NPM = 0x7CA2,    // Clock stretching, T first, Normal power mode
    SHTC3_CMD_CSE_TF_LPM = 0x6458,    // Clock stretching, T first, Low power mode
    
    SHTC3_CMD_CSD_RHF_NPM = 0x58E0,   // Polling, RH first, Normal power mode
    SHTC3_CMD_CSD_RHF_LPM = 0x401A,   // Polling, RH first, Low power mode
    SHTC3_CMD_CSD_TF_NPM = 0x7866,    // Polling, T first, Normal power mode
    SHTC3_CMD_CSD_TF_LPM = 0x609C   // Polling, T first, Low power mode
    

    By default, the code sets the SHTC3 up to use clock stretching, report temperature data first and run on low power mode. To change to another mode, refer to the settings above and change this line:

    language:c
    mySHTC3.setMode(SHTC3_CMD_CSE_TF_LPM) == SHTC3_Status_Nominal
    

    Once you have selected which mode you want the SHTC3 to operate in, upload it and open a serial monitor to 115200 baud. You should see the checksum data print and then whether or not the setMode function was successful. Note that the code defaults to print out "Choosing low-power measurements with T first: " so if you use a different mode, you may want to alter that print statement to avoid confusion.

    If all of that is successful, the code will start printing out humidity and temperature data.

    Example 4: Using Callback

    The fourth example in the library demonstrates how to use the callback feature on the SHTC3. You may be wondering, what is a callback? It is a way that a library can provide a place for the user to do something. The library was written with a function that is called (nearly) every time a function is exited. How is that useful? You can overwrite the function with your own definition that allows you to do things like debug or watch the program execute.

    Make a function with this signature:

    language:c
    void SHTC3_exitOp_Callback(SHTC3_Status_TypeDef status, bool inProcess, char * file, uint16_t line)
    

    Then write in it some code that might help you. The example helps us watch the code execute by displaying the line number, file, and status every time that a function finishes.

    Including these functions is particularly helpful for debugging but can be taxing on your processor and slow down your code.

    Resources & Going Further

    That's all for this guide. Hopefully by now you have the know-how and circuit to start your own humidity and temperature monitoring. For further information about the SparkFun Humidity Sensor Breakout - SHTC3 (Qwiic), check out the links below. Thanks for reading!

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

    Si4707 Hookup Guide

    Instructions on hooking up to and communicating with the Si4707 Weather Band Radio Breakout using an Arduino.

    MS5803-14BA Pressure Sensor Hookup Guide

    Breakout of MS5803-14BA Pressure Sensor to measure the absolute pressure of the fluid around them to determine altitude, water depth, or any other tasks that require an accurate pressure reading. This includes air, water, and anything else that acts like a viscous fluid.

    Arduino Weather Shield Hookup Guide V12

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

    SparkFun gator:UV Hookup Guide

    The gator:UV is an I2C based UV sensor. This tutorial will get you started using the gator:UV with the micro:bit platform.

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

    Wireless Remote Weather Station with micro:bit

    $
    0
    0

    Wireless Remote Weather Station with micro:bit a learn.sparkfun.com tutorial

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

    Introduction

    In this tutorial, we will utilize MakeCode's radio blocks to have one micro:bit transmit a signal to a receiving micro:bit on the same channel! This is useful if your weather station is installed in a location that is difficult to retrieve data from the OpenLog. We will explore a few different ways to send and receive data.

    Wireless Remote Weather Station with micro:bit Demo

    Required Materials

    To follow along with this tutorial, you will need the following materials at a minimum. 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.

    Suggested Reading

    This project tutorial builds on the experiments from the micro:climate kit. Make sure you check out the guide before proceeding.

    micro:climate Kit Experiment Guide

    July 21, 2017

    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 following concepts, we recommend checking out these tutorials before continuing.

    How to Use a Breadboard

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

    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!

    micro:bit Breakout Board Hookup Guide

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

    SparkFun gator:RTC Hookup Guide

    The gator:RTC is an I2C based, real-time clock (RTC) for keeping time while your micro:bit isn't powered. This tutorial will get you started using the gator:RTC with the micro:bit platform.

    Installing the Extensions for Microsoft MakeCode

    To make the most out of the carrier boards with the least amount of coding, we will use the Microsoft MakeCode extensions written for the weather:bit. If you decide to add an RTC to the mix, you will need to include the gator:RTC extension as well. If you have not already, check out the instructions for installing the extensions for the board as explained in the associated guide whenever you make a new MakeCode project utilizing the boards.

    SparkFun Extensions

    Weather:bit Extension

    To install the extension for the weather:bit, head over to our micro:climate kit experiment guide to follow the instructions.

    Gator:RTC Extension

    To install the extension for the gator:RTC, head over to our gator:RTC guide to follow the instructions.

    Experiment 1: Sending and Receiving a Signal

    Introduction

    There are a few methods of transmitting data between two or more micro:bits. You can send a number or a string. If you are unfamiliar with strings, it is basically a sequence of characters that make up a word.

    If you followed along with the wireless remote micro:bot, you will remember that we simply sent one number to control the robot. For the scope of this tutorial, we will be transmitting the values from more than one sensor so we will want to know what number is associated with the reading. To do that, we will send a string and number pair between two micro:bits. We will animate the LEDs for each micro:bit as an indicator.

    GIF of first micro:bit transmitting to second micro:bit

    Parts Needed

    You will need the following parts:

    • 2x micro:bit Boards
    • 2x Micro-B USB Cables

    For a few items listed, you will need more than one unit (i.e. micro:bits, micro-B USB cables, etc.). 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.

    USB micro-B Cable - 6 Foot

    USB micro-B Cable - 6 Foot

    CAB-10215
    $4.95
    13
    micro:bit Board

    micro:bit Board

    DEV-14208
    $14.95
    7

    1.1: Sending

    For this part of the experiment, we are going to send a string and number from one micro:bit to another micro:bit on the same channel.

    Hardware Hookup

    Connect the first micro:bit to your computer via USB cable.

    micro-B USB Cable Inserted into Micro:bit

    Running Your Script

    We are going to use Microsoft MakeCode to program the micro:bit. You can download the following example script and move the *.hex file to your micro:bit. Or use it as an example to build it from scratch in MakeCode.


    Note: You may need to disable your ad/pop blocker to interact with the MakeCode programming environment and simulated circuit!

    Code to Note

    When the micro:bit is powered up, we'll want to set the radio to a certain channel. In this case, we head to the Radio blocks, grab the radio set group &lowbar;&lowbar; block, and set it to 1. Later (in the next experiment) we'll have the transmitting micro:bit that is attached to the weather station continuously transmit data to a receiving micro:bit. In this section, however, we'll continuously send a string and number pair out - the word string will be sent out with the number 1. For feedback, we will use the Basic blocks to have the LEDs animate with a dot expanding out into a square to represent a signal being sent out. Once the animation is finished, we will clear the screen. We will add a short delay with pause _____ from the basic blocks to give the second micro:bit some time to handle the data before sending out data again. We will set it to 1000ms.

    Screenshot of Basic Transmitting Code

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

    1.2: Receiving

    For this part of the experiment, we are going to have a second micro:bit receive a string and number from the first micro:bit.

    Hardware Hookup

    To avoid confusion when uploading code, unplug the first micro:bit from your computer. Then connect the second micro:bit to your computer via USB cable.

    Insert Second micro:bit

    Running Your Script

    Download the following example script and move the *.hex file to your micro:bit. Or use it as an example to build it from scratch in MakeCode. You will need to open a new project to receive the data from the first part of this experiment.


    Note: You may need to disable your ad/pop blocker to interact with the MakeCode programming environment and simulated circuit!

    Code to Note

    When the second micro:bit is powered up, we'll want to set the radio to the same channel as the first micro:bit. In this case, it will be 1. Using the on radio received name value block, we will want to check to see what signal was sent from the first micro:bit. In this case, we will want to check to see if the string that was received and stored in name is what we expect. Using the if statement from the Logic blocks, we will want to check to see if name matches word string by using the "_" = "_" block. If it matches, we will want to see if the value matches 1 by using the ___=___. Note the differences in the two comparisons. One compares a string while the other compares a number.

    If both match, we will want some sort of indicator. Visually, using LEDs would be the easiest so an animation of a square shrinking to a dot was chosen to represent the received signal. Once the animation is finished, we will want to clear the screen until we receive another signal.

    Screenshot of Basic Receiving Code

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

    What You Should See

    Powering both micro:bits up, the first micro:bit (our transmitting) will send a string and number pair out on channel 1. In this case, the pair was string and 1, respectively.

    The second micro:bit (our receiving) will take that string and number pair that was sent on channel 1 and do something based on the condition statement. In this case, there is an animation using the LED array to indicate when we have received the pair.

    GIF of first micro:bit transmitting to second micro:bit

    Experiment 2: Wireless Remote Weather Data

    Introduction

    Remember our weather station from the micro:climate kit? If you have been following along from the last experiment, we were logging sensor data to an OpenLog and saving it to a microSD card to graph. Now what if you installed the weather station in a remote location where it was difficult to obtain the sensor readings? In this part of the experiment, we will have one micro:bit transmit sensor readings from the weather:bit and weather meter. Then in the second part of this experiment, we will take the readings and output them to a serial terminal.

    Serial Output Received from a Remote micro:bit Using the MakeCode Console

    Parts Needed

    You will need the following parts:

    • 2x micro:bit Boards
    • 2x Micro-B USB Cables
    • 1x Weather:bit Carrier Board
    • 1x Weather Meter
    • 3x 12" M/M Jumper Wires
    • 1x SparkFun Soil Moisture Sensor
    • 1x Waterproof Temperature Sensor

    For a few items listed, you will need more than one unit (i.e. micro:bits, micro-B USB cables, etc.). 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.

    Temperature Sensor - Waterproof (DS18B20)

    Temperature Sensor - Waterproof (DS18B20)

    SEN-11050
    $11.95
    25
    Weather Meter Kit

    Weather Meter Kit

    SEN-15901
    $64.95
    USB micro-B Cable - 6 Foot

    USB micro-B Cable - 6 Foot

    CAB-10215
    $4.95
    13
    SparkFun Soil Moisture Sensor (with Screw Terminals)

    SparkFun Soil Moisture Sensor (with Screw Terminals)

    SEN-13637
    $6.95
    2
    micro:bit Board

    micro:bit Board

    DEV-14208
    $14.95
    7
    SparkFun weather:bit - micro:bit Carrier Board (Qwiic)

    SparkFun weather:bit - micro:bit Carrier Board (Qwiic)

    DEV-15837
    $15.95
    Jumper Wires Premium 12" M/M  Pack of 10

    Jumper Wires Premium 12" M/M Pack of 10

    PRT-09387
    $4.50

    2:1 Sending

    For this part of the experiment, we are going to send a string and number pair for each sensor attached to the first micro:bit. A second micro:bit on the same channel will receive the data and output it to a serial terminal.

    Hardware Hookup

    We will also assume that your weather meter has been assembled. Make sure to check out following guides before continuing on.

    micro:climate Kit Experiment Guide

    July 21, 2017

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

    Weather Meter Hookup Guide

    July 20, 2017

    How to assemble your very own weather meter!

    If you have not already, insert one micro:bit into the weather:bit's carrier board. Make sure to insert the micro:bit with the LED array facing up (the same direction the connectors) as explained in the micro:climate kit experiment guide. We’re continuing on from experiment 7. Below is a view from the back as a USB cable is being inserted.

    Inserting a USB Cable into the Micro:bit on the Weather Station's Side

    Your setup should look similar to the image below.

    Weather Station Setup on a Table

    Running Your Script

    We are going to use Microsoft MakeCode to program the micro:bit. You can download the following example script and move the *.hex file to your micro:bit. Or use it as an example to build it from scratch in MakeCode.


    Note: You may need to disable your ad/pop blocker to interact with the MakeCode programming environment and simulated circuit!

    Code to Note

    In the on start block, we will set up the channel to 1 just like the previous example. Additionally, we will set up the weather, wind, and rain blocks just like each of the experiments in the micro:climate kit experiment guide.

    Screenshot of Weather Station code

    Click on image for a closer view.

    In the forever loop, we will send a string and number for each reading with the values calculated every second. For each piece of data, we will update the LED array to indicate the status. The following blocks of code were taken from the basic, radio, weather, and logic blocks.

    • running time [ms] as time
    • BME280's temperature [degrees C] as tmpC
    • BME280's humidity in [rH] as humidity
    • BME280's pressure in [hPa] as pressure
    • altitude in [meters] as altitude
    • acculmulated rain [in] as rain
    • wind speed [mph] as wind spe
    • wind direction as wind dir
    • soil moisture as soilMstr
    • soil temperature [degrees C] as soilTmpC

    If you look at each string, you will notice a few of the names were shortened. This is due the radio block only being able to send 8x characters for each string and number pair. Additionally, since the wind direction is a character and not a number, we will need to assign a number to refer to each wind direction. If the wind vane is pointing to an unknown direction, we will output ???. If you remember from the troublehsooting tip in experiment 5, this may be due to a loose connection or when the micro:bit read the wind vane at a certain moment when the magnet was within a small region somewhere between the 8x directions.

    When finished, we will clear the screen and wait a few seconds using the pause_____ block to give the second micro:bit some time to finish what it was doing before we start sending more data. This value can be adjusted to send out data at longer intervals.


    2:2 Receiving

    For this part of the experiment, we are going to have a second micro:bit receive a string and number pair for each sensor that was sent from the first micro:bit. We will then view the sensor data using a serial terminal. In this case, we will use the MakeCode console. You can use a different serial terminal program depending on your personal preference.

    Hardware Hookup

    To avoid confusion when uploading code, unplug the first micro:bit from your computer. Then connect the second micro:bit to your computer via USB cable.

    Insert Second micro:bit

    Running Your Script

    Download the following example script and move the *.hex file to your micro:bit. Or use it as an example to build it from scratch in MakeCode. You will need to open a new project to receive the data from the first part of this experiment.


    Note: You may need to disable your ad/pop blocker to interact with the MakeCode programming environment and simulated circuit!

    Code to Note

    When the code first starts, we initialize a serial output on the micro:bit to send serial to the USB with the help of the serial blocks. Using the serial redirect to USB code block defaults the 115200 baud. This is useful whenever we need to inspect the sensor readings and interpret the values in a serial terminal.

    Screenshot of Receiving Code

    For every string and number pair that we receive, we will output it to the serial terminal. If we receive a number for the wind direction, we will translate it back to its respective direction. For feedback, we will use the LED array as a status indicator on the receiving end. Every time we receive data, we will blink the center LED in the array before clearing it.


    What You Should See

    Serial Output

    For the scope of this tutorial, we'll use the MakeCode console to display the serial output. If you have paired the micro:bit to your computer and used the one-click download feature for MakeCode, a "Show console Device" button should appear in MakeCode. Click on the button to begin viewing the serial output. A graph and serial monitor will appear over the MakeCode code editor. Otherwise, open a serial terminal with 115200 baud and connect to the COM port listed for the micro:bit.

    At this point, apply power to the first micro:bit that is attached to the weather station. It will begin transmitting sensor data to the second micro:bit and display in the MakeCode console. You may notice that some data may not be graphed if it is not changing. This is due to the graph automatically resizing. Try testing the sensors to see if the values change as expected!

    Serial Output Received from a Remote micro:bit Using the MakeCode Console

    Experiment 3: Checking Sensor Data with Arrays

    Introduction

    We have successfully sent data from the first micro:bit and received it using a second micro:bit! However, we are not done yet! If you look at the data sent, sometimes the second micro:bit can miss some data points depending on when either micro:bit is powered up. If you are just viewing the data on the serial terminal or saving the values into a variable, it's not too much of a concern. However, this will cause problems if you decide you want to save and graph the data using the OpenLog. The data may be shifted depending on when you powered the micro:bit. The missing data points will have holes in your data set and cause errors whenever the micro:bit saves data intended for a different sensor. Below is an example output with missing data.

    Hole in Transmitted Data When a micro:bit is Powered at a Different Time

    In this section, we will save the weather stations running time and temperature into an array. To check, we will have a second array to keep track of what is received to ensure that we have received everything that was transmitted. If we have received it, we will display the values in comma delimited form through a serial terminal. If not, we will not output the values. For debugging purposes and to help us understand what is going on, we will also display the status of the second array that is keeping track of what is being received.

    Output from Arrays

    Parts Needed

    You will need the following parts:

    • 2x micro:bit Boards
    • 2x Micro-B USB Cables
    • 1x Weather:bit Carrier Board

    For a few items listed, you will need more than one unit (i.e. micro:bits, micro-B USB cables, etc.). 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.

    USB micro-B Cable - 6 Foot

    USB micro-B Cable - 6 Foot

    CAB-10215
    $4.95
    13
    micro:bit Board

    micro:bit Board

    DEV-14208
    $14.95
    7
    SparkFun weather:bit - micro:bit Carrier Board (Qwiic)

    SparkFun weather:bit - micro:bit Carrier Board (Qwiic)

    DEV-15837
    $15.95

    3.1 Sending Some Data

    Let's take a step back and only send the running time and temperature for simplicity.

    Hardware Hookup

    We recommend having just the weather station's micro:bit connected for this section to avoid confusion when uploading code.

    Inserting a USB Cable into the Micro:bit on the Weather Station's Side

    The setup is the same as the previous experiment. However, we are just using the BME280's temperature sensor. We can leave everything connected as it currently is from the previous example.

    Weather Station Setup on a Table

    Running Your Script

    We are going to use Microsoft MakeCode to program the micro:bit. You can download the following example script and move the *.hex file to your micro:bit. Or use it as an example to build it from scratch in MakeCode.


    Note: You may need to disable your ad/pop blocker to interact with the MakeCode programming environment and simulated circuit!

    Code to Note

    This code is just a shortened version of experiment 2.1's code for simplicity.

    Screenshot shortened code transmitting from the weather station

    3.2 Receiving and Checking Some Data

    In this section, we will be receiving two readings and storing them into arrays. We will check the data to see if we received all the readings for that instance. If we do not receive everything in that row, we will not output the readings to the serial terminal. Instead we will output a message indicating that we did not receive everything.

    Hardware Hookup

    To avoid confusion when uploading code, unplug the first micro:bit from your computer. Then connect the second micro:bit to your computer via USB cable.

    Insert Second micro:bit

    Running Your Script

    We are going to use Microsoft MakeCode to program the micro:bit. You can download the following example script and move the *.hex file to your micro:bit. Or use it as an example to build it from scratch in MakeCode.


    Note: You may need to disable your ad/pop blocker to interact with the MakeCode programming environment and simulated circuit!

    Code to Note

    There is a lot going on. Let's inspect the code in parts.

    Screenshot of code to check readings received from the weather station

    Click image for a closer view.

    As the receiving micro:bit is powered up, we set up the serial and radio. We then create two arrays. Similar to creating regular variables, we first need to create two array variables called Sensor_Data and Rx_Data_Check from the variables block. We set each to an array of ____ ____ from the array blocks so that they are able to to save more than one number. The values in Sensor_Data are used to initialize the array for two data points from the weather station and will be used as a place holder for the array. The values in Rx_Data_Check are used to initialize the array as well but this will be used to keep track of each data point that is received for each interval. We know that the weather station will be sending two data points associated with the time and tmpC strings. We will change those values to a 1 to indicate that we have received one data point. We will assume that those two are received before the transmitting micro:bit loops back and sends the next running time and temperature. Otherwise, it will remain 0 if we did not receive anything. We also create one more variable called Total_Rx_Data and set it to 0. We only need one, which will be used to add up all the 1's from the received data points in Rx_Data_Check.

    Closeup of Code

    We will use the on radio received name value to listen for the string and number pair. We will use the if statement to check if we have received one of the strings sent from the first micro:bit. The first string we will check is time. If we received that as the string, we will use the array's ____ insert at ____ value ____ . The first space is for the array called Sensor_Data. The number where the second space is in the code block indicates the location that the data will be placed at. Since we expect this to be the running time, it will be at position 0 in the array. In terms of programming, this is refered to as index 0. Once inserted, everything will be shifted to the next higher position. The final space in the code block indicates the number that we will be inserted at that position; in this case the number received will be equal to the radio's variable called value. This code block is an advanced operation but it is quite useful when collecting and organizing data.

    Closeup of Code

    Now that we have inserted one data point into the Sensor_Data array, we will want to delete the old data point. In this case, it is the old running time. This was shifted to the next higher position, which is at position 1 in the Sensor_Data. This is important because we do not want to flood the memory and break the micro:bit. You'll probably notice a sad face with an error code when this happens. Don't worry, you can still upload new code to the micro:bit.

    Just make sure to fix your code to prevent the micro:bit from being sad and not able to run any code. We will first create a variable to "throw away" the old value called Deleted_Item. We set the variable to the Sensor_Data at position 1. This is different than how we usually save numbers with variables because we will specify the position that we are removing. Since we know the old position is the next higher position, we will set that to 1. Once this block is executed, the old value is saved in Deleted_Item and we remove whatever was at Sensor_Data's position 1.

    Whew, that was a lot but we are not done! Next we will send the string and number to the serial terminal to monitor what is going on. Since we received a data point for the running time, we will update the Rx_Data_Check array like we did for the Sensor_Data at position 0 by marking it as 1. We will repeat the step to remove the old information from the Rx_Data_Check.

    Below is a graphical representation of arrays in MakeCode of what is happening. The left is the code that is running. On the right is a graphic of what is happening to the array in the background. You will not actually see this in the MakeCode editor.

    Graphical Representation of Arrays in MakeCode

    We will then exit the if statement block and head to the bottom where we blink the middle LED in the array.

    Closeup of Code

    The receiving micro:bit will listen for the next data point. When we receive it, the code will start executing from the top of the on radio receive name value. Since we know that the next data point to be received is tmpC, the else if statement block will jump to the next check. It will repeat all the steps as outlined earlier but for the temperature at position 1.

    Since we know this is the last value to be received in this experiment, we will start checking to see if we received two data points inside the for loop block by adding all the 1's in Rx_Data_Check array. Each time we loop through, we will output where we are at in the Rx_Data_Check array and the current total for received data (called Total_Rx_Data). Note that programmers start counting a 0 instead of 1. The length of Rx_Data_Check array is 2. So the for loop will execute 3 times if we do subtract the length of the Rx_Data_Check array by 1.

    Closeup of Code

    If it equals a total of 2 data points, we will output a message in the serial terminal. We will also display a check mark in the LED array, and output the readings at that instance in a comma delimited form. If it does not equal what we expect, we will output a message indicating that we did not receive everything, display a bracket [] to represent there was something missing in the array, and not output any readings for that instance. We will reset the Rx_Data_Check array and blink the LED before exiting.

    Closeup of Code

    Click on image for a closer view.

    What You Should See

    We'll use the MakeCode console once again to display the serial output from the receiving micro:bit. If you have paired the micro:bit to your computer and used the one-click download feature for MakeCode, a "Show console Device" button should appear in MakeCode. Click on the button to begin viewing the serial output.

    Apply power to the first micro:bit that is attached to the weather station. It will begin transmitting sensor data to the second micro:bit and display in the MakeCode console. You should see the output messages with the checks and readings for each instance. Whew, that was a lot of work to check for two data points. Let's move onto the next experiment and repeat this for the other sensor values that were sent in experiment 2

    Serial Output in MakeCode Console from the Receiving micro:bit

    Click on image for a closer view.

    Experiment 4: Wireless Remote Weather Data (Revisited)

    Introduction

    Now that we have a way to verify that the data is received, we will repeat this check for each string/number pair.

    Serial Output in MakeCode Console for all received readings

    Parts Needed

    You will need the following parts:

    • 2x micro:bit Boards
    • 2x Micro-B USB Cables
    • 1x Weather:bit Carrier Board
    • 1x Weather Meter
    • 3x 12" M/M Jumper Wires
    • 1x SparkFun Soil Moisture Sensor
    • 1x Waterproof Temperature Sensor

    For a few items listed, you will need more than one unit (i.e. micro:bits, micro-B USB cables, etc.). 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.

    Temperature Sensor - Waterproof (DS18B20)

    Temperature Sensor - Waterproof (DS18B20)

    SEN-11050
    $11.95
    25
    Weather Meter Kit

    Weather Meter Kit

    SEN-15901
    $64.95
    USB micro-B Cable - 6 Foot

    USB micro-B Cable - 6 Foot

    CAB-10215
    $4.95
    13
    SparkFun Soil Moisture Sensor (with Screw Terminals)

    SparkFun Soil Moisture Sensor (with Screw Terminals)

    SEN-13637
    $6.95
    2
    micro:bit Board

    micro:bit Board

    DEV-14208
    $14.95
    7
    SparkFun weather:bit - micro:bit Carrier Board (Qwiic)

    SparkFun weather:bit - micro:bit Carrier Board (Qwiic)

    DEV-15837
    $15.95
    Jumper Wires Premium 12" M/M  Pack of 10

    Jumper Wires Premium 12" M/M Pack of 10

    PRT-09387
    $4.50

    4.1 Sending... Again

    In this section, we will be sending the same data that was transmitted in 2.1

    Hardware Hookup

    We recommend having just the weather station's micro:bit connected for this section to avoid confusion when uploading code.

    Inserting a USB Cable into the Micro:bit on the Weather Station's Side

    Nothing special here. The setup is the same as experiment 2. We can leave everything connected as it currently is from the previous examples.

    Weather Station Setup on a Table

    Running Your Script

    We are going to use Microsoft MakeCode to program the micro:bit. You can download the following example script and move the *.hex file to your micro:bit. Or use it as an example to build it from scratch in MakeCode.

    Code to Note

    This is the same code that was used in 2.1! Nothing has changed on the weather station side.

    Screenshot of Code that was used in 2.1

    Click image for a closer view

    4.2 Receiving and Checking All the Data

    In this section, we will be receiving the data and checking to see if we received everything in that instance. If we did, we will output the row in comma delimited form.

    Hardware Hookup

    To avoid confusion when uploading code, unplug the first micro:bit from your computer. Then connect the second micro:bit to your computer via USB cable.

    Insert Second micro:bit

    Running Your Script

    We are going to use Microsoft MakeCode to program the micro:bit. You can download the following example script and move the *.hex file to your micro:bit. Or use it as an example to build it from scratch in MakeCode.


    Note: You may need to disable your ad/pop blocker to interact with the MakeCode programming environment and simulated circuit!

    Code to Note

    The code is long but we are basically repeating what we did in experiment 3 for each reading. Let's take a look at a few of the changes.

    Screenshot of Code checking readings and outputting it to serial

    Click image for a closer view

    When the second micro:bit is powered up, we have the same setup as experiment 3.2. However, we will be storing and verifying 10 readings. We'll set up 10 positions for the Sensor_Data. We'll also set 10 positions to 0 for the Rx_Data_Check.

    Closeup of Code

    Click image for a closer view

    We then set condition statements to check all 10 readings. Every time we receive data, we will blink the center of the LED array. The for loop to print the received data is the same. If we received all 10 readings, we will output the data to the serial terminal. If we do not receive all 10 readings, we will not output any data like the previous experiment.

    Closeup of Code

    Click image for a closer view

    What You Should See

    Again, we'll use the MakeCode console to display the serial output from the receiving micro:bit. If you have paired the micro:bit to your computer and used the one-click download feature for MakeCode, a "Show console Device" button should appear in MakeCode. Click on the button to begin viewing the serial output.

    Apply power to the first micro:bit that is attached to the weather station. It will begin transmitting sensor data to the second micro:bit and display in the MakeCode console. You should see the output messages with the checks and an instance of the readings.

    Serial Output in MakeCode Console for all received readings

    If you powered the receiving micro:bit in the middle of the transmission, it will not output the comma delimited data. Instead it will wait for the next transmission so that we have a complete row.

    Serial Output in MakeCode Console when we do not receiving everything at that instance

    Experiment 5: Real Time Wireless Data Logging

    Introduction

    At the time of release, we did not have a real time clock (RTC) available for the micro:climate kit. We used the running time to record when a reading was obtained. In this experiment, we will be adding the gator:RTC to help record the day and time for each reading before saving it with the OpenLog.

    Wireless Remote Weather Station with micro:bit Demo

    Parts Needed

    You will need the following parts:

    • 2x micro:bit Boards
    • 2x Micro-B USB Cables
    • 1x Weather:bit
    • 1x Weather Meter
    • 7x 12" M/M Jumper Wires
    • 1x SparkFun Soil Moisture Sensor
    • 1x Waterproof Temperature Sensor
    • 1x OpenLog with Headers
    • 1x microSD Card
    • 1x microSD Card Reader
    • 1x gator:RTC
    • 4x Alligator to Pigtails
    • 1x micro:bit Breakout with Headers
    • 1x Breadboard

    For a few items listed, you will need more than one unit (i.e. micro:bits, micro-B USB cables, etc.). 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.

    Temperature Sensor - Waterproof (DS18B20)

    Temperature Sensor - Waterproof (DS18B20)

    SEN-11050
    $11.95
    25
    Weather Meter Kit

    Weather Meter Kit

    SEN-15901
    $64.95
    SparkFun micro:climate kit for micro:bit - v3.0

    SparkFun micro:climate kit for micro:bit - v3.0

    KIT-16274
    $99.95
    Breadboard - Self-Adhesive (White)

    Breadboard - Self-Adhesive (White)

    PRT-12002
    $4.95
    41
    USB micro-B Cable - 6 Foot

    USB micro-B Cable - 6 Foot

    CAB-10215
    $4.95
    13
    SparkFun Soil Moisture Sensor (with Screw Terminals)

    SparkFun Soil Moisture Sensor (with Screw Terminals)

    SEN-13637
    $6.95
    2
    micro:bit Board

    micro:bit Board

    DEV-14208
    $14.95
    7
    SparkFun micro:bit Breakout (with Headers)

    SparkFun micro:bit Breakout (with Headers)

    BOB-13989
    $5.95
    3
    Alligator Clip with Pigtail (10 Pack)

    Alligator Clip with Pigtail (10 Pack)

    CAB-14303
    $6.95
    4
    SparkFun weather:bit - micro:bit Carrier Board (Qwiic)

    SparkFun weather:bit - micro:bit Carrier Board (Qwiic)

    DEV-15837
    $15.95
    Jumper Wires Premium 12" M/M  Pack of 10

    Jumper Wires Premium 12" M/M Pack of 10

    PRT-09387
    $4.50
    SparkFun gator:RTC - micro:bit Accessory Board

    SparkFun gator:RTC - micro:bit Accessory Board

    COM-15486
    $14.95

    5.1 Requesting Weather Station Data

    We could add the RTC to the weather station and just have the first micro:bit (let's call this micro:bit A) send the day and time. However, let's make it interesting and have the second micro:bit (we will call this micro:bit B) request this data. In this part of the experiment, we will be listening for a string/number pair before sending out the data.

    Hardware Hookup

    We recommend having just the weather station's micro:bit connected for this section to avoid confusion when uploading code.

    Inserting a USB Cable into the Micro:bit on the Weather Station's Side

    Nothing is new here - the setup is the same as the previous experiment. We recommend having just the weather station's micro:bit connected for this section to avoid confusion when uploading code.

    Weather Station Setup on a Table

    Running Your Script

    We are going to use Microsoft MakeCode to program the micro:bit. You can download the following example script and move the *.hex file to your micro:bit. Or use it as an example to build it from scratch in MakeCode.

    Code to Note

    This is pretty much the same code that was used in 2.1 and 4.1 except for one addition.

    Screenshot of Code

    Click on image for a closer view.

    The only difference is that we are now requesting the weather station's data after each interval. If we receive the request from the micro:bit B in the form of a string/value pair, we will begin sending the readings as we do in the previous examples.

    Closeup of Code

    5.2 Requesting and Recording Readings in Intervals

    In this section, we will request data from the weather station after a certain period of time has passed. If we receive everything, we will output the readings to either the serial terminal or OpenLog.

    Hardware Hookup

    To avoid confusion when uploading code, unplug the first micro:bit from your computer. Then connect the second micro:bit to your computer via USB cable.

    Insert Second micro:bit

    If you have not already, insert the microSD card into the OpenLog.

    microSD Card inserted into OpenLog's microSD Card Socket

    Then make the following connection using the circuit diagram. You'll need to connect a few parts together using a combination of M/M jumper wires on a breadboard. Then using the alligator with pigtails, you will need to connect the gator:RTC to the rest of the circuit.

    Circuit Diagram

    Your setup should look similar to the image below.

    micro:bit connected to OpenLog and gator:RTC

    Running Your Script

    We are going to use Microsoft MakeCode to program the micro:bit. You can download the following example script and move the *.hex file to your micro:bit. Or use it as an example to build it from scratch in MakeCode.


    Note: You may need to disable your ad/pop blocker to interact with the MakeCode programming environment and simulated circuit!

    Code to Note

    This is quite a lot of code but don't worry, we did most of the work in previous examples! We are also repeating most of the steps for each sensor reading so don't feel overwhelmed. Let's inspect the changes.

    Screenshot of Code

    The code is pretty big. You can click this image for a closer view. However, it would be better to just view the entire code in the MakeCode editor.

    In the on start block, we want to be able to easily send serial to either the serial terminal or OpenLog. We create a variable called Debug and set it equal to 0. We also set up a variable to be able to set the RTC's day and time. We will call this Set_RTC and set it equal to 0. Write_Data is also created to output the comma delimited data and is initially set to 0.

    Depending on the value of Debug, we direct which of the pins to send the serial data to and adjust the baud rate as necessary using condition statements. We will also have have a condition statement for setting the day and time. If the Set_RTC is set to 1, we will set the day and time from the gator:RTC extension blocks. For simplicity and avoiding confusion, we will just use military time.

    Closeup of Code

    Click image for a closer view

    We set the radio, header to help read the data, arrays, and a variable to keep track of the total number of readings received.

    Closeup of Code

    Click image for a closer view

    The variables for Past_DD_MM_YYYY and Past_HH_MM_SS will be useful when requesting data over a certain period of time. This period of time will be our Interval in seconds and we set it equal to 30 seconds. The time it takes for all 10 string/number pairs is about ~15 seconds so we will want to give it some breathing room for micro:bit B to finish what it is doing before requesting the next set of readings. We then set up condition statements to convert the interval to either the Past_Hour, Past_Minute, or Past_Second.

    Closeup of Code

    Click image for a closer view

    In the forever block, we will keep checking the time. Each time we jump into the if statement, we will convert the time into seconds. If the time is greater than or equal than the last time that we recorded data, we will save the date and time. We will then send a request to micro:bit A to begin sending data back.

    Closeup of Code

    Click image for a closer view

    We will not send comma delimited readings through the serial terminal or OpenLog until we press button A. If we press this button, we will begin writing serial data to either port just like we did in the micro:climate kit experiment guide.

    Closeup of Code

    You will notice in parts of the on radio received namevalue block that it is not exactly the same as the previous experiment. Since we are recording data, we do not want to also record any output that was used to debug the code. Therefore, we add an if statement to only send these messages to the serial terminal when we are in debug mode.

    Closeup of Code

    Click image for a closer view

    We will also add a small 100ms pause to give the micro:bit some time to write data to either serial port.

    Closeup of Code

    Click image for a closer view

    What You Should See

    The code is set currently to output sensor data to the OpenLog. If you have not set up your RTC, you will need to adjust a few settings. Just before uploading the code to micro:bit B, make sure to adjust these settings:

    • Debug to 1
    • Set_RTC to 1
    • set date to _________ , _____ __ ____ to the current date
    • set time to __ : __ : __ AM to the current time

    When set, pair micro:bit B to your computer to use the one-click download feature for MakeCode. Upload code and click on the "Show console Device" button begin viewing the serial output in the MakeCode console. Then power up micro:bit A that is attached to the weather station. micro:bit B will begin requesting data from micro:bit A as soon as we are within our specified interval. Press button A on micro:bit B to write data to the serial terminal.

    Wireless Remote Weather Station with micro:bit Demo

    If we received all 10 readings, we will output the date, time, and 9 readings that were received. Try changing the sensor readings on the weather station every 30 seconds to see if the values are responding to your input. If it is, we are good to start logging data!

    Serial Output of Data Received Checked, and Printed in a Comma Delimited Row

    Unplug the weather station from your computer if you are using it to power micro:bit A. Then adjust the settings to direct serial data to the Openlog and turn off any comment that was used for debugging.

    • Set_RTC to 0
    • Debug to 0

    We will assume that micro:bit B is still paired to your computer. Click the Download button to upload code. Power up the weather station again and hit button A to start sending serial data to the OpenLog. Try changing the sensor readings on the weather station every 30 seconds and waiting a bit to obtain some sensor readings. Hit button A again to stop recording. Remove power from micro:bit B.

    Insert the microSD card into a microSD card reader. Open up the saved file in your favorite text editor or spreadsheet to inspect the values. If the readings make sense, our weather station is ready! Depending on your application, try adjusting the interval to record data to 5 minutes, 15 minutes, 30 minutes, or an hour!

    MicroSD card in Card Readers

    If you are a user of Google Sheets, try importing this data on a spreadsheet like we did at the end of the micro:climiate kit experiment guide. You can import this text file as a CSV and then graph these values pretty easily. We recommend this quick guide from Google on how to import a .txt file as a CSV into sheets.


    Coding Challenges

    Read/Write Different Files on the OpenLog

    The examples created a file every time the OpenLog is powered up and we simply wrote data to one file. Can you try to write data to a specific file using the gator:log extension? Note that the OpenLog has the same functionality as the gator:log but they have a different board layout.

    gator:log Extension

    Average, High/Low, Totals for the Day?

    How hot was it today? What time was it when the day was at its coldest? Try making additional variables to keep track of the average, high, low, and/or totals for each day. Then try to cycle through the readings in a serial terminal or serial enabled LCD when pressing a button.

    Transmitting Other Sensor Readings

    Try adding another sensor to the weather station's Qwiic connector. Want to monitor the UV light coming from the sun? Try adding the gator:UV to monitor UV exposure in a certain location. Or try adding a microphone to monitor noise levels in your neighborhood.

    SparkFun gator:microphone - micro:bit Accessory Board

    SparkFun gator:microphone - micro:bit Accessory Board

    SEN-15289
    $6.95
    SparkFun gator:UV - micro:bit Accessory Board

    SparkFun gator:UV - micro:bit Accessory Board

    SEN-15273
    $6.95

    Serial LCD Display

    Try soldering some headers on the serial enabled LCD display and send serial data from the receiving micro:bit via serial UART or I2C port. This can display a lot more readings in a small amount of time compared to the LED array without the need for a computer. Can you toggle between each reading using buttons?

    SparkFun 20x4 SerLCD - Black on RGB 3.3V

    SparkFun 20x4 SerLCD - Black on RGB 3.3V

    LCD-14074
    $24.95
    6
    SparkFun 16x2 SerLCD - Black on RGB 3.3V

    SparkFun 16x2 SerLCD - Black on RGB 3.3V

    LCD-14072
    $19.95
    5
    SparkFun 16x2 SerLCD - RGB on Black 3.3V

    SparkFun 16x2 SerLCD - RGB on Black 3.3V

    LCD-14073
    $19.95
    3

    Broadcasting

    Have more than two micro:bits? Try modifying code to broadcast a signal from one micro:bit to several micro:bits by having the receiving micro:bits on the same channel!

    LEDs

    If you have the gator:bit or some WS2812-based LEDs, try having the LEDs react based on the temperature that the weather station is sensing. Or try alerting yourself with a color when the soil moisture and temperature are not ideal for your plants.

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

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

    DEV-15162
    $19.95
    LED RGB Strip - Addressable, Sealed, 1m (APA104)

    LED RGB Strip - Addressable, Sealed, 1m (APA104)

    COM-15205
    $24.95

    "Earth" Rover

    Try adding the weather station on a robot to survey the weather at different locations. You'll need a robot that is able to handle the terrain but for flat surfaces, the micro:bot will work. Try using one micro:bit for the weather station, one for the micro:bot, and one for the remote controller. Can you switch between modes to survey the environment and control the micro:bot?

    Troubleshooting

    Not working as expected? Below are a few troubleshooting tips to get your micro:bits working as expected. For your convenience, relevant troubleshooting tips from the micro:climate experiment guide were included below.

    • Not Receiving a Signal?

      • Make sure that the micro:bits are on the same channel.
      • Make sure that the name/value pair sent is what you expect.
      • Make sure that your are sending and receiving a name/value pair.   

    • The Second Micro:bit is Reacting Without Sending Data from the First Micro:bit.

      • If you have more than one micro:bit transmitting on the same channel, the receiving micro:bit may be reacting to other micro:bits sending on the same channel. Make sure that each micro:bit pair is on their own unique channel. You can also try to adjust the number being transmitted on each micro:bit to react to certain number.   

    • I Upgraded My micro:bit's Firmware and I am Unable to Pair using the WebUSB Feature.

      • Check your USB cable to ensure that it is not just a power cable. If you previously uploaded code to the micro:bit by dragging and dropping a *.hex file to the board, the issue is probably software related. Just in case, try restarting your computer or uploading code with the cable on a different computer to troubleshoot the issue.
      • Make sure that your browser is able to support the WebUSB feature.    

    • The USB Cable is Functional and My Browser is Supported. However, I am Still Having Issues Connecting My micro:bit with the WebUSB Feature.

      • Another reason may be due to a conflicting driver. If you are on a Windows computer, open the Device Manager by clicking the search button. Then type "device manager" to open it up. Scroll down to Ports (COM & LPT) and Universal Serial Bus Controllers. Then open the trees. If the board shows up as "Ports (COM & LPT)>mbed Serial Port (COM#)" and "Universal Serial Bus Controllers>mbed Composite Device" respectively, you will need to uninstall the mbed drivers. These may have been installed if you were using MicroPython with micro:bit.

        Try heading over to micro:bit support page for instructions on how to uninstall the driver. They included a neat GIF demonstrating how to uninstall the conflicting drivers.    

    • I Uninstalled the MBED Drivers but I am Still Having Issues Connecting My micro:bit with the WebUSB Feature.

      • If you follow the directions above to uninstall the mbed drivers for a Windows computer and are still having issues, the mbed drivers may still be installed somewhere (shout out to user "Wim van der Vegt" for the tip). Caution! Caution is advised when following instructions to delete the drivers! You are handling system files which can cause issues with your computer if you accidentally delete the wrong files!

        Open the File Explorer and paste the following path in the address bar: C:\Windows\System32\drivers. Then try looking in the folder for mbedComposite.sys or mbedSerial.sys (there may be a suffix "_x64" in the file name).

        If you see those files, try uninstalling the driver from the Device Manager as explained the earlier. Then delete the mbedComposite.sys or mbedSerial.sys files from the folder. To ensure that the changes take effect, restart your computer. Windows will automatically install the appropriate drivers for your micro:bit.    

    • weather:bit or gator:RTC Blocks are Not Visible.

      • Make sure you have a network connection and you have added the extension to your MakeCode environment.
      • Try installing it again from the add extension option in MakeCode.   

    • micro:bit Not Showing Up.

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

    • Data Seems Odd and Does Not Make Sense.

      • Make sure that the BME280 is free from contact with sources of heat and/or moisture (for example, having your finger over the top of it). Also, make sure that your wiring is correct. If you wire the soil moisture or waterproof temperature sensor incorrectly it will give unexpected results. You will also need to make sure that the weather meter's are connected to the correct RJ11 sockets and fully inserted in the socket. You will hear a "click" when you fully insert the connectors.    

    • I am Constantly Seeing a ??? from the Wind Vane.

      • If you are getting a ??? for the wind vane, this may be due to a loose connection. Make sure that the RJ11 is fully in the socket as explained above. The micro:bit also reads the voltage from the wind vane using an analog pin. The makeCode extension was written to read 8 cardinal directions for simplicity. When the magnet closes one of the reed switches inside the wind vane, the micro:bit will read a certain value. The ??? indicates that micro:bit read the wind vane at a certain moment when the magnet was within a small region somewhere between the 8 cardinal directions. This also may be due to a conflicting pin causing an invalid reading. Try writing a condition statement to ignore this invalid data point and taking another measurement.    

    • What is North?

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

    • I am Getting a Lot of Rain?

      • Every time the bucket tips, it is measured as rainfall. If you bump into the sensor or if it is vibrated it may trigger the sensor and you get a false reading.   

    • Doesn't Seem to be Logging.

      • Make sure your openLog is oriented correctly and connected to the correct pins. Also, make sure that you set the micro:bit to log data by pressing the A button or setting Write_Data to 1 when the variable is initialized. you may also want to check your microSD card to see if it is compatible.    

    • The Log has Weird Characters.

      • Make sure you have the serial baud rate set to 9600!    

    Resources and Going Further

    Now that you've successfully got your micro:bits communicating, it's time to incorporate it into your own project! If you have not already, try making an enclosure or your weather station. The following tutorial uses a different programming language but it is a good illustration of how to place your sensors in an enclosure.

    Weather Station Wirelessly Connected to Wunderground

    April 11, 2014

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

    Need more inspiration? Check out our other sensors and weather stations used in other languages found in our weather section.

    Weather Station Wirelessly Connected to Wunderground

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

    SparkFun BME280 Breakout Hookup Guide

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

    Photon Weather Shield Hookup Guide V11

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

    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.

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

    Understanding Thermal Resistance

    $
    0
    0

    Understanding Thermal Resistance a learn.sparkfun.com tutorial

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

    Introduction

    When working with low power devices, thermal management isn’t much of an issue. Once you start adding motors, LED strips, and the current draw of the project goes up, parts can start to get hot. If you don’t manage the heat, parts can overheat, shortening the life of the component. In this tutorial we’ll cover what thermal resistance is, how it’s used for thermal management, and how to maximize the life of your project.

    Suggested Reading

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

    Voltage, Current, Resistance, and Ohm's Law

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

    How to Use a Multimeter

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

    Thermal Resistance

    To understand how power losses affect the heat generated, you first need to understand Thermal Resistance (Rθ). Similar to how electrical resistance resists the flow of current in ohms, thermal resistance resists the flow of heat in Kelvins per watt, or in degrees Celsius per watt. We can use thermal resistance to estimate how hot a particular part might get under various loads based on how easily the heat is able to be transfered from one place to another. For electronics the heat starts at the source, such as a semiconductor junction, and spreads to be eventually dissipated to ambient air.

    If the junction of a semiconductor exceeds its maximum temperature it will break and let all the magic smoke out. To make sure we don't do that, we need to look at how efficiently the device is able to use the power.....

    Ohm’s Law and Thermal Resistance

    We can use ohm’s law to calculate the temperatures from the heatsink to the junction, and everywhere in between using Ohm’s Law. As mentioned earlier, electrical resistance is very similar to thermal resistance. We can use Ohm’s Law which states that V = I*R, and replace the voltage for temperature (T) and current for power (P), which gives us:

    Thermal version of Ohm's Law

    The equivalent thermal circuit is shown below where:

    • T_Junction (TJ): the junction temperature
    • RθJC:the junction to case thermal resistance
    • T_Case (TC): the junction temperature
    • RθCH: the case to heatsink thermal resistance
    • T_Heatsink (TH): the heatsink temperature
    • RθHA: the heatsink to ambient air thermal resistance
    • T_Ambient (TA): the ambient air temperature

    Thermal Circuit Schematic

    To better understand how thermal resistance is used, lets look at the following example:

    • Power dissipated: 2W
    • RθJC = 4°C/W
    • RθCH = 0.5°C/W
    • RθHA = 6°C/W
    • TA = 25°C

    Starting with the thermal equivalent of Ohm's Law:

    Thermal version of Ohm's Law

    We want to solve for our junction temperature rise , so T becomes TJ. Our power dissipated, P, is 2W. And our thermal resistances are in series, so just like resistors in series in a circuit we can add the values together:

    Thermal version of Ohm's Law

    The junction temperature is 20.5°C above ambient temperature (25°C in this case), which means the absolute temperature is 20.5°C + 25°C, which would be 45.5°C.

    Where do you find the thermal resistance values? For parts like voltage regulators, diodes, transistors, and other semiconductors, the datasheet will have a section for the thermal information, mainly the Junction to Air (RθJA) if some type of heatsink weren't used, or Junction to Case (RθJC) if a heatsink was going to be used, which would have its own thermal resistance and is covered in the next section. The typical thermal resistance data would look similar to the image below.

    Thermal Resistance in a Datasheet

    How to Transfer Heat

    Metal Fin Heatsinks

    Photo of a heatsink

    Heatsinks some in all shapes and sizes, with a single purpose: transfer heat to the air. The purpose of each of the fins on a heatsink is to create as much surface area as possible for the air to interact with and pull heat away from the heatsink, which helps to pull heat away from the semiconductor’s junction. The thermal resistance of a heatsink can be a bit complicated though because a metal fin heatsink performs at different rates based on the amount of air flowing past the fins. A typical datasheet for a heatsink provides not only the dimensions of the part, but the thermal characteristics as well, which looks like this:

    Typical thermal characteristics of a heatsink

    The arrows on each plot line correspond to the axis they represent. For example, the red highlight shows that in free air (ie without a fan), dissipating 10W of power would raise the temperature of heatsink around 78°C above ambient temperature. If instead you had around 400ft/min of air flowing along the fins of the heatsink, the green line shows the heatsink would have a thermal resistance of around 1.8°C/W, or 18°C above ambient temperature dissipating the same 10W of power.

    Vias

    If you need to add a heatsink to the design, designs like switch mode power supplies where it’s important to keep components as close to the IC as possible, vias can not only transfer signals from one side of the PCB to the other, but they can transfer heat too!

    If you don’t feel like doing a bunch of math, the PCB Toolkit from Saturn PCB Design Inc has a lot of great tools to solve a ton of the equations an electrical engineer might use. One of the tabs in particular is for via properties:

    Photo of PCB Toolkit from Saturn PCB Design Inc

    Image courtesy of SaturnPCB

    To get the thermal resistance of the vias, I entered in the boxes I highlighted red the properties of the PCB I have. Setting the layer set to 2 layer, and the via hole diameter should be the only setting you might need to change. The via plating thickness and via height are pretty standard for most PCBs. After clicking solve, in the blue box in the bottom right corner I got the thermal resistance which was 179.3°C/W per via. With 10 vias, the via thermal resistance drops down to 17.9°C/W. If you were going to calculate the junction temperature now, you would add another thermal resistance in series for the vias, which would be added with the other thermal resistances when you do the calculation.

    PCB Heatsinking

    When it comes to transferring heat in a PCB, the math can get complicated pretty quickly, which is one of the reasons why for via thermal resistance, using the tool from Saturn PCB is the easier way to go. Even more complicated is using a PCB as a heatsink. There’s the thermal resistance not only of the copper, which is a function of the surface area, but the solder mask, substrate material, which also transfers heat to surrounding isolated copper planes. For a thorough explanation, you can read this application report from Texas Instruments. For easier to digest information, Paul Bryson has a great blog post on the subject and provides some great tips and findings which can be found here.

    For a rough guide you can use the graph from Paul Bryson's post below:

    PCB Thermal Resistance Graph

    Image courtesy of Paul Bryson of brysonics.com

    Example: PTH Linear Regulator

    Let’s see how well the thermal resistance calculations work in the real world. For these examples I’m going to use two different kinds of voltage regulators, a linear regulator, specifically the LM7805, as well as a DC-DC converter. We’ll see how well they stand up to the numbers we get from the datasheets.

    Linear Regulator

    Having a low cost and low noise voltage regulator, how can you go wrong? Linear regulators are a great choice for many applications, but where they fall short is their efficiency. We can see the basic design of a linear regulator below:

    Linear Regulator Schematic

    Image courtesy of EE Times

    To determine how hot a linear regulator will get, let’s start with the understanding that the input power must equal the output power. Ideally, the system would be 100% efficient, but in the real world there are going to be some losses, and that power loss is dissipated in the form of heat (PD). This can be expressed as the following formula:

    Calculating Pin as Pout plus Pdissipated

    This means that the power dissipated can be expressed as:

    Calculating Power dissipated as Power In minus Power out

    In electronics power can be expressed as the product of the voltage and current. Which means we can rewrite the first equation as:

    Power Dissipated is (Vin * Iin) minus (Vout * Iout)
    With linear regulators the input and output current is the same, so we can simplify the equation to the following:

    Simplified, the Power dissipated is the Current times (Vin minus Vout)

    Now we need to look at the thermal characteristics of the linear regulator. The LM7805, has the following thermal resistances for the TO-220 package being used:

    Thermal Characteristics for the LM7805

    Without a heatsink (RθJA)

    For this first example, we’ll see how hot a linear regulator gets with only a 200mA load. TheLM7805 has an output voltage of 5V, and the input voltage will be around 12V. Plugging those numbers into our power loss equation from above, gives us:

    Simplified, the Power dissipated is the Current times (Vin minus Vout)

    Calculating power dissipated as 1.4 watts without a heatsink

    To figure out how hot that will get without a heatsink, we’ll need to use the Junction to Air thermal resistance, which is 50°C/W. Using the formula from the thermal resistance section, and assuming ambient air temperature is 23°C, we can calculate the junction temperature to be:

    Junction temperature is Power Dissipated times AirThermalResistance plus Ambient temp

    Calculating Junction Temperature as 93 degrees C

    To see how that compares to the real world, I measured the input voltage to be 12.1V and the output voltage under load to be 4.90V. I used a constant current dummy load set to 200mA connected to the output. Using the measured values, the dissipated power is:

    Setting up dummy load to calculate power dissipation as 1.44W

    The expected junction temperature should then be:

    Adjusted junction temperature calculation is 95 degrees C

    Thermal Image of LM7805 Under Load without a heatsink

    As the thermal image above shows, after turning on the load and letting the regulator heat up, it settled at a temperature of around 98°C. Pretty close, but it’s a good example of why it’s important to add margins to numbers. Due to the lack of precision, the power supply was slightly higher than we calculated, and under load, the regulator has a output voltage tolerance of 4%, which could allow the output voltage to drop to as low as 4.8V and still be in spec.

    With a Heatsink (Using RθJC)

    Now with the addition of a heatsink, instead of using the thermal resistance from the junction to air, we need to use the value for junction to case, which is around 5°C/W. After looking at the datasheet for the heatsink I’m using, ~1.4W of power in free air would result in a 25°C temperature rise:

    Heatsink temperature raise for 1.4W of power

    Because the heatsink provides a temperature rise instead of a thermal resistance, We will need to first calculate the junction temperature rise using the thermal resistance from the junction to the heatsink, and then add on temperature rise from the heatsink and ambient air temperature to get the junction temperature. Using thermal compound lowers the thermal resistance from the case to the heatsink (~0.25°C/W), without it we'll assume the thermal resistance is around 1°C/W. The junction temperature equation therefore becomes:

    Junction temperature calculated with a heatsink added in

    Junction temperature is calculated as 56.4 degrees C when using a heatsink

    The actual voltages were the same as without a heatsink: Vin = 12.10V, Vout = 4.90V, Iout = 200mA. This resulted in the same 1.44W of power that actually needed to be dissipated, which only increased the calculated junction temperature to 56.64°C. After turning on power and enabling the load, I waited to let the temperature get up to a steady state temperature and measured the temperature of the regulator to be around 54°C.

    Thermal Image of LM7805 Under Load with a heatsink

    This time the temperature was lower than we calculated. Most likely the error came from reading the temperature rise in still air for the heatsink, instead of 25°C, it could have been closer to 23°C. In the last example we’ll use a surface mount regulator and try to estimate how hot the regulator gets using the PCB as a heatsink.

    Example: SMD DC/DC Converter

    The board we’re using is the Buck-Boost, which uses the TPS63070 DC-DC converter. The board is 1.25x1.25 inches using 1oz copper. Other things to note, is the regulator is in the center of the board, and is over 95% solid copper. Because of the size, I’m going to make some assumptions by using the total board area for the thermal resistance, and use all 41 vias for the via thermal resistance.

    To get started we need to figure out how much power we need to dissipate. With a DC-DC converter, the input current does not equal the output current, so we can’t use the same formula as we did for the linear regulator. Instead we can estimate using the efficiency graph from the datasheet:

    DC/DC Converter Efficency Graph at 5V out

    The efficiency graph plots the efficiency as a function of the output current, which is different based on the input and output voltages. For this test, we’ll use the same values before, having an input voltage of 12V and output voltage of 5V. This time though we’ll increase the load current to 1.0A. Using the 5V efficiency graph above, the efficiency should be around 93%, which would make our power loss 7% of the output power.

    Example power dissipation efficiency

    For the thermal resistances I used the via thermal resistance calculator and approximated the thermal resistance with the vias to be around 4.4°C/W using the values from the via calculation tool. To estimate the PCB thermal resistance, the board will be elevated off the table, to prevent using the table a heatsink. But because the bottom of the board is also in contact with the air, the surface area is now doubled from 10.08cm^2 to 20.16cm^2. Based on the surface area for the buck-boost board, I can estimate the PCBs thermal resistance to be around 65°C/W.

    PCB Thermal Resistance Highlight

    The datasheet for the TPS63070 has the following for the thermal characteristics:

    TPS63070 Thermal Characteristics

    Click on the image for a closer view.

    The junction to case thermal resistance is not applicable, however the junction to board thermal resistance is, which is around 13°C/W. Using the thermal resistance values, we can plug that into the junction temperature equation:

    calculating junction temperature with Power dissipated, junction to board thermal resistance, Via to Board thermal resistance, board to air thermal resistance, and ambient temperature

    Final junction temperature calculation using heat sink

    Just like before, I enabled the dummy load and let the board heat up until the temperature stopped rising. As shown below, I recorded a temperature of around 54°C.

    Thermal Image of a PCB Heatsink

    Resources and Going Further

    You can do these same calculations for a variety of power parts. For example you can look at the resistance between the drain and source of a mosfet to see how hot it might get at various currents. Or if you have a diode for reverse current protection, you can use the forward voltage drop and current. All these components will generate some amount of heat, but now you can take an educated guess as to how much.

    Wanna use your new found skill set? Try out these great tutorials!

    Simultaneous RFID Tag Reader Hookup Guide

    A basic guide to getting started with the RFID Tag Reader breakout and how to read and write multiple RFID tags over multiple feet!

    ESP32 Thing Power Control Shield Hookup Guide

    This tutorial shows you how to get started with the ESP32 Thing Power Control Shield.

    Variable Load Hookup Guide - Revised

    This tutorial will show you how to assemble and use SparkFun's Variable Load board. It can be used to test stability of the power supply under various loads, battery lifetime, safety cutoffs, and other design elements of power supplies under test.

    Buck-Boost Hookup Guide

    This tutorial shows you how to hook up and use the SparkFun Buck-Boost board.

    Magnetic Levitation

    This tutorial will show you how to build a magnetic levitation circuit using common parts.

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

    SparkFun Environmental Sensor Breakout - BME680 (Qwiic) Hookup Guide

    $
    0
    0

    SparkFun Environmental Sensor Breakout - BME680 (Qwiic) Hookup Guide a learn.sparkfun.com tutorial

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

    Introduction

    The SparkFun Environmental Sensor - BME680 (Qwiic) is a breakout for the 4-in-1 BME680 gas sensor from Bosch. The BME680 combines a gas sensor with temperature, humidity and barometric pressure sensing for a complete environmental sensor in a single package. The gas sensor on the BME680 can detect a wide variety of volatile organic compounds (or VOC for short) to monitor indoor air quality. Combine that with precise temperature, humidity and barometric pressure and the BME680 can work as a completely standalone environmental sensor all in a 1x1" breakout! The BME680 communicates over either I2C or SPI. As you would expect from the name, the BME680's I2C pins are broken out to a Qwiic connector so integrating it into the SparkFun Qwiic System is a breeze. Simply plug it into a Qwiic-enabled microcontroller and you're well on your way to making your own weather station.

    SparkFun Environmental Sensor Breakout - BME680 (Qwiic)

    SparkFun Environmental Sensor Breakout - BME680 (Qwiic)

    SEN-16466
    $18.95

    Required Materials

    To follow along with this guide you will need a microcontroller to communicate with the BME680. Below are a few options that come Qwiic-enabled out of the box:

    SparkFun Qwiic Pro Micro - USB-C (ATmega32U4)

    SparkFun Qwiic Pro Micro - USB-C (ATmega32U4)

    DEV-15795
    $19.95
    SparkFun Thing Plus - ESP32 WROOM

    SparkFun Thing Plus - ESP32 WROOM

    WRL-15663
    $20.95
    2
    SparkFun RedBoard Qwiic

    SparkFun RedBoard Qwiic

    DEV-15123
    $19.95
    5
    SparkFun RedBoard Artemis

    SparkFun RedBoard Artemis

    DEV-15444
    $19.95
    3

    If your chosen microcontroller is not already Qwiic-enabled, you can add that functionality with one or more of the following items:

    SparkFun Qwiic Cable Kit

    SparkFun Qwiic Cable Kit

    KIT-15081
    $7.95
    4
    SparkFun Qwiic Shield for Arduino

    SparkFun Qwiic Shield for Arduino

    DEV-14352
    $6.95
    SparkFun Qwiic Adapter

    SparkFun Qwiic Adapter

    DEV-14495
    $1.50
    1
    SparkFun Qwiic Shield for Arduino Nano

    SparkFun Qwiic Shield for Arduino Nano

    DEV-16130
    $3.50

    You will also want at least one Qwiic cable to connect your sensor to your microcontroller.

    Qwiic Cable - 100mm

    Qwiic Cable - 100mm

    PRT-14427
    $1.50
    Qwiic Cable - 200mm

    Qwiic Cable - 200mm

    PRT-14428
    $1.50
    Qwiic Cable - 50mm

    Qwiic Cable - 50mm

    PRT-14426
    $0.95
    Qwiic Cable - 500mm

    Qwiic Cable - 500mm

    PRT-14429
    $1.95

    Suggested Reading

    If you are not 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 the concepts covered in 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.

    Serial Terminal Basics

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

    Hardware Overview

    The heart of this breakout, Bosch's BME680 Gas Sensor, integrates four sensors (gas, pressure, temperature and humidity) into a tiny package. The BME680 measures just 3mm x 3mm x 0.93 mm and was specifically designed for applications that depend on a small footprint and low power consumption. This makes the BME680 a great choice for remote or mobile environmental sensing applications. We will highlight some of the unique aspects of the BME680 in this section but for a full overview of the sensor package, check out the Datasheet.

    Power

    The BME680 accepts a supply voltage between 1.71 to 3.6V. Power can be supplied to the board either through one of the Qwiic connectors or the dedicated 3.3V and GND pins broken out on either side of the board.

    BME680 Power Inputs Highlighted

    Qwiic and I2C Interface

    The SparkFun Environmental Sensor - BME680 (Qwiic) communicates over I2C by default. We have routed the BME680's I2C pins to two Qwiic connectors as well as broken them out to 0.1"-spaced the header pins highlighted below.

    BME680 Qwiic and I2C Interface Highlighted

    Serial Peripheral Interface (SPI)

    If you would prefer to communicate with your BME680 via SPI, we have broken those pins out as well to standard 0.1"-spade header pins. Communicating over SPI requires more connections than I2C but is more versatile and can be faster. It is particularly helpful if you need to use more than two BME680's in your circuit or if you have other devices using the same I2C addresses.

    SPI Pins Highlighted

    Jumpers

    The SparkFun Environmental Sensor - BME680 (Qwiic) has three solder jumpers which can be modified to alter the functionality of the sensor.

    If you have never worked with solder jumpers or PCB traces before or would like a refresher, take a look at our How to Work with Jumper Pads and PCB Traces tutorial.

    I2C Pull-Up Jumper

    The SDA/SDI and SCL/SCK pins are pulled to VDDIO (3.3V) through a pair of 4.7k Ohm resistors. The jumper is normally closed so to disable the pull-up resistors, simply sever the traces between the three pads using a hobby knife.

    I2C Jumper Highlighted

    Power LED Jumper

    This jumper connects the power LED to 3.3V via a 1K Ohm resistor. This jumper is normally closed so to disable the power LED, sever the trace between the two pads. This is particularly helpful for reducing the total current draw of your breakout for low-power applications.

    Power LED Circuit highlighted

    I2C Address Jumper

    This jumper sets the 7-Bit unshifted I2C address of the BME680 and is open by default. The default address is 0x77 and can be adjusted to 0x76 by closing this jumper.

    Address Jumper Highlighted

    Board Dimensions

    This breakout fits the Qwiic standard sizing for breakouts. It is a 1x1" square with two mounting holes that fit a 4-40 screw.

    Board dimensions

    Now that we have a thorough understanding of the hardware and features on the Environmental Sensor - BME680 (Qwiic), it's time to hook it up and start taking measurements.

    Hardware Hookup

    Using the Qwiic system, assembling the hardware is simple. All you need to do is connect your Environmental Sensor - BME680 (Qwiic) to your chosen development board with a Qwiic cable or adapter cable. Otherwise, you can use the I2C pins broken out if you do not have a Qwiic connector on your development board or if you do not want to use a Qwiic connection. If you are not using a Qwiic-enabled board, make sure your input voltage and logic are either running at 3.3V or you are shifting the logic level from whatever logic your controller runs at to 3.3V for the BME680.

    BME680 Connected to a RedBoard Qwiic

    If you would prefer to communicate with the BME680 via SPI, you will need to connect to the SPI pins broken out on this board and route them to the respective pins for SPI communication on your development board (MISO, MOSI, SCK and CS/SS). Also note that this breakout defaults to I2C mode so your code will need to toggle the CS pin LOW once on power up to enable SPI mode. The BME680 will remain in SPI mode until the next power cycle. The SPI examples further on in this guide do that automatically so it's only necessary to note for writing your own code.

    Soldering to the pins is the best option for a secure connection but you can also create temporary connections to those pins for prototyping using something like these IC Hooks. If you are not familiar with through-hole soldering, take a look at this tutorial:

    How to Solder: Through-Hole Soldering

    September 19, 2013

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

    With everything connected properly, we're ready to move on to uploading a sketch and start monitoring your environment!

    BME680 Arduino Library

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

    For the scope of tutorial, we are going to use the BME680 Arduino Library created by SV-Zanshin. You can download it with the Arduino Library Manager by searching 'BME680' and selecting the one authored by SV-Zanshin. Alternatively, you can grab the zip of the latest release (v1.0.3 as of this writing) below or you can download the most up to date version of the library from the GitHub repository.

    Once you have the library installed you can move on to uploading the examples and gathering environmental data.

    Arduino Examples

    Now that the library is installed, we can move on to uploading some code. Before we discuss the individual examples, we'll cover some of the setup they perform for the BME680.

    The code configures the BME680 to perform oversampling for the temperature, humidity and pressure sensors and sets an IIR (infinite impulse response) filter for these sensors. This helps smooth out environmental data from any short term outliers. Finally, the setup also configures the temperature and time settings for the hot plate on the gas sensor. If you would like to adjust any of these settings, refer to the BME680 Datasheet and the library source files for more information.

    I2C Demo

    To open this example, head to File>Examples>BME680>I2CDemo. Next, open the Tools menu and select your board (in our case, Arduino Uno) and the correct Port your board enumerated on.

    Upload the code, open the Arduino Serial Monitor and set your baud rate to 115200. You probably will see the code print out the successful initialization of the BME680 as well as the settings we discussed above and after that, you should see temperature, humidity, pressure, altitude and raw gas readings every five seconds.

    Sample screenshot of I2C Demo

    SPI Demo

    This example is nearly identical to the I2C demo but instead uses SPI mode. One thing to note is, depending on which type of microcontroller you are using, you may need to adjust this line:

    language:c
    const uint8_t  SPI_CS_PIN   = 53;
    

    Set the CS/SS pin to the appropriate pin on your microcontroller. In our case, the Uno uses D10 for CS so the modified version of that line for an Uno or SparkFun RedBoard Qwiic would be:

    language:c
    const uint8_t  SPI_CS_PIN   = 10;
    

    With that line adjusted, upload the code and open your serial monitor. You should see a similar stream of data as the screenshot above for the I2C example.

    Tip: If you'd like to use this library with a development board with multiple serial ports like the RedBoard Turbo we show in the Hardware Hookup section, you'll want to add this line: #define Serial SerialUSB prior to your void setup(). This definition can be modified to any serial port on your chosen microcontroller.

    Troubleshooting

    In this section we'll cover a few tips and tricks for troubleshooting common questions with the Environmental Sensor Breakout - BME680.

    Gas Readings Interpretation

    The library used in this tutorial only prints out the raw resistance values from the gas sensor on the BME680. You can use these values as a rough estimate of air quality where lower resistance values equate to a higher concentration of gases measured (and vice versa). If you want to get true Indoor Air Quality (IAQ) measurements from the BME680, we recommend taking a look at Bosch's BSEC Arduino Library which includes an algorithm to convert the resistance value to an IAQ value. For more information, refer to that library as well as sections 1.2 and 4.2 in the BME680 Datasheet. Calculated IAQ measurements are beyond the scope of this tutorial.

    Incorrect Temperature Data

    You may notice some deviation from the true ambient temperature in your data as residual heat from the hot plate for the gas sensor in the BME680 can cause minor fluctuations in the observed temperature. The heating phase starts after temperature, pressure and humidity measurements are complete so there should be no heating during those measurements but subsequent readings may be skewed. The IIR filters can help here but if needed, you can compensate for this by measuring the average deviation and subtracting that from your temperature data.

    Incorrect Altitude Data

    The altitude data is collected by converting the barometric pressure. This is a great tool for approximate altitude readings but things like weather patterns can affect the accuracy of the altitude. The examples use the standard measurement for pressure at sea level (1013.25 hPa) in the calculation so you may wish to adjust that with a corrected value for a more accurate altitude data. Refer to this Wikipedia page for more information.

    Chip Select Definition

    As we covered in the previous section, if you choose to communicate with the BME680 via SPI, make sure you are connecting to the correct pins on your development board (MOSI, MISO, SCK and CS) as well as modifying the Chip Select/Slave Select definition to the appropriate I/O pin used for CS on your controller. If you are not certain which pin is used for CS, refer to documentation for your particular development board.

    Resources and Going Further

    Now that your BME680 is integrated in your circuit and sending data it's time to start tracking some weather! For more information about this breakout and the BME680, take a look at the links below:

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

    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.

    Weather Meter Hookup Guide

    How to assemble your very own weather meter!

    Qwiic Kit for Raspberry Pi Hookup Guide

    Get started with the CCS811, BME280, VCNL4040, and microOLED via I2C using the Qwiic system and Python on a Raspberry Pi! Take sensor readings from the enviroment and display them on the microOLED, serial terminal, or the cloud with Cayenne!

    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!

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


    SparkFun Air Quality Sensor - SGP30 (Qwiic) Hookup Guide

    $
    0
    0

    SparkFun Air Quality Sensor - SGP30 (Qwiic) Hookup Guide a learn.sparkfun.com tutorial

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

    Introduction

    Do you want to know the quality of the air in your room or house? Maybe you need to monitor the volatile organic compounds emitted during a 3D Print so you know when to turn on some ventilation (or leave the room!). The SparkFun Air Quality Sensor - SGP30 (Qwiic) may be just the sensor you need! Indoor air quality (referred to as IAQ) sensors are great for measuring CO2 and volatile organic compounts (commonly referred to as VOCs) but some of them like the CCS811 require a burn-in time of 48 hours and a 20-min start up time. By comparison, the SGP30 can return valid IAQ readings within 15 seconds of powering up!

    Along with a very quick start-up time, the SGP30 is very resistant to contamination from other gases to ensure low drift and long-term stability for extremely reliable results. To cap it all off, you can also read the SGP30's raw measurements of ethanol and H2. The SGP30 communicates via I2C so naturally we broke out the pins on the sensor to Qwiic connectors so you can easily connect it to SparkFun's ever growing Qwiic Ecosystem!

    SparkFun Air Quality Sensor - SGP30 (Qwiic)

    SparkFun Air Quality Sensor - SGP30 (Qwiic)

    SEN-16531
    $19.95

    In this guide we will go over the features of the SGP30, how to connect and use it as well as an Arduino library with examples to get you started monitoring your indoor air quality.

    Required Materials

    To follow along with this guide you will need a microcontroller to communicate with the SGP30. Below are a few options that come Qwiic-enabled out of the box:

    SparkFun Thing Plus - ESP32 WROOM

    SparkFun Thing Plus - ESP32 WROOM

    WRL-15663
    $20.95
    2
    SparkFun Qwiic Pro Micro - USB-C (ATmega32U4)

    SparkFun Qwiic Pro Micro - USB-C (ATmega32U4)

    DEV-15795
    $19.95
    SparkFun RedBoard Qwiic

    SparkFun RedBoard Qwiic

    DEV-15123
    $19.95
    5
    SparkFun RedBoard Artemis

    SparkFun RedBoard Artemis

    DEV-15444
    $19.95
    3

    If your chosen microcontroller is not already Qwiic-enabled, you can add that functionality with one or more of the following items:

    SparkFun Qwiic Cable Kit

    SparkFun Qwiic Cable Kit

    KIT-15081
    $7.95
    4
    SparkFun Qwiic Shield for Arduino

    SparkFun Qwiic Shield for Arduino

    DEV-14352
    $6.95
    2
    SparkFun Qwiic Adapter

    SparkFun Qwiic Adapter

    DEV-14495
    $1.50
    1
    SparkFun Qwiic Shield for Arduino Nano

    SparkFun Qwiic Shield for Arduino Nano

    DEV-16789
    $3.95

    You will also need at least one Qwiic cable to connect your sensor to your microcontroller.

    Qwiic Cable - 100mm

    Qwiic Cable - 100mm

    PRT-14427
    $1.50
    Qwiic Cable - 200mm

    Qwiic Cable - 200mm

    PRT-14428
    $1.50
    Qwiic Cable - 500mm

    Qwiic Cable - 500mm

    PRT-14429
    $1.95
    Qwiic Cable - 50mm

    Qwiic Cable - 50mm

    PRT-14426
    $0.95

    Suggested Reading

    If you aren't familiar with the Qwiic system, take a look here for an overview.

    Qwiic Connect System

    We also recommend taking a look at the following tutorials if you aren't familiar with the concepts covered in them. If you are using one of the Qwiic Shields listed above, you may want to read through their respective Hookup Guides as well before you get started with the SparkFun Air Quality Sensor - SGP30 (Qwiic).

    I2C

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

    Serial Terminal Basics

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

    Qwiic Shield for Arduino & Photon Hookup Guide

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

    SparkFun Qwiic Shield for Arduino Nano Hookup Guide

    Hookup Guide for the SparkFun Qwiic Shield for Arduino Nano.

    Hardware Overview

    The brains of this breakout is the excellent SGP30 gas sensor from Sensirion. In this section we will cover some of the features and characteristics of the SGP30 as well as the hardware present on this breakout.

    As we mentioned in the Introduction, the SGP30 gas sensor outputs measurements of total VOCs (TVOC) in parts per billion (ppb), carbon dioxide (CO2) equivalent in parts per million (ppm) as well as raw gas readings of ethanol and hydrogen (H2). The ethanol and H2 readings are primarily intended for the SGP30's on-chip calibration and baseline compensation algorithms but they can be useful for rough measurements of both compounds. Refer to page 8 of the datasheet for more information on these raw signals.

    The table below outlines the basic parameters of each sensing output. For a detailed description of these and all other aspects of the sensor, review the datasheet.

    Sensing ParameterValue
    TVOC Output Signal Range0 to 60,000 ppb
    CO2eq Output Signal Range400 to 60,000 ppm
    Ethanol Signal Measurement Range0 to 1,000 ppm
    H2 Signal Measurement Range0 to 1,000 ppm

    Power

    The SGP30 accepts a supply voltage between 1.62-1.98V so to work with the 3.3V standard for the Qwiic ecosystem, we added a voltage regulator to, well, regulate that 3.3V down to 1.8V. Power can be provided via the Qwiic connectors or through the labeled 3.3V and GND pins broken out to 0.1" header pins on this board.

    Note: While the voltage regulator on this breakout can accept up to a 6V supply voltage, we strongly recommend only using 3.3V as all Qwiic devices are designed to work at that voltage.

    Highlighting the power input and Qwiic connectors

    Qwiic and I2C Interface

    The SGP30 communicates via I2C so of course we broke out these pins to two Qwiic connectors as well as 0.1"-spaced header pins if you would prefer to use standard PTH connections. Since the sensor operates at 1.8V we have added transistors to both the SDA and SCL lines to level shift them from 3.3V so you can use it without issue with other Qwiic devices. Note, the HIGH side of this level circuit is tied directly to your power input so, as the note above regarding supply voltage warns, we recommend to power the board with 3.3V.

    The SGP30's I2C address is 0x58 (1011000 bin) and is hardware-set. If you have other devices that share the same address as the SGP30 or need to use multiple SGP30 sensors on a single I2C bus, you will want to use a multiplexer/mux like the Qwiic Mux Breakout 8-Channel.

    Highlighting the I2C pins and Qwiic Connectors

    Jumpers

    If you have never worked with solder jumpers and PCB traces before or would like a quick refresher, check out our How to Work with Solder Jumpers and PCB Traces tutorial for detailed instructions and tips.

    This breakout has two jumpers; one controls the power LED and the other enables the two 10K Ohm pull-up resistors on the SDA and SCL traces. Both are closed by default. To disable either of the jumpers, simply sever the trace between the pads. Disabling the power LED is particularly helpful for low-power applications to help reduce total current draw of the board. Note, if you disable the pull-up resistors, make sure the other devices on your I2C bus are running at 3.3V to avoid damaging the SGP30.

    Power LED JumperI2C Resistor Jumper
    Power LED JumperI2C Pull-Up Resistor Jumper

    Board Dimensions

    We've designed the SparkFun Air Quality Sensor to match our Qwiic breakout standard. The board measures 1" x 1" and has two mounting holes that fit a 4-40 screw. For specific spacing measurements, take a look at the dimensional photo below.

    Board Dimensions

    Hardware Hookup

    Using the Qwiic system, assembling the hardware is a breeze. All you need to do is connect your SparkFun Air Quality Sensor - SGP30 (Qwiic) to your chosen development board with a Qwiic cable or adapter cable. If you would prefer to not use the Qwiic connectors, you can connect to the 0.1" header pins broken out on bottom of the board.

    Air Quality Sensor connected to a RedBoard Qwiic

    If you decide to use the PTH pins broken out on the Air Quality Sensor you will need to either solder to them. Alternatively, if you want a temporary connection for prototyping, these IC Hooks are a great option to make that connection. If you are not familiar with through-hole soldering take a look at this tutorial:

    How to Solder: Through-Hole Soldering

    September 19, 2013

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

    With the SGP30 connected to your microcontroller it's time to get some code uploaded and start taking measurements!

    SGP30 Arduino Library

    Note: This library 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.

    The SparkFun SGP30 Arduino library can be downloaded with the Arduino library manager by searching 'SparkFun SGP30' or you can grab the zip here from the GitHub repository:

    Library Functions

    The list below outlines all of the functions of the library with some quick descriptions of what they do. The examples cover most of the functions so take a look at those for demonstrations of how to integrate them in your code.

    Before we get into the heart of the functions, we'll first cover a setup type definition that helps with debugging. This enum parses the four integer values returned by the SGP30 to a more "human readable" way.

    language:c
    typedef enum {
    SUCCESS = 0,
    ERR_BAD_CRC,
    ERR_I2C_TIMEOUT,
    SELF_TEST_FAIL
    } SGP30ERR;
    

    This enum allows us to simply tell what error code was returned by its description instead of getting a number for an error which you would then have to "decode". For example, instead of returning error == 0 an error check returns error == SUCCESS. Now, on to the rest of the functions.

    Device Setup & Settings

    • bool begin(TwoWire &wirePort); - Initializes the sensor on the I2C bus and selects the wire port.
    • void initAirQuality(void); - Initializes air quality measurements on the SGP30. Must be called prior to calling measureAirQuality.
    • void generalCallReset(void); - Performs a soft reset of the SGP30. Not device specific and this call can reset any attached device that support the General Call Mode.
    • getFeatureSetVersion(void); - Returns a readout of the feature set version number. Refer to page 8 of the datasheet for more information.
    • getSerialID(void); - Returns a readout of the serial ID register to identify the chip and verify the sensor is connected.
    • measureTest(void); - Runs a self test on the SGP30. This function is primarily used by the manufacturer for testing.

    Measurement Functions

    • measureAirQuality(void); - Returns CO2 values in ppm and TVOC values in ppb. Call in regular 1 second intervals to maintain baseline calculations.
    • setBaseline(void); - Updates the baseline values to a previous baseline. Recommended to only use previously retrieved baselines to maintain accuracy.
    • getBaseline(void); - Returns the current calculated baseline from the SGP30's dynamic baseline calculations.
    • setHumidity(uint16_t humidity); - Set a humidity value for compensation. Default is 15.5g/m3 and if modified, the new humidity value should be taken from a humidity sensor like the SHTC3. Sending 0x0000 resets to default and turns off humidity compensation. Refer to "Example3_Humidity" in our Arduino library for more information on calculating and sending this value.
    • measureRawSignals(void); - Returns raw signals for H2 and ethanol. These values are used as inputs for on-chip calibration and baseline compensation algorithms. Refer to page 8 of the datasheet for more information.

    With the core functions of this Arduino library outlined and explained, it's time to start putting them together in some example code.

    Arduino Examples

    The SGP30 Arduino Library includes nine examples to get you started. For the scope of this tutorial, we'll just cover the first three as they demonstrate the basics of setting up and reading from the SGP30.

    Example 1 - Basic Readings

    A basic example to get you started reading TVOC and CO2 readings from the SGP30. To open this example, navigate to File>Examples>SparkFun SGP30 Arduino Library>Example1_BasicReadings. Next, open the Tools menu and select your board (in our case, Arduino Uno) and the correct Port your board enumerated on.

    Upload the code, open the Arduino Serial Monitor and set your baud rate to 9600. If the sensor initialization returns false, the code will print out "No SGP30 Detected. Check connections." via serial. That error will almost certainly be the result of a bad connection to the SGP30. After successful initialization, it will start to print out TVOC and CO2 readings. Take note that for the first 15 seconds after sensor power up or reset, the readings will be: CO2 : 400 ppm and TVOC : 0 ppb so if you are logging the data using, say, the OpenLog Artemis, you will want to ignore these first 15 readings.

    After the first 15 readings have passed, try breathing lightly near the sensor and you should see the CO2 readings jump significantly from the 400 ppm baseline. These basic readings are good to get started and making sure your sensor is connected and functioning, but for more accurate readings, you'll probably want to include a compensation value from a humidity sensor like we demonstrate in Example 3 - Humidity.

    Example 2 - Raw Signals

    This example includes both the TVOC and CO2 readings from the SGP30 along with raw readings for ethanol and H2. The Ethanol and H2 values are primarily for internal processing on the SGP30 but you can use them for rough measurements of both gases.

    Open the example from the Examples menu as we did above and select Example2_RawSignals. Select your Board and Port and upload the code. Open the Arduino Serial Monitor again and set your baud to 9600. You should see readings for CO2, TVOC, Raw H2 and Raw Ethanol every second.

    Example 3 - Humidity

    This example demonstrates how to pass humidity data from an external sensor (in this case, the SparkFun Humidity Sensor Breakout - SHTC3 (Qwiic)) to modify the SGP30's humidity compensation with an actual absolute humidity value. Passing an actual humidity value to the SGP30's humidity compensation will help increase the accuracy and reliability of the sensor.

    In order to use this example as is you will need to also have the SparkFun SHTC3 Arduino Library installed. With both libraries installed, simply connect an SHTC3 Breakout to your Qwiic chain and upload the example to add a humidity compensation value to your SGP30's readings!

    SGP30 and SHTC3 Connected to RedBoard Qwiic

    This example initializes both sensors and, in the setup, takes a temperature and humidity reading from the SHTC3. The code then converts those readings to absolute humidity, parses that into a fixed 8.8 bit value the SGP30 can accept for humidity compensation and then sends that data to the SGP30 using the setHumidity function. After this value is set, the code runs through the primary routine of reading CO2 and TVOC values and printing them over serial.

    The value stored for the on-chip humidity compensation will remain static until a new value is sent or the SGP30 is reset. We have included an option to send the letter "H" (upper or lower case) through your serial monitor to adjust the humidity compensation value to a new reading from the SHTC3 to avoid having to reset the circuit.

    To update the compensation value, open the Serial Monitor at any time after initialization and set the baud to 9600. Type in "H", hit enter and the code will reset the humidity compensation value using an updated reading from the SHTC3. The code will also print out the new value in g/m3 and then resume taking CO2 and TVOC readings from the SGP30. The code below shows that if statement and how the humidity value is calculated from the SHTC3's temperature and humidity data:

    language:c
    if (Serial.available())
    {
    char ch = Serial.read();
    if (ch == 'H' || ch == 'h')
    {
      SHTC3_Status_TypeDef result = hSensor.update();
      delay(190);  
      // Measure Relative Humidity from the Si7021
      float humidity = hSensor.toPercent();
    
      //Measure temperature (in C) from the Si7021
      float temperature = hSensor.toDegC();
    
      //Convert relative humidity to absolute humidity
      double absHumidity = RHtoAbsolute(humidity, temperature);
    
      //Convert the double type humidity to a fixed point 8.8bit number
      uint16_t sensHumidity = doubleToFixedPoint(absHumidity);
    
      //Set the humidity compensation on the SGP30 to the measured value
      //If no humidity sensor attached, sensHumidity should be 0 and sensor will use default
      mySensor.setHumidity(sensHumidity);
      Serial.print("Absolute Humidity compensation value set to: ");
      Serial.print(absHumidity);
      Serial.println("g/m^3 ");
      delay(100);
    

    Resources and Going Further

    That's all for this guide. Hopefully after reading this and following along with the Arduino examples you are ready to integrate your SparkFun Air Quality Sensor -SGP30 (Qwiic) into your next air quality monitoring project!

    For more information, take a look at the resources below:

    Looking to add more sensors to your indoor air quality project or simply want more weather and environmental-related tutorials? Check these out:

    Blynk Board Project Guide

    A series of Blynk projects you can set up on the Blynk Board without ever re-programming it.

    TMP102 Digital Temperature Sensor Hookup Guide

    How to connect and use the SparkFun Digital Temperature Sensor Breakout - TMP102 with an Arduino.

    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.

    SparkFun gator:particle Hookup Guide

    The gator:particle is an I2C heart-rate monitor and pulse oximeter that can be used as a particle sensor. This tutorial will get you started using the gator:particle with the micro:bit platform.

    Not sure what type of air quality project you want to start? These blog posts might give you some inspiration:


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

    RFID Beginners Tutorial

    $
    0
    0

    RFID Beginners Tutorial a learn.sparkfun.com tutorial

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

    Introduction

    RFID is as magic as waving a card in front of a little black box and doors open for all to pass. This technology is so versatile that it was projected in 2017 to support a $31.42 billion market by 2023. We’ve enjoyed RFID tech as much as the next and we want to share it with you. In this tutorial we’ll touch on some key topics of the technology. Then we’ll work on making a remote work clock punch that can log time, location, and identification. Who knows, maybe you’ll find your own magic in RFID as well.

    Items we will be using in this tutorial.

    What Is RFID?

    In simple terms, RFID Technology is a method of wireless communication between two (or more) electrical components. There is a reader that can emit a signal and passively reads incoming signals. Tags are devices that contain identification or other information. They come in two types, passive or active. Active tags have their own power source to actively transmit their contained information. Passive tags are ‘powered’ through radiated signals from the reader to transmit unique information. Either way it boils down to two devices yelling at each other like two cranky people. This transmission is how we’ll pass this information to our microcontroller to log our "in’s and out’s".

    Suggested Reading

    Before going further, brave adventurer, please feel free to brush up on other tutorials and content that will help you on your journey.

    GPS Basics

    The Global Positioning System (GPS) is an engineering marvel that we all have access to for a relatively low cost and no subscription fee. With the correct hardware and minimal effort, you can determine your position and time almost anywhere on the globe.

    I2C

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

    Serial Terminal Basics

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

    RFID Basics

    Dive into the basics of Radio Frequency Identification (RFID) technology.

    SparkFun Qwiic RFID-IDXXLA Hookup Guide

    The Qwiic RFID ID-XXLA is an I2C solution that pairs with the ID-LA modules: ID-3LA, the ID-12LA, or the ID-20LA, and utilizes 125kHz RFID chips. Let's take a look at the hardware used for this tutorial.

    SparkFun GPS Breakout (ZOE-M8Q and SAM-M8Q) Hookup Guide

    The SparkFun ZOE-M8Q and SAM-M8Q are two similarly powerful GPS units but with different project applications. We'll compare both chips before getting each up and running.

    Displaying Your Coordinates with a GPS Module

    This Arduino tutorial will teach you how to pinpoint and display your GPS coordinates with a press of a button using hardware from our Qwiic Connect System (I2C).

    Hookup Guide for the SparkFun RedBoard Artemis Nano

    Get started with the powerful RedBoard Artemis Nano
    Qwiic Connect System
    Qwiic Connect System

    Hardware Overview

    You can find the components needed for this tutorial below:

    Product Descriptions:

    SAM-M8Q - Chip Antenna

    "The SparkFun SAM-M8Q GPS Breakout is a high quality, GPS board with equally impressive configuration options. The SAM-M8Q is a 72-channel GNSS receiver, meaning it can receive signals from the GPS, GLONASS, and Galileo constellations. This increases precision and decreases lock time and thanks to the onboard rechargable battery, you'll have backup power enabling the GPS to get a hot lock within seconds!"

    Qwiic RFID Reader

    "The SparkFun RFID Qwiic Kit is a simple, yet all-in-one I2C based RFID starting point for the ID-3LA, ID-12LA, and ID-20LA readers. Simply plug a reader into the headers and use a Qwiic cable to connect to any Qwiic enabled development board, then scan your 125kHz ID tag and the unique 32-bit ID will be shown on the screen."

    Artemis Nano

    "With 1MB flash and 384k RAM you'll have plenty of room for your sketches. The Artemis module runs at 48MHz with a 96MHz turbo mode available and with Bluetooth to boot! The SparkFun Artemis Nano is an incredibly flexible device for a small footprint..."

    Hardware Hookup

    As far as the hardware is concerned, we’re going to lean hard on the Qwiic ecosystem. This ecosystem allows us to easily connect devices together without needing to solder. No mess, no fuss!

    SparkFun Artemis Nano, Qwiic RFID Reader and Qwiic GPS connected together.

    Software

    Note: This code/library has been written and tested on Arduino IDE version 1.8.12 . Otherwise, make sure you are using the latest stable 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.

    Our final code will be a mash up of two basic examples for our components. We’ll take a quick look at each part of the examples that we’ll use and talk about the main points.

    Qwiic RFID Reader

    The Qwiic RFID library will give you the full functionality of the Qwiic RFID ID-XXLA without the hub bub of the I²C data transactions. Also included are examples codes to demonstrate the full functionality of the library. You can click the link below to download the file directly and install it manually, or navigate through the Arduino Library Manager by searching SparkFun Qwiic RFID. You can also go the Github page and get download it from there.

    Qwiic RFID Reader connected to the SparkFun Artemis Nano

    In the Read_Tag_Basics example, the reader logs all tags that are recognized in a memory buffer. We read the buffer and clear it for a new read. We see that functionality below:

    language:c
    serialInput = Serial.read(); 
    if (serialInput == 49){   // "1" on your keyboard is 49 in ASCII
      tag = myRfid.getTag();
      Serial.print("Tag ID: ");
      Serial.print(tag);
      scanTime = myRfid.getPrecReqTime(); 
      // If this time is too precise try: 
      // long time = myRfid.getReqTime(); 
      Serial.print(" Scan Time: ");
      Serial.println(scanTime);
    }
    

    Serial.read(); reads the buffer into the micro-controller's memory and clears the reader's buffer for another swipe. The tag is printed in the serial output along with the scan time. What we need to take away from this is the Serial.read(); and myRfid.getTag();.

    SAM-M8Q GPS Module

    The SparkFun U-blox Arduino library can be downloaded with the Arduino library manager by searching 'SparkFun Ublox' or you can grab the zip here from the GitHub repository:

    SAM-M8Q GPS connected to the SparkFun Artemis Nano

    Using SparkFun’s u-blox Arduino Library and Example2_NMEAParsing.ino, we’ll get our GPS coordinates and time. If you look closely at the code below, you’ll notice that something is missing:

    language:c
    long latitude_mdeg = nmea.getLatitude();
    long longitude_mdeg = nmea.getLongitude();
    
    Serial.print("Latitude (deg): ");
    Serial.println(latitude_mdeg / 1000000., 6);
    Serial.print("Longitude (deg): ");
    Serial.println(longitude_mdeg / 1000000., 6);
    

    We’re missing functions to get time. However, if we look at the u-blox library header file we can see the following functions that we’ll add in to the final code similarly to how the latitude and longitude functions are called in the example:

    language:c
    uint16_t getYear(uint16_t maxWait = getPVTmaxWait);
    uint8_t getMonth(uint16_t maxWait = getPVTmaxWait);
    uint8_t getDay(uint16_t maxWait = getPVTmaxWait);
    uint8_t getHour(uint16_t maxWait = getPVTmaxWait);
    uint8_t getMinute(uint16_t maxWait = getPVTmaxWait);
    uint8_t getSecond(uint16_t maxWait = getPVTmaxWait);
    

    These functions will give us time. Now let's combine all our parts. The full code is below:

    language:c
    /******************************************************************************
    Remote Work Punch Clock
    brandon.williams@sparkfun.com
    May 6, 2019
    
    Description When a card is read then the GPS coordinates and time are read from
        the GPS module.
    
    Development environment specifics:
    Arduino IDE 1.8.12 (or most recent)
    
    Board Definition Packages (or most recent):
      SparkFun Apollo3 Boards           1.1.1
      MicroNMEA                         2.0.1
      SparkFun_Qwiic_Rfid.h             1.1.6
      SparkFun_Ublox_Arduino_Library    1.8.3
    ******************************************************************************/
    
    
    #include <MicroNMEA.h>
    
    #include <SparkFun_Qwiic_Rfid.h>
    
    #include <SparkFun_Ublox_Arduino_Library.h>
    
    
    #define RFID_ADDR 0x7D // Default Qwiic RFID I2C address
    
    // Variables and Constants
          /*GPS*/
    SFE_UBLOX_GPS myGPS;
    char nmeaBuffer[100];
    MicroNMEA nmea(nmeaBuffer, sizeof(nmeaBuffer));
          /*RFID*/
    Qwiic_Rfid myRFID(RFID_ADDR);
    String tag;
    float scanTime;
    int serialInput;
    
    void setup() {
    
      Wire.begin();
      //Disable Serial after confirming setup works
      Serial.begin(115200);
    
      /*Qwiic RFID begin*/
      if(myRFID.begin()== false){
        Serial.println("Could not communicate with Qwiic RFID!");
        while(1);
      }
    
    }
    
    void loop() {
    
      /*RFID loop code*/
      tag = myRFID.getTag();
    
      /* Empty string is returned if no tag is present,
       * wait till a valid ID string is returned.
       */
        if(myGPS.begin() != false){
          if(tag.length() != 6){
            Serial.print("Tag ID: ");
            Serial.println(tag);
    
            /*GPS loop code*/
            myGPS.checkUblox(); //See if new data is available. Process bytes as they come in.
    
            if(nmea.isValid() == true){
              if(nmea.getNumSatellites() != 0){
                long latitude_mdeg = nmea.getLatitude();
                long longitude_mdeg = nmea.getLongitude();
                uint16_t dateYear =  nmea.getYear();
                uint8_t dateMonth = nmea.getMonth();
                uint8_t dateDay = nmea.getDay();
                uint8_t dateHour = nmea.getHour();
                uint8_t dateMin = nmea.getMinute();
                uint8_t dateSec = nmea.getSecond();
    
                //Print Coordinates
                Serial.print("Latitude (deg): ");
                Serial.println(latitude_mdeg / 1000000., 6);
                Serial.print("Longitude (deg): ");
                Serial.println(longitude_mdeg / 1000000., 6);
    
                //Print Time
                Serial.print("Date and Time: ");
                Serial.print(dateMonth);
                Serial.print("-");
                Serial.print(dateDay);
                Serial.print("-");
                Serial.print(dateYear);
                Serial.print(" @ ");
                Serial.print(dateHour);
                Serial.print(":");
                Serial.print(dateMin);
                Serial.print(":");
                Serial.println(dateSec);
              }
            }
            else{
              Serial.print("No Fix - ");
              Serial.print("Num. satellites: ");
              Serial.println(nmea.getNumSatellites());
            }
          }
          delay(500);
        }
    }
    
    //This function gets called from the SparkFun Ublox Arduino Library
    //As each NMEA character comes in you can specify what to do with it
    //Useful for passing to other libraries like tinyGPS, MicroNMEA, or even
    //a buffer, radio, etc.
    void SFE_UBLOX_GPS::processNMEA(char incoming)
    {
      //Take the incoming char from the Ublox I2C port and pass it on to the MicroNMEA lib
      //for sentence cracking
      nmea.process(incoming);
    }
    

    When we swipe a card over the scanner then we should get something like below:

    alt text

    Troubleshooting

    Resources and Going Further

    This tutorial is just a first step into making a larger RFID project. Stay tuned for a more advanced tutorial to expand beyond just reading data in a serial monitor.

    In the meantime, please feel free to visit more RFID tutorials and learn new skils:

    SparkFun RFID Starter Kit Hookup Guide

    Learn the basics of how to get started with the SparkFun RFID Starter Kit.

    Simultaneous RFID Tag Reader Hookup Guide

    A basic guide to getting started with the RFID Tag Reader breakout and how to read and write multiple RFID tags over multiple feet!

    SparkFun Qwiic RFID-IDXXLA Hookup Guide

    The Qwiic RFID ID-XXLA is an I2C solution that pairs with the ID-LA modules: ID-3LA, the ID-12LA, or the ID-20LA, and utilizes 125kHz RFID chips. Let's take a look at the hardware used for this tutorial.
    New!

    RFID Beginners Tutorial

    In this tutorial we'll revisit some RFID basics and practice by making a remote work logger using an RFID reader and a GPS module. You'll scan a card and get ID, location, and time. All the perfect data to punch in and punch out from the middle of Nowhere!

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

    How to Make a Magic Mirror with Raspberry Pi

    $
    0
    0

    How to Make a Magic Mirror with Raspberry Pi a learn.sparkfun.com tutorial

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

    Introduction

    If you follow the SparkFun Blog, you may have seen my post about my attempts to keep up with my family's ever changing schedule. With schooling and summer camps going online and both myself and my partner working from home... there's just too many virtual meetings to keep up with. An offhand comment about needing a "battle station" led to the Magic Mirror project.

    Magic Mirror

    This tutorial presumes you have some basic familiarity with Unix systems and commands. It's not required, but is certainly helpful. Let's dive in and see how to set this up, shall we?

    Required Materials

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

    You May Also Need

    If you prefer a larger, wall mounted Magic Mirror (like the one in this tutorial), you will need to find the following:

    Suggested Reading

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

    Headless Raspberry Pi Setup

    Configure a Raspberry Pi without a keyboard, mouse, or monitor.

    Setting up a Raspberry Pi 3 as an Access Point

    This guide will show you how to configure a Raspberry Pi as an access point and connect it to your local Ethernet network to share Internet to other WiFi devices.

    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.

    Raspberry Pi 4 Kit Hookup Guide

    Guide for hooking up your Raspberry Pi 4 Model B basic or desktop kit together.

    Hardware Hookup

    If you haven't read through the Raspberry Pi 4 Kit Hookup Guide, head on over there now to get yourself set up.

    Raspberry Pi 4 Kit Hookup Guide

    March 14, 2020

    Guide for hooking up your Raspberry Pi 4 Model B basic or desktop kit together.

    Installing Magic Mirror

    If you've followed along with the Raspberry Pi 4 Kit Hookup Guide, you should have a functioning Raspberry Pi desktop in front of you. Now we can move on to the "magic"!

    Installing Magic Mirror

    The basic installation is relatively straight forward. We'll run through the steps here, but you can also head over to the Magic Mirror Installation & Usage tutorial and follow their steps.

    Install NodeSource

    We first need to install NodeSource. Open a terminal window on your Raspberry Pi desktop. Then copy and paste the following code:

    language:shell
    curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
    

    If all goes well, you should see something like the following:

    Step1_-_Installing NodeSource

    Click the image for a closer look.

    Install NodeJS

    The next thing we need is NodeJS. Copy and paste the code below into your terminal window:

    language:shell
    sudo apt install -y nodejs
    

    Step2_-_Installing NodeJS

    Installing NodeJS....

    Step2_-_Installing NodeJS In Progress

    Clone the MagicMirror GitHub Repo

    Now we get to the good part! Let's clone the MagicMirror GitHub repo to our Raspberry Pi. Copy and paste this code to your terminal and watch the GitHub clone magic happen....

    language:shell
    git clone https://github.com/MichMich/MagicMirror
    

    Step3-Cloning the Git Repo

    Away we go!

    Step3-Cloning the Git Repo Complete

    Install Magic Mirror

    We're close! Go ahead and cd (change dir) into the MagicMirror directory:

    language:shell
    cd MagicMirror
    

    And then we type in the following:

    language:shell
    npm install
    

    Step4-Install Magic Mirror

    Copy the Sample Config File

    So close! Let's copy the sample config file into one we can play around with:

    language:shell
    cp config/config.js.sample config/config.js
    

    Step5-Copy Config Sample

    Run the Sample Config

    Okay! Let's make this magic!

    language:shell
    npm start
    

    Default Magic Mirror



    config.js

    This file is essentially the brains of the operation. This is where you layout how you want your Magic Mirror to look. You can add modules, delete modules, move modules, and customize to your heart's content.

    Navigate to your /home/pi/MagicMirror/config directory and open up config.js in Geany (right click and select Geany).

    We're going to skip over most of the setup code. That said, let's look at one little bit here - scroll down until you see the outlined bit below:

    Outlined settings for language, time format, and units

    Click the image for a closer look.

    Outlined in the image are the following settings:

    • language: defaults to english, but can be set to nl, ru, fr, etc
    • timeFormat: defaults to 24. Change this to 12 if you prefer.
    • units: metric or imperial? the battle rages on... (I prefer metric)

    Scroll a little further down and you'll find the modules section:

    modules section of config.js

    Click the image for a closer look.

    Hopefully, this section is also fairly straight forward. You'll notice that for each module:, you'll need the position: you'd like it to be on the screen. Possible values are:

    • top_bar
    • top_left
    • top_center
    • top_right
    • upper_third
    • middle_center
    • lower_third
    • bottom_left
    • bottom_center
    • bottom_right
    • bottom_bar
    • fullscreen_above
    • fullscreen_below

    If you put multiple modules in the same position, they will be shown in the order they are listed in the config file.

    Moving the Clock

    Remember the initial Magic Mirror image above?

    Default Magic Mirror screen

    Let's move that clock from the top left to the top right!

    Find the following in your config file:

    Clock module in the config file - top left

    Click the image for a closer look.

    Change top_left to top_right:

    Clock module in the config file - top right

    Click the image for a closer look.

    Save the config file, go back to your terminal window, and start up Magic Mirror (npm start) aaaaaaand...

    Magic Mirror with the clock at top right

    VOILA! Easy peasy, right? Each module has its own default requirements and in the default config.js file, these requirements are set up for us. We'll look at some more customization in subsequent sections.

    Customizing The Modules - Compliments

    Sooo... one of the first compliments that popped up on my brand new magic mirror was "Hey there sexy!". Not sure about y'all but that made me slightly uncomfortable. Especially when my kids started repeating it to random strangers walking by. No bueno. Let's start by looking at the Compliments module and editing those compliments to be a bit more to our (my) liking.

    CD to your MagicMirror/modules/default/compliments directory on the Pi. Open up compliments.js in either Geany or your text editor of choice. You should see something like the following:

    Default compliments

    Click the image for a closer look.

    See all those weird compliments in there? Yeah. Let's change those. This file is pretty straight forward javascript - you can go ahead and change the text of those compliments; just make sure you leave the syntax intact. This is looking better....

    Updated compliments

    Click the image for a closer look.

    Save your file and head on back to the terminal window. Make sure you are in your MagicMirror folder and type in npm start. Voila!

    Go Get em Captain Tightpants

    No Power In The Verse Can Stop You

    Feelin' pretty shiny right about now.



    Customizing The Modules - Using Your Google Calendar

    One of the primary reasons I wanted a Magic Mirror was to keep track of everyone's calendars. Let's change our calendar module to reflect our Google calendars instead of holidays.

    In config.js, navigate to the calendar module.

    Highlight of calendar module

    Click the image for a larger view.

    See where it says url? That's what you'll need to change. You may want to change the header as well.

    Finding Your Calendar Link

    From your google calendar, navigate to the Settings and Sharing option on the calendar you want to use. Click on the three little dots next to the calendar to get to the link!

    Google Calendar Settings and Sharing Link Location

    Click on that link! Once you're in Settings and Sharing, scroll down until you see the following:

    Google Calendar iCal addresses

    Click the image for a closer look.

    You'll notice that there is a Public Address and a Secret Address. If your calendar is public, go ahead and use that address. However, if you want to keep your calendar private to the world at large, go ahead and use the secret address in iCal format. Copy that link!

    Now head on back to the config.js file and paste that iCal link (secret or public) into the url location.

    Save your config.js file, head back to the terminal window, and type in npm start to see your changes in the Magic Mirror!

    There are plenty of third party modules that can customize the look of your calendars. Take a peek here. Almost all of the modules have their requirements either listed out or an example is shown. Give it a try!



    Customizing The Modules - Adding New Modules

    Now that we have THAT out of the way, let's look at other modules we can edit or add.

    By default, the Magic Mirror comes with the following modules:

    • Alert
    • Calendar
    • Clock
    • Compliments
    • Current Weather
    • Hello World
    • News Feed
    • Update Notification
    • Weather Module
    • Weather Forecast

    The default config.js file that we copied in the Installing Magic Mirror section has the basics set up for us. But what if we want more? Well, we're in luck. There's a whole ecosystem of third party modules you can add into your Magic Mirror.

    Word of the Day

    Let's do something simple - let's add the Word of the Day.

    Start by opening a terminal window on your Raspberry Pi and navigating to your MagicMirror's modules folder. If you are using the default installation directory, use the command:

    language:shell
    cd ~/MagicMirror/modules
    

    Clone the module:

    language:shell
    git clone https://github.com/bittiez/MMM-MWWordOfTheDay.git
    

    You should see something along the lines of the following:

    git clone word of the day module

    Once you have the module code, head back to your config.js file and add the following:

    language:javascript
    module: 'MMM-MWWordOfTheDay',
        position: 'top_right',
        config: {
            updateInterval: 120000,
            headerText: "Word of the day"
    }
    

    Adding word of the day module to config.js

    Click the image for a closer look.

    Save and quit! From your terminal, type npm start and you'll see your word of the day in the upper right hand corner!

    Magic Mirror with Word of the Day



    Finishing Touches

    There are so many options when making the box and the mirror. Googling "Magic Mirror Frame" is a little bonkers. I went with a shadow box I got on sale from Michaels, and some outdoor reflective film I bought from Amazon. I also had to get some right angle HDMI adapters so that the cable would lay somewhat flat and fit into the frame.

    Magic Mirror Main view

    Since the frame was bigger than the screen, I had to do some finagling to get the screen to fit where I wanted it to.

    Mounting the screen in the frame

    Making It Better

    The Raspberry Pi 4 runs hot enough that I bought the Heatsink Case. I still needed to drill a few extra holes on the top of the mirror frame to provide enough ventilation but it's worth it to have the possibility of future expansion.

    When time permits, I'll likely add a safe reboot and shutdown button with the Qwiic PHat like Bobby does here:

    Raspberry Pi Safe Reboot and Shutdown Button

    April 20, 2020

    Safely reboot or shutdown your Raspberry Pi to avoid corrupting the microSD card using the built-in general purpose button on the Qwiic pHAT v2.0!

    I may also use the Qwiic PHat to extend the Qwiic ecosystem. It'd be nice to add a proximity sensor such that it's not just on all the time. As you can see in the images above, I've already used css to customize our calendars and added Google Tasks in. Super handy to know what you need to do each day!

    Troubleshooting

    The MagicMirror project has a wonderful forum of users ready and willing to help out! I have popped over there a few times to sort out some CSS configuration questions myself.

    Common Errors

    • Please create a config file: If you've made changes to your config file and get this error, there is likely a syntax error in your file. If you are just starting out, you need to copy the config.js.sample to config.js.

    • npm fails to start: Get errors when you type in npm start? Likely you're not in the MagicMirror folder. Make sure you're in the correct directory and try again.

    • Module not working: Make sure that when you install modules, you are in the MagicMirror/modules folder. The project assumes your modules will be installed here and if they are not, the config file can't find them.

    Resources and Going Further

    So now you have a delightful command center. What will you do next? How will you customize your daily routine?

    You can also check out some of our other great Raspberry Pi Tutorials here:

    Getting Started with the BrickPi

    How to connect Lego Mindstorms to the Raspberry Pi using the BrickPi.

    Raspberry Pi 3 Starter Kit Hookup Guide

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

    Introduction to MQTT

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

    Qwiic Atmospheric Sensor (BME280) Hookup Guide

    Measure temperature, humidity, barometric pressure with the SparkFun Atmospheric Sensor Breakout BME280 (Qwiic).

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

    Working with Qwiic on a Jetson Nano through Jupyter Notebooks

    $
    0
    0

    Working with Qwiic on a Jetson Nano through Jupyter Notebooks a learn.sparkfun.com tutorial

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

    Introduction

    Let’s face it... SSH or VNC can be frustrating and a barrier to entry at times for people looking to get started with remote computing. Luckily, services like Project Jupyter help make remote computing a little more accessible. Jupyter Notebooks have been around for a while and a number of people use them for a variety of applications; from data visualization to teaching and learning computer science.

    https://raw.githubusercontent.com/jupyter/design/master/logos/Rectangle%20Logo/rectanglelogo-greytext-orangebody-greymoons/rectanglelogo-greytext-orangebody-greymoons.png

    In a nutshell you can think of Jupyter Notebooks as an IDE and documentation repository in one platform that is accessible remotely through a web browser. Jupyter then grants access to the file directories of the host computer, a terminal to run Linux commands to install software on it as well as run required commands and processes. The “Notebooks” are files where you can create interactive Python scripts through intermixing markdown documentation with code so that your Notebook is both a “Notebook” and the program you end up running. Common applications for Jupyter Notebooks include building data visualization displays or GUI interfaces.

    Jupyter Notebooks are accessed through a web browser interface. From a client computer on the same network you can access the Notebooks and edit, run and/or modify the Python scripts that are hosted as well as create new ones. This makes working with a single board computer much easier and cleaner in terms of required hardware peripherals, but it also lowers the barrier of entry in terms of those who are new to the topic and feel overwhelmed.

    Jupyter Notebooks for SparkFun Qwiic on the Jetson Nano

    A great example of using Jupyter Notebooks as both a development and a learning platform is the NVIDIA Jetson Nano.

    We carry two kits: the DLI Course Kit and JetBot AI Kit that can use Jupyter Notebooks as a way to deliver tutorial content to get users up and running easily as well as empower them to go further with those products. Jupyter Notebooks are especially helpful with topics and projects that can be mentally taxing and hard to understand such as Machine Learning and Computer Vision.

    SparkFun DLI Kit for Jetson Nano

    SparkFun DLI Kit for Jetson Nano

    KIT-16308
    $174.95
    1
    SparkFun JetBot AI Kit v2.1 Powered by Jetson Nano

    SparkFun JetBot AI Kit v2.1 Powered by Jetson Nano

    KIT-16417
    $249.95
    2

    This tutorial covers a set of Jupyter Notebooks that we created for our Python supported Qwiic boards and their use with the NVIDIA Jetson Nano!

    With Python support for the ever growing catalog of SparkFun Qwiic boards we thought that a Jupyter Notebook collection built around using our Qwiic boards with the NVIDIA Jetson Nano would be a good idea. We have created eight different notebooks that give you a “Hello World” example for each of the currently supported boards. Each Notebook breaks down the Python script into manageable chunks giving explanation and context to what is happening and in the end we get you enough knowledge to be dangerous!

    alt text

    When you feel comfortable and want to dig into creating your own Python scripts for a project, you can create your own Notebook and execute the code right from Jupyter Notebooks. You can even try your hand at integrating some of the sensors into a Machine Learning project as all of the Qwiic libraries will be installed on your Jetson Nano!

    This tutorial will get you up and running on an NVIDIA Jetson Nano and Jupyter Notebooks using SparkFun Qwiic Boards!

    Hardware Overview and Assembly

    We will obviously need an NVIDIA Jetson Nano (we recommend starting with the DLI Course Kit) as well as some Qwiic hardware. We recommend starting with the SparkFun Qwiic Kit for Raspberry Pi but we have Python packages for many Qwiic boards. The most up to date list of Python-supported Qwiic boards can be found in the Qwiic Py GitHub Repository.


    qwiic kit

    Hooking up your Qwiic kit to the NVIDIA Jetson Nano is straight forward. The kit comes with our Qwiic pHAT which plugs in to the Jetson Nano via the 2x20 GPIO header.


    Qwiic pHAT connected to the Jetson Nano

    The orientation of the pHAT is very important here. It should hang off the Jetson Nano Developer Kit carrier board and not over the top of the heat sync. Think “spoiler” for your Jetson Nano and you will get it!

    Once the pHAT is in place we can now add the distance sensor and environmental combo board as well as the micro OLED display using the Qwiic cables included in the kit.


    Qwiic breakouts connected to the pHAT on the Nano

    You can configure your hookup of the Qwiic boards in any combination you like as long as you have both boards connected to the pHAT. Personally, I like to daisy chain them together but you can go with the flavor that suits you and your needs.

    Software Setup and Installation

    Once you have everything connected to the pHAT, it is now time to get the Python libraries and Jupyter Notebooks installed.

    This tutorial assumes you have already gone through the process of burning an OS image to a microSD card, ran initial setup and have your Nano connected to the internet either through Ethernet or WiFi. If you are just opening the box at this point take a moment to set your board up by going through the following tutorials:

    Note: We will be working from a DLI Course image with network connection already setup. If you are looking for a shortcut, using our JetBot Image with your Jetson Nano will get you the drivers for the Edimax USB adapter and Qwiic Python libraries installed for you!

    Navigating to Jupyter Notebooks

    To access Jupyter Notebooks on your Jetson Nano you will need to know its IP address. There are a number of ways to find it. The most straightforward way is to hook the Jetson Nano up to a monitor and keyboard, open a terminal and type the following:

    ifconfig[Enter]

    This command will list off all of your network connections and the IP address for that connection. If you have followed the instructions for the WiFi setup tutorial linked above we will assume you know your IP address and have your Jetson Nano connected to your network.

    Open a browser window and type the following in the address bar: http://[IP ADDRESS]:8888 with [IP ADDRESS] being your Jetson Nanos IP Address.

    The first time you connect it may take a bit of time for Jupyter Notebooks to load, but you should be greeted by a loading page and then a sign-in page asking for a password. The password for the DLI image is dlinano and the password for the Jetbot image is jetbot.


    Screenshot showing Jupyter Notebook Launcher

    Once you are logged into Jupyter Notebooks you will need to open a new terminal window to download the Jupyter Notebooks for the Qwiic Boards as well as install the Qwiic Python libraries.


    Terminal opened and command to download Qwiic Jupyter entered
    Having trouble seeing details in the image? Click on it for a larger view!

    Once you open the terminal window from the Launcher window, navigate to the DLI-Nano Notebooks directory by typing the following command:

    cd nvdli-nano[Enter]

    You can then download the SparkFun Qwiic Jupyter Notebooks from GitHub with the following command:

    sudo git clone https://github.com/d1runberg/qwiic-jupyter-nb.git[Enter]

    This command will download a folder with the contents of our Jupyter Notebooks as well as the assets required to display images, etc. You should now be able to see the SparkFun Qwiic Notebooks directory in the directory tree on the left side of Jupyter Notebooks!

    Once the SparkFun Qwiic Notebooks downloads you need to install the Qwiic Python libraries before digging in and using them.

    Installing Qwiic Libraries

    With the terminal window in Jupyter Notebooks still opened you can install the SparkFun Qwiic Python libraries through pip by typing the following command:

    sudo pip3 install sparkfun-qwiic[Enter]

    This will install the entire Qwiic Py package with libraries for the Qwiic boards that are supported in Python.


    alt text

    Once the installation is complete, you should be good to go and can close the terminal window.

    Running an Example in Jupyter Notebooks

    With our Qwiic boards connected to the Jetson Nano we have two different options of Notebooks to choose from! For the sake of simplicity I chose the OLED notebook to walk you through, but once you run the first Notebook the other will be simple enough to run as well. Open the SparkFun Qwiic Notebooks directory by double clicking on it. Find the OLED.ipynb notebook file and open it by double clicking it as well.


    Screenshot of SparkFun Qwiic OLED Notebook

    Notebooks work in Jupyter Notebooks by running your code in a kernel which you need to start and stop. It is a good habit to make sure that you are not running other Notebook kernels before starting one. To check if any kernels are running select the small running man icon on the far left toolbar. Any kernels that are running will be listed here and you can click “SHUTDOWN” to close any that are open.


    Screenshot showing SHUTDOWN for Jupyter Notebooks

    To run the OLED Notebook we need to specify what type of kernel we want to run it as. In the upper right hand corner there is a small text box next to a circle. It should say “Python 3”, but if it says “No Kernel” click on it and select Python 3 from the options provided. We can now run the python code in the Notebook!


    Screenshot showing selecting the Kernel

    Next, interact with the Notebook by clicking on the first cell which is the product description for the OLED and then click the "Play" button in the top menu bar. This play button steps you through each cell (either text or code) and moves you to the next one.


    Screenshot showing the Play button

    You may notice that each cell has a box next to it. For code cells there will be an ‘*’ in that box while the code is executing and when it completes its execution the asterisk will turn to a number. So, you can follow through the Notebook by clicking the Play button as code executes combined with reading the explanation through the tutorial text.

    In the end your OLED should display some text on it.


    The OLED displaying text

    The code cells in the Notebook are interactive and you can make changes. So changing the string that the display changes is as simple as double clicking on that code cell and changing the string to your name for example. You then need to reselect the code cell and re-run it.

    Resources and Going Further

    With that you have installed our Jupyter Notebooks for our Qwiic boards that are currently supported in Python. With these examples at your fingertips, explore different boards and use them with your Jetson Nano and even take a crack at integrating the OLED or the distance sensor with any of the other Notebook examples for the Jetson Nano. I tried my hand at creating a small widget to accept text in small text box and then send that to the OLED display! Check it out... In your Notebooks it is called button_oled.ipybb


    Screenshot of button_oled Notebook

    If you aren't up to tackling something around Machine Learning yet, check out the different widgets from the Jupyter Notebook Python libraries. These widgets are a simple way to create GUI dashboards and graphic displays for your Qwiic Boards! You can find more on the widget API here.

    For more information and resources about the NVIDIA Jetson Nano and Project Jupyter, check out the links below:


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

    SparkFun Photodetector (MAX30101) Hookup Guide

    $
    0
    0

    SparkFun Photodetector (MAX30101) Hookup Guide a learn.sparkfun.com tutorial

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

    Introduction

    The SparkFun Photodetector - MAX30101 (Qwiic) is the successor to the MAX30105 particle sensor, a highly sensitive optical sensor. This tutorial will get you up and running to retrieve the raw data from the MAX30101 sensor.

    SparkFun Photodetector Breakout - MAX30101 (Qwiic)

    SparkFun Photodetector Breakout - MAX30101 (Qwiic)

    SEN-16474
    $19.95

    The MAX30101 includes three LEDs and an optical detector in a single package, which can be utilized as a wearable, biosensor for pulse oximeter and heart-rate measurements. For accurate and reliable biometric readings, we recommend the SparkFun Pulse Oximeter and Heart Rate Sensor, which utilizes proprietary algorithms programmed on the MAX32664 Biometric Sensor Hub. Other possible applications include proximity sensing and particle detection by measuring the changes in light that is reflected back from the LEDs.

    Required Materials

    The Qwiic Photodetector Sensor does need a few additional items for you to get started. The RedBoard Qwiic will be used for the Arduino examples. A single board computer and the Qwiic pHAT are required for the Python examples (see note below). You may already have a few of these items, including the required Qwiic cable, so feel free to modify your cart based on your needs. Additionally, there are also options that are available as well (click button below to toggle options).

    SparkFun Qwiic Cable Kit

    SparkFun Qwiic Cable Kit

    KIT-15081
    $7.95
    5
    SparkFun RedBoard Qwiic

    SparkFun RedBoard Qwiic

    DEV-15123
    $19.95
    5
    USB micro-B Cable - 6 Foot

    USB micro-B Cable - 6 Foot

    CAB-10215
    $4.95
    13
    SparkFun Qwiic pHAT v2.0 for Raspberry Pi

    SparkFun Qwiic pHAT v2.0 for Raspberry Pi

    DEV-15945
    $5.95
    Qwiic Compatible Microcontrollers:
    SparkFun RedBoard Qwiic

    SparkFun RedBoard Qwiic

    DEV-15123
    $19.95
    5
    SparkFun Thing Plus - SAMD51

    SparkFun Thing Plus - SAMD51

    DEV-14713
    $19.95
    1
    SparkFun RedBoard Turbo - SAMD21 Development Board

    SparkFun RedBoard Turbo - SAMD21 Development Board

    DEV-14812
    $24.95
    3
    SparkFun Thing Plus - ESP32 WROOM

    SparkFun Thing Plus - ESP32 WROOM

    WRL-14689
    7Retired
    In addition we also offer, Qwiic compatible stackable shields for microcontrollers and pHATs for single board computers (like the Raspberry Pi boards) that don't include a Qwiic connector.
    SparkFun Qwiic Shield for Arduino

    SparkFun Qwiic Shield for Arduino

    DEV-14352
    $6.95
    2
    SparkFun Qwiic Adapter

    SparkFun Qwiic Adapter

    DEV-14495
    $1.50
    1
    SparkFun Qwiic Shield for Thing Plus

    SparkFun Qwiic Shield for Thing Plus

    DEV-16138
    $3.50
    SparkFun Qwiic Shield for Arduino Nano

    SparkFun Qwiic Shield for Arduino Nano

    DEV-16130
    $3.50
    SparkFun Auto pHAT for Raspberry Pi

    SparkFun Auto pHAT for Raspberry Pi

    ROB-16328
    $29.95
    SparkFun Top pHAT for Raspberry Pi

    SparkFun Top pHAT for Raspberry Pi

    DEV-16301
    $49.95
    SparkFun Qwiic HAT for Raspberry Pi

    SparkFun Qwiic HAT for Raspberry Pi

    DEV-14459
    $5.95
    3
    SparkFun Qwiic pHAT v2.0 for Raspberry Pi

    SparkFun Qwiic pHAT v2.0 for Raspberry Pi

    DEV-15945
    $5.95
    SparkFun Servo pHAT for Raspberry Pi

    SparkFun Servo pHAT for Raspberry Pi

    DEV-15316
    $10.95
    1
    SparkFun Qwiic SHIM for Raspberry Pi

    SparkFun Qwiic SHIM for Raspberry Pi

    DEV-15794
    $0.95
    1
    SparkFun Qwiic pHAT for Raspberry Pi

    SparkFun Qwiic pHAT for Raspberry Pi

    DEV-15351
    $5.95
    You will also need a Qwiic cable to connect to your MAX30101 (Qwiic), choose a length that suits your needs.
    Qwiic Cable - 100mm

    Qwiic Cable - 100mm

    PRT-14427
    $1.50
    Qwiic Cable - 500mm

    Qwiic Cable - 500mm

    PRT-14429
    $1.95
    1
    Qwiic Cable - 200mm

    Qwiic Cable - 200mm

    PRT-14428
    $1.50
    Qwiic Cable - 50mm

    Qwiic Cable - 50mm

    PRT-14426
    $0.95

    Python Example: If you don't already have them, you will need an SBC (single board computer) such as a Raspberry Pi and standard peripherals or Jetson Nano and standard peripherals. An example setup is listed below.
    Raspberry Pi 3 B+

    Raspberry Pi 3 B+

    DEV-14643
    $39.95
    31
    NVIDIA Jetson Nano Developer Kit (V3)

    NVIDIA Jetson Nano Developer Kit (V3)

    DEV-16271
    $99.00
    8
    SparkFun DLI Kit (without Jetson Nano)

    SparkFun DLI Kit (without Jetson Nano)

    KIT-16389
    $74.95
    SparkFun Noobs Card for Raspberry Pi (16GB)

    SparkFun Noobs Card for Raspberry Pi (16GB)

    COM-15052
    $19.95
    Multimedia Wireless Keyboard

    Multimedia Wireless Keyboard

    WIG-14271
    $29.95
    3
    pi-topCEED (Green)

    pi-topCEED (Green)

    KIT-14035
    $114.95
    4

    Rubber Band

    Note: For the heart beat plotter examples, users will require a small to medium size rubber band.

    rubber band in use
    rubber band

    Suggested Reading

    If you're unfamiliar with serial terminals, jumper pads, or I2C be sure to checkout some of these foundational tutorials. The MAX30105 is designed for a handful of uses including Pulse Oximetry. If you're unfamiliar with optical pulse detection there are some very good application notes from TI and NXP that have great starter information.

    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.

    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.

    Serial Terminal Basics

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

    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!

    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.

    SparkFun Pulse Oximeter and Heart Rate Monitor Hookup Guide

    Find out your oxygen saturation level or check out your heart rate using the MAX30101 biometric sensor and MAX32664 Biometric Hub via I2C!

    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.

    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 pHAT for Raspberry Pi Hookup Guide

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

    Working with Qwiic on a Jetson Nano through Jupyter Notebooks

    We created a few Jupyter Notebooks to make using our Qwiic boards with your Jetson Nano even easier!

    Qwiic Connect System

    The Qwiic Photodetector utilizes the Qwiic connect system. We recommend familiarizing yourself with the Logic Levels and I2C tutorials (above) before using it. Click on the banner above to learn more about our Qwiic products.

    Note: First time Raspberry Pi users should also head over to the Raspberry Pi Foundation website and check out their quickstart guides:

    We have also listed a few additional resources for users to familiarize themselves with the Raspberry Pi:

    Hardware Overview

    Dimensions

    The Qwiic Photodetector Sensor is laid out on the standardized 1" x 1" (2.54 x 2.54 cm) Qwiic breakout board and includes the standard four 0.13" mounting holes, which are compatible with M3 screws.

    Board Dimensions
    Board layout. (Click to enlarge)

    Power LED

    There is a power status LED to help make sure that your Qwiic Photodetector Sensor is getting power. You can power the board either through the polarizedQwiic connector system or the breakout pins (3.3V and GND) provided. The Qwiic system is meant to run on 3.3V, be sure that you are NOT using another voltage when using the Qwiic system. A jumper is available on the back of the board to remove power to the LED for low-power applications (see Jumpers section below).

    Power LED
    Power LED. (Click to enlarge)

    MAX30101

    The MAX30101 includes three LEDs and an optical detector in a single package. Behind the window on the left, are red, green, and IR LEDs. While behind the window on the right, is a highly sensitive photon detector.

    Close up photo of the MAX30101 sensor
    Close up of the MAX30101 sensor. (Click to enlarge)

    The working principle of the sensor is that the optical detector measures the changes in the reflected light that was emitted from the LEDs. This is great for various application like detecting particles or for photoplethysmography.

    MAX30101 Sensor
    MAX30101 sensor. (Click to enlarge)

    (*For more details on the MAX30101, users can check out the datasheet.)

    Pin LabelDescription
    Power Supply Voltage: 1.7 - 2.0V
    Supply Cuurent: 0.6 - 1.1mA
    LED Driver:
    • Red/IR: 3.1-5V
    • Green: 4.5 - 5.5V
    ADCResolution: 18-bits (65536 Counts)
    LEDs
    Wavelength:
    • IR: 870 - 900nm
    • Red: 650 - 670nm
    • Green 530 - 545nm
    Power:
    • IR: 6.5mW
    • Red: 9.8mW
    • Green 17.2mW
    Photodetector Spectral Range: 640 - 980nm
    Temperature Sensor Range: -40 - 85°C
    Accuracy: &PlusMinus;1°C
    I2C Address0x57

    Application Notes

    Note: Particle detection, heart rate measurement, and photoplethysmography (for pulse oximetry) are applications of the MAX30101. These applications are detailed in the notes below; however, they require an understanding of the operating principles of the sensor and a conceptual knowledge of the application(s). Although, we provided the information below for interested users and may provide some examples of the application in our software; these applications are, unfortunately, not supported by SparkFun and the examples are primarily for demonstration purposes only.

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

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

    Maxim's Original Firmware for the MAX30102 adapted in our Arduino Library:

    Qwiic and I2C

    I2C Address

    The Qwiic Photodetector Sensor’s I2C address, 0x57, is factory set.

    Qwiic Connectors

    The simplest way to use the Qwiic Photodetector Sensor is through the Qwiic connect system. The connectors are polarized for the I2C connection and power. (*They are tied to the corresponding power and I2C breakout pins.)

    Qwiic connectors
    Qwiic connectors.

    Breakout Pins

    The board also provides six labeled breakout pins. You can connect these lines to the I2C bus of your microcontroller and power pins (3.3V and GND), if it doesn't have a Qwiic connector. The interrupt pin is also broken out to use for triggered events.

    Breakout Pins
    I2C Connections- The pins are tied to the Qwiic connectors.

    Interrupt Pin

    The interrupt pin (active low) is used to indicate various states of the MAX30101, depending on how it is configured and if it is enabled. The INT pin is pulled up with a 4.7kΩ resistor.

    Jumpers

    There are three jumpers on the board. Not sure how to cut a jumper? Read here!

    Power LED

    Cutting the LED jumper will remove the 1kΩ resistors and PWR LED from the 3.3V power. This is useful for low power applications

    power LED jumper
    Power LED jumper. (Click to enlarge)

    I2C Pull-Up

    Cutting the I2C jumper will remove the 2.2kΩ pull-up resistors from the I2C bus. If you have many devices on your I2C bus you may want to remove these jumpers. Be aware that these resistors are also part of the transistor logic level shifting circuit.

    I2C jumper
    I2C pull-up resistor jumper. (Click to enlarge)

    Interrupt Pull-up

    Cutting the INT jumper will remove the 4.7kΩ pull-up resistors from the interrupt pin.

    interrupt jumper
    Interrupt pull-up resistor jumper. (Click to enlarge)

    Hardware Assembly

    Arduino Examples

    With the Qwiic connector system, assembling the hardware is simple. All you need to do is connect your SparkFun Photodetector -MAX30101 (Qwiic) to the RedBoard Qwiic with a Qwiic cable. Otherwise, you can use the I2C pins of your microcontroller; just be aware of logic levels.

    Hardware assembly with RedBoard Qwiic
    RedBoard Qwiic connected the Qwiic Photodetector with a Qwiic cable.

    Note: This tutorial assumes users are familiar with Arduino products and are using the latest stable version of the Arduino IDE on your desktop. If this is your first time using the Arduino IDE, please review our tutorial on installing the Arduino IDE.

    Python Examples

    With the Qwiic connector system, assembling the hardware is simple. In addition to the SparkFun Photodetector -MAX30101 (Qwiic), you will need: a Qwiic cable, a SparkFun Qwiic pHAT for Raspberry Pi, single board computer, monitor, and standard peripherals. (*If you are unfamiliar with the Qwiic pHAT, you can find the Hookup Guide here.)

    There are two single board computer (SBC) options that we have tested on:

    Hardware assembly with Raspberry Pi 4 with Qwiic pHAT
    Raspberry Pi 4 (with heat sink case) connected the Qwiic Photodetector.
    Hardware assembly with Jetson Nano with Qwiic pHATJetson Nano connected the Qwiic Photodetector.

    Note: This tutorial assumes users are familiar with using a Raspberry Pi and have the latest version of Raspbian OS (full... with recommended software) your Raspberry Pi. You can download the latest version of the Raspbian OS from the Raspberry Pi Foundation website.

    If this is your first time using a Raspberry Pi, please head over to the Raspberry Pi Foundation website to use their quickstart guides. We have listed a few of them here:

    1. Setting up your Raspberry Pi
    2. Using your Raspberry Pi
    3. Documentation:
    4. Setup Documentation
      Installation Documentation
      Raspbian Documentation
      SD card Documentation

    Note: This tutorial assumes users are familiar with using a Jetson Nano and you have the latest version of L4T OS your Jetson Nano. You can download the latest version of the L4T OS from the Jetson Download Center on Nvidia's website.

    If this is your first time using a Jetson Nano, please head over to the Nvidia website to use their quickstart guides. We have listed a few of them here:

    1. Getting Started With Jetson Nano Developer Kit
    2. Jetson Nano Developer Kit User Guide
    3. Documentation:
    4. Jetson Nano Getting Started Guide
      Jetson Download Center
      Wiki: Jetson Nano
      Jetpack Software Documentation
      Nvidia Jetson Tutorials

    Heart Beat Plotter and Heart Rate Examples

    In both the Arduino and Python examples, there is are sample codes to demonstrate the MAX30101's biometric capability to detect a user's heart rate (or pulse). These are tricky examples to get working properly as the sensor can be finicky about the amount of pressure used along with the sensor's position on the finger.

    rubber band in use
    Using rubber band to attach MAX30101 sensor to a finger for Example 4 - Heart Beat Plotting in the Arduino examples.

    Here are a few tips for users that may help:

    • Relax in a comfortable position and keep you arm, hand, and finger as still as possible.
    • A consistent amount of pressure should be used for more reliable readings.
      • Tape or a rubber band are recommended. The engineer for this product had the most success using a rubber band in this configuration:

        top view of rubber band on boardbottom view of rubber band on board
        SparkFun Photodetector (MAX30101) with rubber band.
    • There is such a thing as too much pressure; use a fairly light amount of pressure. I found taping the board down, resting my arm on a table, and with just placing my finger's weight on the sensor worked fairly well for getting a consistent waveform.
    • The photodetector on the MAX30101 is highly sensitive and light passing from above the finger can also affect the sensor readings.
    • The sensor can be finicky for some users... and there isn't an easy way to troubleshoot this situation when you are getting poor readings. Keep trying. It took me 5 days of fiddling to get just the right combination of position and pressure for a proper reading. That being said, if you struggle that far, it will be a light bulb moment when you discover that combination and it becomes easier to repeat.
      • Try to get the plotter working first, with the blips/bumps as that is how the heart rate example calculates your pulse.

    Arduino Library

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

    (*Users can also check out the steps shown in the MAX30105 hookup guide. For the heart beat plotter example, the Arduino IDE must be version 1.6.6 or higher.)

    We've written a library to easily get setup and take readings from theSparkFun Photodetector -MAX30101 (Qwiic). However, before we jump into getting data from the sensor, let's take a closer look at the available functions in the library. You can install this library through the Arduino Library Manager. Search for SparkFun MAX3010X Arduino Library and you should be able to install the latest version. If you prefer manually downloading the libraries from the GitHub repository, you can grab them here:

    Let's get started by looking at the functions that set up the Qwiic Atmospheric Sensor:

    Class

    In the global scope, construct your sensor object (such as mySensor) without arguments.

    MAX30105 mySensor;

    Object Parameters and setup()

    Rather that passing a bunch of data to the constructor, configuration is accomplished by setting the values of the MAX30105 type in the setup() function. They are exposed by being public: so use the myName.aVariable = someValue; syntax.

    Settable variables of the class MAX30105:

    language:c
    // Status Registers
    uint8_t MAX30105_INTSTAT1 =     0x00;
    uint8_t MAX30105_INTSTAT2 =     0x01;
    uint8_t MAX30105_INTENABLE1 =       0x02;
    uint8_t MAX30105_INTENABLE2 =       0x03;
    
    // FIFO Registers
    uint8_t MAX30105_FIFOWRITEPTR =     0x04;
    uint8_t MAX30105_FIFOOVERFLOW =     0x05;
    uint8_t MAX30105_FIFOREADPTR =  0x06;
    uint8_t MAX30105_FIFODATA =     0x07;
    
    // Configuration Registers
    uint8_t MAX30105_FIFOCONFIG =       0x08;
    uint8_t MAX30105_MODECONFIG =       0x09;
    uint8_t MAX30105_PARTICLECONFIG =   0x0A;    // Note, sometimes listed as "SPO2" config in datasheet (pg. 11)
    uint8_t MAX30105_LED1_PULSEAMP =    0x0C;
    uint8_t MAX30105_LED2_PULSEAMP =    0x0D;
    uint8_t MAX30105_LED3_PULSEAMP =    0x0E;
    uint8_t MAX30105_LED_PROX_AMP =     0x10;
    uint8_t MAX30105_MULTILEDCONFIG1 = 0x11;
    uint8_t MAX30105_MULTILEDCONFIG2 = 0x12;
    
    // Die Temperature Registers
    uint8_t MAX30105_DIETEMPINT =       0x1F;
    uint8_t MAX30105_DIETEMPFRAC =  0x20;
    uint8_t MAX30105_DIETEMPCONFIG =    0x21;
    
    // Proximity Function Registers
    uint8_t MAX30105_PROXINTTHRESH =    0x30;
    
    // Part ID Registers
    uint8_t MAX30105_REVISIONID =       0xFE;
    uint8_t MAX30105_PARTID =           0xFF;    // Should always be 0x15. Identical to MAX30102.
    
    // MAX30105 Commands
    // Interrupt configuration (pg 13, 14)
    uint8_t MAX30105_INT_A_FULL_MASK =      (byte)~0b10000000;
    uint8_t MAX30105_INT_A_FULL_ENABLE =    0x80;
    uint8_t MAX30105_INT_A_FULL_DISABLE =   0x00;
    
    uint8_t MAX30105_INT_DATA_RDY_MASK = (byte)~0b01000000;
    uint8_t MAX30105_INT_DATA_RDY_ENABLE =  0x40;
    uint8_t MAX30105_INT_DATA_RDY_DISABLE = 0x00;
    
    uint8_t MAX30105_INT_ALC_OVF_MASK = (byte)~0b00100000;
    uint8_t MAX30105_INT_ALC_OVF_ENABLE =   0x20;
    uint8_t MAX30105_INT_ALC_OVF_DISABLE = 0x00;
    
    uint8_t MAX30105_INT_PROX_INT_MASK = (byte)~0b00010000;
    uint8_t MAX30105_INT_PROX_INT_ENABLE = 0x10;
    uint8_t MAX30105_INT_PROX_INT_DISABLE = 0x00;
    
    uint8_t MAX30105_INT_DIE_TEMP_RDY_MASK = (byte)~0b00000010;
    uint8_t MAX30105_INT_DIE_TEMP_RDY_ENABLE = 0x02;
    uint8_t MAX30105_INT_DIE_TEMP_RDY_DISABLE = 0x00;
    
    uint8_t MAX30105_SAMPLEAVG_MASK =   (byte)~0b11100000;
    uint8_t MAX30105_SAMPLEAVG_1 =  0x00;
    uint8_t MAX30105_SAMPLEAVG_2 =  0x20;
    uint8_t MAX30105_SAMPLEAVG_4 =  0x40;
    uint8_t MAX30105_SAMPLEAVG_8 =  0x60;
    uint8_t MAX30105_SAMPLEAVG_16 =     0x80;
    uint8_t MAX30105_SAMPLEAVG_32 =     0xA0;
    
    uint8_t MAX30105_ROLLOVER_MASK =    0xEF;
    uint8_t MAX30105_ROLLOVER_ENABLE = 0x10;
    uint8_t MAX30105_ROLLOVER_DISABLE = 0x00;
    
    uint8_t MAX30105_A_FULL_MASK =  0xF0;
    
    // Mode configuration commands (page 19)
    uint8_t MAX30105_SHUTDOWN_MASK =    0x7F;
    uint8_t MAX30105_SHUTDOWN =         0x80;
    uint8_t MAX30105_WAKEUP =           0x00;
    
    uint8_t MAX30105_RESET_MASK =       0xBF;
    uint8_t MAX30105_RESET =            0x40;
    
    uint8_t MAX30105_MODE_MASK =        0xF8;
    uint8_t MAX30105_MODE_REDONLY =     0x02;
    uint8_t MAX30105_MODE_REDIRONLY =   0x03;
    uint8_t MAX30105_MODE_MULTILED =    0x07;
    
    // Particle sensing configuration commands (pgs 19-20)
    uint8_t MAX30105_ADCRANGE_MASK =    0x9F;
    uint8_t MAX30105_ADCRANGE_2048 =    0x00;
    uint8_t MAX30105_ADCRANGE_4096 =    0x20;
    uint8_t MAX30105_ADCRANGE_8192 =    0x40;
    uint8_t MAX30105_ADCRANGE_16384 =   0x60;
    
    uint8_t MAX30105_SAMPLERATE_MASK = 0xE3;
    uint8_t MAX30105_SAMPLERATE_50 =    0x00;
    uint8_t MAX30105_SAMPLERATE_100 =   0x04;
    uint8_t MAX30105_SAMPLERATE_200 =   0x08;
    uint8_t MAX30105_SAMPLERATE_400 =   0x0C;
    uint8_t MAX30105_SAMPLERATE_800 =   0x10;
    uint8_t MAX30105_SAMPLERATE_1000 = 0x14;
    uint8_t MAX30105_SAMPLERATE_1600 = 0x18;
    uint8_t MAX30105_SAMPLERATE_3200 = 0x1C;
    
    uint8_t MAX30105_PULSEWIDTH_MASK = 0xFC;
    uint8_t MAX30105_PULSEWIDTH_69 =    0x00;
    uint8_t MAX30105_PULSEWIDTH_118 =   0x01;
    uint8_t MAX30105_PULSEWIDTH_215 =   0x02;
    uint8_t MAX30105_PULSEWIDTH_411 =   0x03;
    
    //Multi-LED Mode configuration (pg 22)
    uint8_t MAX30105_SLOT1_MASK =       0xF8;
    uint8_t MAX30105_SLOT2_MASK =       0x8F;
    uint8_t MAX30105_SLOT3_MASK =       0xF8;
    uint8_t MAX30105_SLOT4_MASK =       0x8F;
    
    uint8_t SLOT_NONE =                 0x00;
    uint8_t SLOT_RED_LED =          0x01;
    uint8_t SLOT_IR_LED =               0x02;
    uint8_t SLOT_GREEN_LED =            0x03;
    uint8_t SLOT_NONE_PILOT =           0x04;
    uint8_t SLOT_RED_PILOT =            0x05;
    uint8_t SLOT_IR_PILOT =             0x06;
    uint8_t SLOT_GREEN_PILOT =      0x07;
    
    uint8_t MAX_30105_EXPECTEDPARTID = 0x15;
    

    Functions

    The MAX30101 is highly configurable, and there are a large number of functions exposed in the library to the user. Checkout the MAX30105.h file for all the functions, but here are the major ones. Read the MAX30101 datasheet for more information.

    The library supports the following functions:

    • .begin(wirePort, i2cSpeed) - If you have a platform with multiple I2C ports, pass the port object when you call begin. You can increase the I2C speed to 400kHz by including I2C_SPEED_FAST when you call .begin() as well.
    • .setup() - Initializes the sensor with various settings. See the Example 2 from the MAX30105 hookup guide for a good explanation of the options.
    • .getRed() - Returns the immediate red value
    • .getIR() - Returns the immediate IR value
    • .getGreen() - Returns the immediate Green value
    • .available() - Returns how many new samples are available
    • .readTemperature() - Returns the temperature of the IC in C
    • .readTemperatureF() - Returns the temperature of the IC in F
    • .softReset() - Resets everything including data and configuration
    • .shutDown() - Powers down the IC but retains all configuration
    • .wakeUp() - Opposite of shutDown
    • .setLEDMode(mode) - Configure the sensor to use 1 (Red only), 2 (Red + IR), or 3 (Red + IR + Green) LEDs
    • .setADCRange(adcRange) - Set ADC to be at 2048, 4096, 8192, or 16384
    • .setSampleRate(sampleRate) - Configure the sample rate: 50, 100, 200, 400, 800, 1000, 1600, 3200
    Interrupts
    • .getINT1() - Returns the main interrupt group
    • .getINT2() - Returns the temp ready interrupt
    • Enable/disable individual interrupts. See page 13 and 14 of the datasheet for an explanation of each interrupt:
      • .enableAFULL()
      • .disableAFULL()
      • .enableDATARDY()
      • .disableDATARDY()
      • .enableALCOVF()
      • .disableALCOVF()
      • .enablePROXINT()
      • .disablePROXINT()
      • .enableDIETEMPRDY()
      • .disableDIETEMPRDY()
    FIFO

    The MAX30101 has a 32 byte FIFO (first-in first-out) buffer. This allows us do other things on our microcontroller while the sensor is taking measurements.

    • .check() - Call regularly to pull data in from sensor
    • .nextSample() - Advances the FIFO
    • .getFIFORed() - Returns the FIFO sample pointed to by tail
    • .getFIFOIR() - Returns the FIFO sample pointed to by tail
    • .getFIFOGreen() - Returns the FIFO sample pointed to by tail

    Arduino Examples

    ☠ Do not rely on our examples for medical diagnosis or any life saving applications

    Note: Particle detection, heart rate measurement, and photoplethysmography (for pulse oximetry) are applications of the MAX30101. These applications require a fundamental understanding of the operating principles of the sensor and a conceptual knowledge of the applications. Although, we provide some examples for these applications; they are primarily for demonstration purposes only and are not supported by SparkFun.

    Note: Although there is an example, Maxim has since removed the proximity sensing and particle detection as functionalities of this sensor in their datasheet.

    Example 1 - Reading Red/IR/Green

    Once you've got the library installed, open the Example1 Basic Readings sketch. You can find it under

    File > Examples > SparkFun MAX3010x Pulse and Proximity Sensor Library > Examples
    

    Then load it onto your RedBoard or Uno. Open your favorite Serial Terminal to see the printed values.

    Screen shot of MAX30101 readings
    Data readings for photodetector. (Click to enlarge)

    This example outputs the raw values read by the sensor. With the sensor pointing up, use your hand to hover over the sensor. You should see a change in values as your hand reflects different amounts of light. Note that the IR readings will probably change before the Red and Green readings. IR is better at sensing distance changes.

    Completely cover the sensor with your finger. Note the very large readings. This is one of the features that sets the MAX30101 from other reflectance sensors. The IC is capable of reading up to 18-bits or values up to 262,144. An extremely small change in light can be detected!

    The MAX30101 is easy to use! Calling particleSensor.getGreen() will take a reading and return the reflected amount of green light.

    Example 3 - Temperature Sensor

    Open the Example3 Temperature Sense sketch, and load it onto your RedBoard or Uno.

    Temperature output from MAX30101 sensor
    Internal temperature readings. (Click to enlarge)

    This example outputs readings from the on-board temperature sensor in both Celsius and Fahrenheit. The temp sensor is accurate to &PlusMinus;1 °C but has an astonishing precision of 0.0625 °C.

    The temperature is used internally by the sensor to calibrate its samples but can be useful if you need a sensitive and fast responding temp sensor.

    Example 4 - Heart Beat Plotting

    Note: The Arduino IDE must be version 1.6.6 or higher. The Serial Plotter is only available in Arduino versions v1.6.6 or later.

    For this demo, you'll need a rubber band small enough to go through the mounting holes on the breakout. Make sure to follow the example in the Hardware Assembly section for the best results.

    This is where the fun really begins! Hemoglobin reflects IR light really well, and the MAX30101 is capable of detecting such small changes in IR reflectance that it can detect blood flowing through your finger at different rates. Let's graph it! Open the Example4 HeartBeat Plotter sketch, and load it on your Redboard or Uno.

    Instructions:

    1. Load code onto Redboard
    2. Attach sensor to your finger with a rubber band
    3. Open Tools->Serial Plotter
    4. Make sure the drop down is set to 115200 baud
    5. Checkout the blips!
    6. Feel the pulse on your neck and watch it mimic the blips
    I'll just hold my finger on the sensor instead...

    Humans are bad at applying consistent pressure to a thing. Without a rubber band the pressure varies enough to cause the blood in your finger to flow differently which causes the sensor readings to go wonky. It is best to attach the sensor to your finger using a rubber band or other tightening device.

    Graph of heart beat
    Graph of IR data - That's my pulse!

    Now that we have seen the blips, Example 5 will try to calculate the time between blips and show us beats per minute (BPM).

    Example 5 - HeartRate

    ☠ WARNING: Let's have a brief chat about the example code. We're going to try to detect heart-rate optically. This is tricky and prone to give false readings. We really don't want to get anyone hurt, so use this code only as an example of how to process optical data. Build fun stuff with our MAX30101 breakout board, but don't use it for actual medical diagnosis.

    Open the Example5 HeartRate sketch, and load it on your Redboard or Uno.

    Heart rate output
    Heart rate readings. (Click to enlarge)

    This example runs a filter called the PBA or Penpheral Beat Amplitude algorithm on the IR data. This algorithm is able to pull out the blips from all the noise and calculate the time between blips to get a heart rate. The output is your instantaneous heart rate and your average heart rate (BPM).

    As one might expect the human body isn't as precise as a metronome. The time between pulses can vary quite a bit so this sketch takes a running average of 4 readings to try to smooth out the variance.

    Python Package

    Note: This tutorial assumes you are using the latest version of Python 3. If this is your first time using Python or I2C hardware on a Raspberry Pi, please checkout our tutorial on Python Programming with the Raspberry Pi and the Raspberry Pi SPI and I2C Tutorial. Jetson Nano users can check out this tutorial on Working with Qwiic on a Jetson Nano through Jupyter Notebooks.

    We've written a Python package to easily get setup and take readings from the button controller on the Top pHAT. There are two methods for installing the Python package for the button controller.

    1. Install the all inclusive SparkFun Qwiic Python package.
    2. Independently install the SparkFun MAX3010x Python package.

    The all inclusive SparkFun Qwiic Python package, is recommended as is also installs the required I2C driver as well.

    Note: Don't forget to double check that the hardware I2C connection is enabled on your single board computer.

    SparkFun Qwiic Package

    This repository is hosted on PyPi as the sparkfun-qwiic package. On systems that support PyPi installation via pip3 (use pip for Python 2) is simple, using the following commands:

    For all users (note: the user must have sudo privileges):

    language:bash
    sudo pip3 install sparkfun-qwiic
    

    For the current user:

    language:bash
    pip3 install sparkfun-qwiic
    

    Independent Installation

    You can install the sparkfun-qwiic-max3010x Python package independently, which is hosted by PyPi. However, if you prefer to manually download and install the package from the GitHub repository, you can grab them here (*Please be aware of any package dependencies. You can also check out the repository documentation page, hosted on ReadtheDocs.):

    PyPi Installation

    This repository is hosted on PyPi as the sparkfun-qwiic-max3010x package. On systems that support PyPi installation via pip3 (use pip for Python 2) is simple, using the following commands:

    For all users (note: the user must have sudo privileges):

    language:bash
    sudo pip3 install sparkfun-qwiic-max3010x
    

    For the current user:

    language:bash
    pip3 install sparkfun-qwiic-max3010x
    

    Local Installation

    To install, make sure the setuptools package is installed on the system.

    Direct installation at the command line (use python for Python 2):

    language:bash
    python3 setup.py install
    

    To build a package for use with pip3:

    language:bash
    python3 setup.py sdist
    

    A package file is built and placed in a subdirectory called dist. This package file can be installed using pip3.

    language:bash
    cd dist
    pip3 install sparkfun_qwic_max3010x-<version>.tar.gz
    

    Python Package Operation

    Before we jump into getting readings, let's take a closer look at the available functions in the Python package. Below, is a description of the basic functionality of the Python package. This includes the package organization, built-in methods, and their inputs and/or outputs. For more details on how the Python package works, check out the source code and package documentation.

    Dependencies

    This Python package has a very few dependencies in the code, listed below:

    language:python
    from __future__ import print_function
    import struct
    import qwiic_i2c
    import time
    from smbus2 import SMBus, i2c_msg
    _i2c_msg = i2c_msg
    
    from . import heart_rate
    hr = heart_rate.HeartRate()
    

    Default Variables

    The default variables, in the code, for this Python package are listed below:

    language:python
    # Some devices have multiple availabel addresses - this is a list of these addresses.
    # NOTE: The first address in this list is considered the default I2C address for the
    # device.
    _AVAILABLE_I2C_ADDRESS = [0x57] # 7-bit I2C Address
    # Note that MAX30102 has the same I2C address and Part ID
    
    # Status Registers
    MAX30105_INTSTAT1 =     0x00 
    MAX30105_INTSTAT2 =     0x01 
    MAX30105_INTENABLE1 =       0x02 
    MAX30105_INTENABLE2 =       0x03 
    
    # FIFO Registers
    MAX30105_FIFOWRITEPTR =     0x04 
    MAX30105_FIFOOVERFLOW =     0x05 
    MAX30105_FIFOREADPTR =  0x06 
    MAX30105_FIFODATA =     0x07 
    
    # Configuration Registers
    MAX30105_FIFOCONFIG =       0x08 
    MAX30105_MODECONFIG =       0x09 
    MAX30105_PARTICLECONFIG =   0x0A     # Note, sometimes listed as "SPO2" config in datasheet (pg. 11)
    MAX30105_LED1_PULSEAMP =    0x0C 
    MAX30105_LED2_PULSEAMP =    0x0D 
    MAX30105_LED3_PULSEAMP =    0x0E 
    MAX30105_LED_PROX_AMP =     0x10 
    MAX30105_MULTILEDCONFIG1 = 0x11 
    MAX30105_MULTILEDCONFIG2 = 0x12 
    
    # Die Temperature Registers
    MAX30105_DIETEMPINT =       0x1F 
    MAX30105_DIETEMPFRAC =  0x20 
    MAX30105_DIETEMPCONFIG =    0x21 
    
    # Proximity Function Registers
    MAX30105_PROXINTTHRESH =    0x30 
    
    # Part ID Registers
    MAX30105_REVISIONID =       0xFE 
    MAX30105_PARTID =           0xFF     # Should always be 0x15. Identical to MAX30102.
    
    # MAX30105 Commands
    # Interrupt configuration (pg 13, 14)
    MAX30105_INT_A_FULL_MASK =      (~0b10000000)
    MAX30105_INT_A_FULL_ENABLE =    0x80 
    MAX30105_INT_A_FULL_DISABLE =   0x00 
    
    MAX30105_INT_DATA_RDY_MASK = (~0b01000000)
    MAX30105_INT_DATA_RDY_ENABLE =  0x40 
    MAX30105_INT_DATA_RDY_DISABLE = 0x00 
    
    MAX30105_INT_ALC_OVF_MASK = (~0b00100000)
    MAX30105_INT_ALC_OVF_ENABLE =   0x20 
    MAX30105_INT_ALC_OVF_DISABLE = 0x00 
    
    MAX30105_INT_PROX_INT_MASK = (~0b00010000)
    MAX30105_INT_PROX_INT_ENABLE = 0x10 
    MAX30105_INT_PROX_INT_DISABLE = 0x00 
    
    MAX30105_INT_DIE_TEMP_RDY_MASK = (~0b00000010)
    MAX30105_INT_DIE_TEMP_RDY_ENABLE = 0x02 
    MAX30105_INT_DIE_TEMP_RDY_DISABLE = 0x00 
    
    MAX30105_SAMPLEAVG_MASK =   (~0b11100000)
    MAX30105_SAMPLEAVG_1 =  0x00 
    MAX30105_SAMPLEAVG_2 =  0x20 
    MAX30105_SAMPLEAVG_4 =  0x40 
    MAX30105_SAMPLEAVG_8 =  0x60 
    MAX30105_SAMPLEAVG_16 =     0x80 
    MAX30105_SAMPLEAVG_32 =     0xA0 
    
    MAX30105_ROLLOVER_MASK =    0xEF 
    MAX30105_ROLLOVER_ENABLE = 0x10 
    MAX30105_ROLLOVER_DISABLE = 0x00 
    
    MAX30105_A_FULL_MASK =  0xF0 
    
    # Mode configuration commands (page 19)
    MAX30105_SHUTDOWN_MASK =    0x7F 
    MAX30105_SHUTDOWN =         0x80 
    MAX30105_WAKEUP =           0x00 
    
    MAX30105_RESET_MASK =       0xBF 
    MAX30105_RESET =            0x40 
    
    MAX30105_MODE_MASK =        0xF8 
    MAX30105_MODE_REDONLY =     0x02 
    MAX30105_MODE_REDIRONLY =   0x03 
    MAX30105_MODE_MULTILED =    0x07 
    
    # Particle sensing configuration commands (pgs 19-20)
    MAX30105_ADCRANGE_MASK =    0x9F 
    MAX30105_ADCRANGE_2048 =    0x00 
    MAX30105_ADCRANGE_4096 =    0x20 
    MAX30105_ADCRANGE_8192 =    0x40 
    MAX30105_ADCRANGE_16384 =   0x60 
    
    MAX30105_SAMPLERATE_MASK = 0xE3 
    MAX30105_SAMPLERATE_50 =    0x00 
    MAX30105_SAMPLERATE_100 =   0x04 
    MAX30105_SAMPLERATE_200 =   0x08 
    MAX30105_SAMPLERATE_400 =   0x0C 
    MAX30105_SAMPLERATE_800 =   0x10 
    MAX30105_SAMPLERATE_1000 = 0x14 
    MAX30105_SAMPLERATE_1600 = 0x18 
    MAX30105_SAMPLERATE_3200 = 0x1C 
    
    MAX30105_PULSEWIDTH_MASK = 0xFC 
    MAX30105_PULSEWIDTH_69 =    0x00 
    MAX30105_PULSEWIDTH_118 =   0x01 
    MAX30105_PULSEWIDTH_215 =   0x02 
    MAX30105_PULSEWIDTH_411 =   0x03 
    
    #Multi-LED Mode configuration (pg 22)
    MAX30105_SLOT1_MASK =       0xF8 
    MAX30105_SLOT2_MASK =       0x8F 
    MAX30105_SLOT3_MASK =       0xF8 
    MAX30105_SLOT4_MASK =       0x8F 
    
    SLOT_NONE =                 0x00 
    SLOT_RED_LED =          0x01 
    SLOT_IR_LED =               0x02 
    SLOT_GREEN_LED =            0x03 
    SLOT_NONE_PILOT =           0x04 
    SLOT_RED_PILOT =            0x05 
    SLOT_IR_PILOT =             0x06 
    SLOT_GREEN_PILOT =      0x07 
    
    MAX_30105_EXPECTEDPARTID = 0x15
    

    Class

    QwiicMax3010x() or QwiicMax3010x(address)
    This Python package operates as a class object, allowing new instances of that type to be made. An __init__() constructor is used that creates a connection to an I2C device over the I2C bus using the default or specified I2C address.

    The Constructor

    A constructor is a special kind of method used to initialize (assign values to) the data members needed by the object when it is created.

    __init__(address=None, i2c_driver=None):

    Input: value
    The value of the device address. If not defined, the Python package will use the default I2C address (0x71) stored under _AVAILABLE_I2C_ADDRESS variable.
    Input: i2c_driver
    Loads the specified I2C driver; by default the Qwiic I2C driver is used: qwiic_i2c.getI2CDriver(). Users should use the default I2C driver and leave this field blank.

    Functions

    A function is an attribute of the class, which defines a method for instances of that class. In simple terms, they are objects for the operations (or methods) of the class. A list of all the available functions are detailed on the API Reference page of ReadtheDocs for the Qwiic_MAX3010x_Py Python package.

    Upgrading the Python Package

    In the future, changes to the Python package might be made. Updating the installed packages has to be done individually for each package (i.e. sub-modules and dependencies won't update automatically and must be updated manually). For the sparkfun-qwiic-max3010x Python package, use the following command (use pip for Python 2):

    For all users (note: the user must have sudo privileges):

    language:bash
    sudo pip3 install --upgrade sparkfun-qwiic-max3010x
    

    For the current user:

    language:bash
    pip3 install --upgrade sparkfun-qwiic-max3010x
    

    Python Examples

    ☠ Do not rely on our examples for medical diagnosis or any life saving applications

    Note: Particle detection, heart rate measurement, and photoplethysmography (for pulse oximetry) are applications of the MAX30101. These applications require a fundamental understanding of the operating principles of the sensor and a conceptual knowledge of the applications. Although, we provide some examples for these applications; they are primarily for demonstration purposes only and are not supported by SparkFun.

    Note: Although there is an example, Maxim has since removed the proximity sensing and particle detection as functionalities of this sensor in their datasheet.

    There are several examples written for the Qwiic_MAX30101x_Py Python package. They can be found in the Examples folder of the GitHub repository or view on the repository documentation page, hosted on ReadtheDocs. Users can also grab them here, using the link below. (*Please be aware of any package dependencies.):

    Example 1 - Basic Readings

    Example 1 outputs the raw values read by the sensor.

    language:python
    #!/usr/bin/env python
    #-----------------------------------------------------------------------------
    # ex1_Basic_Readings.py
    #
    # Simple example for the qwiic MAX3010x device
    # Outputs all Red/IR/Green values.
    #
    #------------------------------------------------------------------------
    #
    # Written by Pete Lewis
    # SparkFun Electronics, May 2020
    #
    # Based on code from the SparkFun MAX3010x Sensor Arduino Library
    # https://github.com/sparkfun/SparkFun_MAX3010x_Sensor_Library
    # By: Nathan Seidle @ SparkFun Electronics, October 2nd, 2016
    # 
    # This python library supports the SparkFun Electroncis qwiic 
    # qwiic sensor/board ecosystem on a Raspberry Pi (and compatable) single
    # board computers. 
    #
    # More information on qwiic is at https://www.sparkfun.com/qwiic
    #
    # Do you like this library? Help support SparkFun. Buy a board!
    #
    #==================================================================================
    # Copyright (c) 2019 SparkFun Electronics
    #
    # Permission is hereby granted, free of charge, to any person obtaining a copy 
    # of this software and associated documentation files (the "Software"), to deal 
    # in the Software without restriction, including without limitation the rights 
    # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
    # copies of the Software, and to permit persons to whom the Software is 
    # furnished to do so, subject to the following conditions:
    #
    # The above copyright notice and this permission notice shall be included in all 
    # copies or substantial portions of the Software.
    #
    # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
    # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
    # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
    # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
    # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
    # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 
    # SOFTWARE.
    #==================================================================================
    # Example 1
    #
    
    from __future__ import print_function
    import qwiic_max3010x
    import time
    import sys
    
    def runExample():
    
        print("\nSparkFun MAX3010x Photodetector - Example 1\n")
        sensor = qwiic_max3010x.QwiicMax3010x()
    
        if sensor.begin() == False:
            print("The Qwiic MAX3010x device isn't connected to the system. Please check your connection", \
                file=sys.stderr)
            return
        else:
            print("The Qwiic MAX3010x is connected.")
    
        if sensor.setup() == False:
            print("Device setup failure. Please check your connection", \
                file=sys.stderr)
            return
        else:
            print("Setup complete.")        
    
        while True:
                print(\
                 'R[', sensor.getRed() , '] \t'\
                                                                 'IR[', sensor.getIR() , '] \t'\
                                                                 'G[', sensor.getGreen() , ']'\
                )
                time.sleep(0.1)
    
    if __name__ == '__main__':
        try:
            runExample()
        except (KeyboardInterrupt, SystemExit) as exErr:
            print("\nEnding Example 1")
            sys.exit(0)
    

    Just as in the Arduino example, feel free to wave you hand over the sensor to see the changes in values. Users should see an output similar to the image below:

    streaming data
    Raw data streaming from the MAX30101.

    Example 3 - Temperature Sense

    Example 3 outputs readings from the on-board temperature sensor in both Celsius and Fahrenheit. The temp sensor is accurate to &PlusMinus;1 °C but has an astonishing precision of 0.0625 °C.

    language:python
    #!/usr/bin/env python
    #-----------------------------------------------------------------------------
    # ex3_Temperature_Sesnse.py
    #
    # Simple example for the qwiic MAX3010x device
    # This demo outputs the onboard temperature sensor. 
    # The temp sensor is accurate to +/-1 C but
    # has an astonishing precision of 0.0625 C.
    #
    #------------------------------------------------------------------------
    #
    # Written by Pete Lewis
    # SparkFun Electronics, May 2020
    #
    # Based on code from the SparkFun MAX3010x Sensor Arduino Library
    # https://github.com/sparkfun/SparkFun_MAX3010x_Sensor_Library
    # By: Nathan Seidle @ SparkFun Electronics, October 2016
    # 
    # This python library supports the SparkFun Electroncis qwiic 
    # qwiic sensor/board ecosystem on a Raspberry Pi (and compatable) single
    # board computers. 
    #
    # More information on qwiic is at https://www.sparkfun.com/qwiic
    #
    # Do you like this library? Help support SparkFun. Buy a board!
    #
    #==================================================================================
    # Copyright (c) 2019 SparkFun Electronics
    #
    # Permission is hereby granted, free of charge, to any person obtaining a copy 
    # of this software and associated documentation files (the "Software"), to deal 
    # in the Software without restriction, including without limitation the rights 
    # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
    # copies of the Software, and to permit persons to whom the Software is 
    # furnished to do so, subject to the following conditions:
    #
    # The above copyright notice and this permission notice shall be included in all 
    # copies or substantial portions of the Software.
    #
    # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
    # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
    # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
    # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
    # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
    # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 
    # SOFTWARE.
    #==================================================================================
    # Example 3
    #
    
    from __future__ import print_function
    import qwiic_max3010x
    import time
    import sys
    
    def runExample():
    
        print("\nSparkFun MAX3010x Photodetector - Example 3\n")
        sensor = qwiic_max3010x.QwiicMax3010x()
    
        if sensor.begin() == False:
            print("The Qwiic MAX3010x device isn't connected to the system. Please check your connection", \
                file=sys.stderr)
            return
        else:
            print("The Qwiic MAX3010x is connected.")
    
        # Setup Sensor
        # The LEDs are very low power and won't affect the temp reading much but
        # we will call setup() with LEDs off, to avoid any local heating (ledMode = 0)
    
        if sensor.setup(ledMode = 0) == False:
            print("Device setup failure. Please check your connection", \
                file=sys.stderr)
            return
        else:
            print("Setup complete.")        
    
        sensor.enableDIETEMPRDY() # Enable the temp ready interrupt. This is required.
    
        while True:
                temperature = sensor.readTemperature()
                temperatureF = sensor.readTemperatureF()
    
                temperature = round(temperature, 4)
                temperatureF = round(temperatureF, 4)
    
                print(\
                 'temperatureC[', temperature , '] \t',\
                 'temperatureF[', temperatureF , ']',\
                )
    
    
    if __name__ == '__main__':
        try:
            runExample()
        except (KeyboardInterrupt, SystemExit) as exErr:
            print("\nEnding Example 3")
            sys.exit(0)
    

    Feel free to heat up the sensor with your finger or blowing on it to cool it down.

    Temp data streaming
    Internal temperature data streaming from the MAX30101.

    Example 4 - Heartbeat Plotter

    Note: For this demo, you'll need a rubber band small enough to go through the mounting holes on the breakout. Make sure to follow the example in the Hardware Assembly section for the best results. Additionally, this example requires some software for the plotter to be installed.

    On the Raspberry Pi, execute the following lines in the terminal:

    • sudo apt-get install libatlas3-base libffi-dev at-spi2-core python3-gi-cairo
    • sudo pip3 install matplotlib
    On a Jeston Nano, execute the following line in the terminal:
    • sudo apt-get install python3-matplotlib

    Example 4 is where the fun really begins! Hemoglobin reflects IR light really well, and the MAX30101 is capable of detecting such small changes in IR reflectance that it can detect blood flowing through your finger at different rates.

    language:python
    #!/usr/bin/env python
    #-----------------------------------------------------------------------------
    # ex4_HeartBeat_Plotter.py
    #
    # Simple example for the qwiic MAX3010x device
    # Shows the user's heart beat on a graphical plotter
    # Using Matplotlib
    # To learn more about plotting data in python check out this tutorial:
    # https://learn.sparkfun.com/tutorials/graph-sensor-data-with-python-and-matplotlib/
    # The example code below was built using the code from the previously mentioned tutorial.
    # Thanks Shawn Hymel!
    #
    # Instructions:
    #   1) Install MatplotLib (see below)
    #   2) Connect sensor to system via qwiic cable
    #   3) Attach sensor to your finger with a rubber band (see below)
    #   4) Run this python example
    #   5) Checkout the blips!
    #   6) Feel the pulse on your neck and watch it mimic the blips
    #
    #   It is best to attach the sensor to your finger using a rubber band or other tightening
    #   device. Humans are generally bad at applying constant pressure to a thing. When you
    #   press your finger against the sensor it varies enough to cause the blood in your
    #   finger to flow differently which causes the sensor readings to go wonky.
    #
    # MatplotLib install
    # Install Dependencies
    # Like any good Linux project, we need to install a number of dependencies and libraries 
    # in order to get matplotlib to run properly. Make sure you have an Internet connection 
    # and in a terminal, enter the following commands. You may need to wait several minutes 
    # while the various packages are downloaded and installed.
    #
    # sudo apt-get update
    # sudo apt-get install libatlas3-base libffi-dev at-spi2-core python3-gi-cairo
    # sudo pip3 install cairocffi
    # sudo pip3 install matplotlib
    #
    #------------------------------------------------------------------------
    #
    # Written by Pete Lewis
    # SparkFun Electronics, May 2020
    #
    # Based on code from the SparkFun MAX3010x Sensor Arduino Library
    # https://github.com/sparkfun/SparkFun_MAX3010x_Sensor_Library
    # By: Nathan Seidle @ SparkFun Electronics, October 2nd, 2016
    # 
    # This python library supports the SparkFun Electroncis qwiic 
    # qwiic sensor/board ecosystem on a Raspberry Pi (and compatable) single
    # board computers. 
    #
    # More information on qwiic is at https://www.sparkfun.com/qwiic
    #
    # Do you like this library? Help support SparkFun. Buy a board!
    #
    #==================================================================================
    # Copyright (c) 2019 SparkFun Electronics
    #
    # Permission is hereby granted, free of charge, to any person obtaining a copy 
    # of this software and associated documentation files (the "Software"), to deal 
    # in the Software without restriction, including without limitation the rights 
    # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
    # copies of the Software, and to permit persons to whom the Software is 
    # furnished to do so, subject to the following conditions:
    #
    # The above copyright notice and this permission notice shall be included in all 
    # copies or substantial portions of the Software.
    #
    # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
    # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
    # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
    # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
    # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
    # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 
    # SOFTWARE.
    #==================================================================================
    # Example 4
    #
    
    from __future__ import print_function
    import qwiic_max3010x
    import time
    import sys
    
    sensor = qwiic_max3010x.QwiicMax3010x()
    
    #Plotter Stuff
    import matplotlib.pyplot as plt
    import matplotlib.animation as animation
    
    # Create figure for plotting
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    xlen= 100 #sample number, increments and is used for labeling x axis in plot
    xs = list(range(0,xlen))
    ys = [0]*xlen
    line, = ax.plot(xs, ys)
    plt.title('Heartbeat over time')
    plt.ylabel('IR Value')
    
    # This function is called periodically from FuncAnimation
    def animate(i, ys):
        # Read IR from MAX3010x
        ir = sensor.getIR()
    
        ys.append(ir)
        ys = ys[-xlen:]
        line.set_ydata(ys)
        ax.set_ylim([min(ys),max(ys)])
    
        return line,
    
    
    def runExample():
    
        print("\nSparkFun MAX3010x Photodetector - Example 4\n")
    
        if sensor.begin() == False:
            print("The Qwiic MAX3010x device isn't connected to the system. Please check your connection", \
                file=sys.stderr)
            return
        else:
            print("The Qwiic MAX3010x is connected.")
    
        # Setup to sensor
        ledBrightness = 0x1F # Options: 0=Off to 255=50mA
        sampleAverage = 8 # Options: 1, 2, 4, 8, 16, 32
        ledMode = 3 # Options: 1 = Red only, 2 = Red + IR, 3 = Red + IR + Green
        sampleRate = 100 # Options: 50, 100, 200, 400, 800, 1000, 1600, 3200
        pulseWidth = 411 # Options: 69, 118, 215, 411
        adcRange = 4096 # Options: 2048, 4096, 8192, 16384
    
        if sensor.setup(ledBrightness, sampleAverage, ledMode, sampleRate, pulseWidth, adcRange) == False:
            print("Device setup failure. Please check your connection", \
                file=sys.stderr)
            return
        else:
            print("Setup complete.")
        # Set up plot to call animate() function periodically
        ani = animation.FuncAnimation(fig, animate, fargs=(ys,), interval=10, blit=True)
        plt.show()
    
    
    if __name__ == '__main__':
        try:
            runExample()
        except (KeyboardInterrupt, SystemExit) as exErr:
            print("\nEnding Example 4")
            sys.exit(0)
    

    Once the code is running, you should begin to see your pulse as the scale of the axis shrinks into the proper range. Again, the sensor can be a little finicky; especially, if it is moving around slightly. It make take several attempts to view your pulse.

    I'll just hold my finger on the sensor instead...

    Humans are bad at applying consistent pressure to a thing. Without a rubber band the pressure varies enough to cause the blood in your finger to flow differently which causes the sensor readings to go wonky. It is best to attach the sensor to your finger using a rubber band or other tightening device.

    Plotting IR data
    The last 40 values of IR data streaming onto a graph chart from the MAX30101.

    Feel free to compare the plot with your pulse from your carotid artery.

    Example 5 - Heartrate

    ☠ WARNING: Let's have a brief chat about the example code. We're going to try to detect heart-rate optically. This is tricky and prone to give false readings. We really don't want to get anyone hurt, so use this code only as an example of how to process optical data. Build fun stuff with our MAX30101 breakout board, but don't use it for actual medical diagnosis.

    Example 5 runs a filter called the PBA or Penpheral Beat Amplitude algorithm on the IR data. This algorithm is able to pull out the blips from all the noise and calculate the time between blips to get a heart rate. The output is your instantaneous heart rate and your average heart rate (BPM).

    language:python
    #!/usr/bin/env python
    #-----------------------------------------------------------------------------
    # ex5_HeartRate.py
    #
    # Simple example for the qwiic MAX3010x device
    # This is a demo to show the reading of heart rate or beats per minute (BPM) using
    # a Penpheral Beat Amplitude (PBA) algorithm.
    #
    # It is best to attach the sensor to your finger using a rubber band or other tightening
    # device. Humans are generally bad at applying constant pressure to a thing. When you
    # press your finger against the sensor it varies enough to cause the blood in your
    # finger to flow differently which causes the sensor readings to go wonky.
    #
    #------------------------------------------------------------------------
    #
    # Written by Pete Lewis
    # SparkFun Electronics, May 2020
    #
    # Based on code from the SparkFun MAX3010x Sensor Arduino Library
    # https://github.com/sparkfun/SparkFun_MAX3010x_Sensor_Library
    # By: Nathan Seidle @ SparkFun Electronics, October 2nd, 2016
    # 
    # This python library supports the SparkFun Electroncis qwiic 
    # qwiic sensor/board ecosystem on a Raspberry Pi (and compatable) single
    # board computers. 
    #
    # More information on qwiic is at https://www.sparkfun.com/qwiic
    #
    # Do you like this library? Help support SparkFun. Buy a board!
    #
    #==================================================================================
    # Copyright (c) 2019 SparkFun Electronics
    #
    # Permission is hereby granted, free of charge, to any person obtaining a copy 
    # of this software and associated documentation files (the "Software"), to deal 
    # in the Software without restriction, including without limitation the rights 
    # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
    # copies of the Software, and to permit persons to whom the Software is 
    # furnished to do so, subject to the following conditions:
    #
    # The above copyright notice and this permission notice shall be included in all 
    # copies or substantial portions of the Software.
    #
    # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
    # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
    # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
    # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
    # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
    # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 
    # SOFTWARE.
    #==================================================================================
    # Example 5
    #
    
    from __future__ import print_function
    import qwiic_max3010x
    import time
    import sys
    
    def millis():
        return int(round(time.time() * 1000))
    
    def runExample():
    
        print("\nSparkFun MAX3010x Photodetector - Example 5\n")
        sensor = qwiic_max3010x.QwiicMax3010x()
    
        if sensor.begin() == False:
            print("The Qwiic MAX3010x device isn't connected to the system. Please check your connection", \
                file=sys.stderr)
            return
        else:
            print("The Qwiic MAX3010x is connected.")
    
        print("Place your index finger on the sensor with steady pressure.")
    
        if sensor.setup() == False:
            print("Device setup failure. Please check your connection", \
                file=sys.stderr)
            return
        else:
            print("Setup complete.")
    
        sensor.setPulseAmplitudeRed(0x0A) # Turn Red LED to low to indicate sensor is running
        sensor.setPulseAmplitudeGreen(0) # Turn off Green LED
    
        RATE_SIZE = 4 # Increase this for more averaging. 4 is good.
        rates = list(range(RATE_SIZE)) # list of heart rates
        rateSpot = 0
        lastBeat = 0 # Time at which the last beat occurred
        beatsPerMinute = 0.00
        beatAvg = 0
        samplesTaken = 0 # Counter for calculating the Hz or read rate
        startTime = millis() # Used to calculate measurement rate
    
        while True:
    
            irValue = sensor.getIR()
            samplesTaken += 1
            if sensor.checkForBeat(irValue) == True:
                # We sensed a beat!
                print('BEAT')
                delta = ( millis() - lastBeat )
                lastBeat = millis() 
    
                beatsPerMinute = 60 / (delta / 1000.0)
                beatsPerMinute = round(beatsPerMinute,1)
    
                if beatsPerMinute < 255 and beatsPerMinute > 20:
                    rateSpot += 1
                    rateSpot %= RATE_SIZE # Wrap variable
                    rates[rateSpot] = beatsPerMinute # Store this reading in the array
    
                    # Take average of readings
                    beatAvg = 0
                    for x in range(0, RATE_SIZE):
                        beatAvg += rates[x]
                    beatAvg /= RATE_SIZE
                    beatAvg = round(beatAvg)
    
            Hz = round(float(samplesTaken) / ( ( millis() - startTime ) / 1000.0 ) , 2)
            if (samplesTaken % 200 ) == 0:
    
                print(\
                    'IR=', irValue , ' \t',\
                                'BPM=', beatsPerMinute , '\t',\
                                                                                    #'DCE', getDCE() , '\t',\
                                'Avg=', beatAvg , '\t',\
                    'Hz=', Hz, \
                    )
    
    if __name__ == '__main__':
        try:
            runExample()
        except (KeyboardInterrupt, SystemExit) as exErr:
            print("\nEnding Example 5")
            sys.exit(0)
    

    As one might expect the human body isn't as precise as a metronome. The time between pulses can vary quite a bit so this code takes a running average of 4 readings to try to smooth out the variance.

    data output
    Example heart rate calculations. For reference, my resting heart rate was around 68 BPM.

    Troubleshooting

    Raspberry Pi

    For comprehensive information or troubleshooting issues, on the Raspberry Pi, users should check out the Raspberry Pi Foundation website and their forum.

    As a general guideline, users should use the following resources when looking for technical information or assistance that is specifically related to the Raspberry Pi itself:

    1. Raspberry Pi FAQ
    2. Raspberry Pi Beginner's Subforum
    3. Raspberry Pi Documentation and Help Guides
    4. Raspberry Pi Forum

    Nvidia Jetson Nano

    For comprehensive information or troubleshooting issues, on the Nvidia Jetson, users should check out the Nvidia website and their forum.

    As a general guideline, users should use the following resources when looking for technical information or assistance that is specifically related to the Jetson Nano itself:

    1. Jetson Support Resources
    2. Jetson Nano Getting Started Guide
    3. Developer Kit User Manual
    4. Jetson Nano Wiki
    5. Nvidia FAQ
    6. Jetson Forum
    7. Jetpack Documentation

    For users looking for technical assistance, click on the link. There you will find, basic troubleshooting tips and instructions to get started with posting a topic in our forum. Our technical support team will do their best to assist you.

    Resources and Going Further

    For more on the SparkFun Photodetector (MAX30101), check out the links below:

    Application Notes

    Note: Particle detection, heart rate measurement, and photoplethysmography (for pulse oximetry) are applications of the MAX30101. These applications are detailed in the notes below; however, they require an understanding of the operating principles of the sensor and a conceptual knowledge of the application(s). Although, we provided the information below for interested users and may provide some examples of the application in our software; these applications are, unfortunately, not supported by SparkFun and the examples are primarily for demonstration purposes only.

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

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

    Maxim's Original Firmware for the MAX30102 adapted in our Arduino Library:

    For more sensor action, check out these other great SparkFun tutorials.

    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.

    TEMT6000 Ambient Light Sensor Hookup Guide

    Bring the ability to detect light levels to any project with the SparkFun TEMT6000 Ambient Light Sensor Breakout.

    MyoWare Muscle Sensor Kit

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

    9DoF Sensor Stick Hookup Guide

    How to connect and use the SparkFun 9 Degrees of Freedom Sensor Stick with an Arduino

    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>