Categories

Tutorial

A rotary encoder is a device that you can rotate infinitely. Simple ones like this one have no real state like a pot does, so when you start up, you won’t be able to simply read from the encoder where it is turned to. But because you can keep turning it it has no beginning, middle or end anyways. However, if you keep track of that rotation in code, you can use it as a knob input you can turn up or down as much as you would like.

Most simple encoders like this only make use of 4 pins, one of those is ground and other Vcc. Those other two pins change state and are always either high or low, so they can only have a total of 4 combinations. 00, 01, 10, and 11. This is known as 2 bit gray code. So when you turn it, the arduino can say… Well you were at 01, and now you are at 00 so you move this way. Or you were at 01, but now you are at 10 so you must have moved the other way. You can see that this encoder has 5 pins, the other 2 are just a simple switch that is engaged when you press down. (see the second illustration on the right)

It sounds super simple, and it kinda is, but what we can do is every time a value changes we can check what direction it moved. Then if we increment a value every time it turned one way, and deincrement it when we move one step the other, we can keep track of how much it has moved since we started. So if you want a knob that can turn up to 11, this is your guy. (there is a double pun in there I promise)

So, the really funky thing about a rotary encoder is for it to work, we need to know every time those values change. This can be hard because if the arduino is in the middle of doing something, like delay(1000) or what have you, we will miss the change. So we need a way to say to the arduino “I don’t care what you are doing, or when you are doing it, if you see any of these two pins change state, you drop everything and attend to them”. To do this we need something called interrupts.

Interrupts Are Magic

Interrupt pins are special pins that can stop your arduino and force it to do something else before it moves on. Because they are special pins you only get a few of them on your arduino, but these pins can watch for any CHANGE (high to low / low to high), FALLING (high to low) or RISING (low to high). You can attach interrupt functions to these pins, so if a change happens, it will drop everything and run that function. It gets funky as it breaks the basic linear nature of the arduino loop, but can become the most powerful thing when you get the hang of it.

Any global variables that are used inside these functions have a special name. They are called volatile variables, and for good reason. Their values can change at any time. So if you use a volatile twice in your loop, it may not be the same value the second time if it was change during an interrupt function.

Code

To keep track of the rotary encoder we are going to do something that will look really weird, so bear with me. The encoder has 2 digital pins that are either HIGH (1) or LOW (0) right? If we treat the pins as binary, we read them as 00, 01, 10, or 11. The sequence the encoder outputs while spinning clockwise is 00, 01, 11, 10 repeat. So if you have a reading of 01, the next reading can either be 00 or 11 depending on the direction the knob is turned. So by adding the previous encoded value to the beginning of the current encoded value we get 1 of 8 possible numbers (0001, 0010, 0100, 0111, 1000, 1011, 1110 & 1101) 1101, 0100, 0010 & 1011 all mean cockwise movement. 1110, 0111, 0001 & 1000 are all counter-clockwise.

So now we can say this: (sum is last reading + current reading)

If we wanted to treat the binary as decimal numbers we could even shorten that to this:

Arduino Code


 

Introduction

36

Adafruit's 9DOF (9 Degrees of Freedom) breakout board allows you to capture nine distinct types of motion or orientation related data: 3 degrees each of acceleration, magnetic orientation, and angular velocity.

If you also want barometric data, check out the Adafruit 10DOF breakout, which adds a BMP180 barometric pressure sensor to measure altitude and temperature.

After testing a lot of combinations of sensors, we settled on the following devices that we think offer the best results and the least amount of hassle:

  • LSM303DLHC - a 3-axis accelerometer (up to +/-16g) and a 3-axis magnetometer (up to +/-8.1 gauss) on a single die
  • L3GD20 - a 3-axis gyroscope (up to +/-2000 dps)

 

37

Related Links

The Adafruit 9DOF board and library reuses the existing Adafruit drivers for the LSM303DLHC(accelerometer and magnetometer) and the L3GD20 (gyroscope).

For information about these particular drivers, consult the following learning guides:

This breakout is basically just a smooshed together version of both of these so anything you can do with those libraries/guides will follow here.

Connecting It Up

38

All of the sensors on the Adafruit 9DOF breakout communicate via a two-pin I2C bus, making it relatively easy to setup with a minimum number of cables:

Start by breaking the header down so it is 10 pins long. Sometimes we toss in a longer strip, but its easy to break it down, just use pliers or diagonal cutters to snap it down to 10 pins.

Place the long ends of the header into a solderless breadboard to keep them steady.

39

Place the 9DOF board right on top of the header so that the short pins are sticking thru the hole pads

40

Heat up your soldering iron and once it is ready, solder all 10 pads to the header, making sure to check that there is plenty of solder to make a mechanically strong connection and there's no solder bridging either.

41

     

42

That's it! you're done, continue on to the wiring step below

44

Basic Setup (5V Logic, Arduino Uno, etc.)

We'll be using an Arduino UNO here, but the code will work on a Mega or Leonardo just fine. Most other Arduino compatibles should have no problems either but we only support official Arduinos for code.

  • Connect the SCL pin on the breakout to the SCL pin on your Arduino. On an UNO & '328 based Arduino, this is also known as A5, on a Mega it is also known as digital 21 and on a Leonardo/Micro, digital 3
  • Connect the SDA pin on the breakout to the SDA pin on your Arduino. On an UNO & '328 based Arduino, this is also known as A4, on a Mega it is also known as digital 20 and on a Leonardo/Micro, digital 2
  • Connect the VIN pin on the breakout to 3.3V or 5V on your Uno (5V is preferred but if you have a 3V logic Arduino 3V is best)
  • Connect the GND pin on the breakout to the GND pin on your Uno

That's it! With those four wires, you should be able to talk to any of the I2C chips on the board and run any of the example sketches.

45

Advanced Setup

While most people probably won't need to use the pins below, we've also broken out a few extra pins for advanced users or for special use cases. If you need to use any of these pins, simply hook them up to a GPIO pin of your choice on the Uno:

  • GINT - The interrupt pin on the L3GD20 gyroscope
  • GRDY - The 'ready' pin on the L3GD20 gyroscope
  • LIN1 - Interrupt pin 1 on the LSM303DLHC
  • LIN2 - Interrupt pin 2 on the LSM303DLHC
  • LRDY- The ready pin on the LSM303DLHC

These pins are all outputs from the 9-DOF breakout and are all 3.3V logic, you can use them with 5V or 3V as 3.3V registers 'high' on 5V systems.

3V3 Setup

If you are using an MCU or board with 3V3 logic (instead of the 5V logic used by the Arduino Uno), you can still power the 9-DOF with the VIN pin or you can use the 3Vo pin, which will bypass the on-board 3V3 regulator and level shifting:

  • Connect Vin or 3Vo on the breakout to the 3.3V supply on your target MCU
  • Connect GND on the breakout to GND on the target MCU
Like other breakouts on Adafruit, the 9 DOF Breakout is fully level shifted, and you can safely use it on 3V3 or 5V systems.

Software

LSM303DLHC and L3GD20 Drivers

You will need to have all of the following libraries available in your /libraries folder for Arduino to make use of the Adafruit 9DOF breakout:

For information on the Adafruit Sensor Library and the Unified Sensor Drivers used for all of these sensors, feel free to have a look at our related learning guide: Using the Adafruit Unified Sensor Driver

Downloading Libraries from Github

If you aren't familiar with Github, the easiest way to install the libraries is to click on the links above and find the button that looks like this on the main repository page:

sensors_downloadzip.png

Click this button to download a .zip file containing everything in the repository, and then place the files in the Arduino Sketch Folder '/libraries' sub-folder. You should end up with a structure like this:

  • arduinosketches/libraries/Adafruit_9DOF
  • arduinosketches/libraries/Adafruit_L3GD20_U
  • arduinosketches/libraries/Adafruit_LSM303DLHC
  • arduinosketches/libraries/Adafruit_Sensor

If you're new to installing libraries, check out our super-awesome detailed tutorial on how to install Arduino libraries

Adafruit_9DOF Helper Functions

The Adafruit_9DOF.cpp file (from Adafruit_9DOF) includes the following helper functions that are useful when working with typicaly 9DOF projects

bool accelGetOrientation ( sensors_event_t *event, sensors_vec_t *orientation )

This function reads the LSM303DLHC accelerometer data (supplied via the 'event' variable), and converts it into equivalent pitch (x) and roll (y) values, populating the supplied 'orientation' variables .pitch and .roll fields accordingly.

Arguments

  • event: The sensors_event_t variable containing the data from the accelerometer
  • orientation: The sensors_vec_t object that will have its .pitch and .roll fields populated

Returns

  • true if the operation was successful,
  • false if there was an error

Example

See the 'pitchrollheading' example in the Adafruit_9DOF library for an example of how to use this helper function
  1. sensors_event_t accel_event;
  2. sensors_vec_t orientation;
  3.  
  4. /* Calculate pitch and roll from the raw accelerometer data */
  5. accel.getEvent(&accel_event);
  6. if (dof.accelGetOrientation(&accel_event, &orientation))
  7. {
  8. /* 'orientation' should have valid .roll and .pitch fields */
  9. Serial.print(F("Roll: "));
  10. Serial.print(orientation.roll);
  11. Serial.print(F("; "));
  12. Serial.print(F("Pitch: "));
  13. Serial.print(orientation.pitch);
  14. Serial.print(F("; "));
  15. }

bool magGetOrientation ( sensors_axis_t axis, sensors_event_t *event, sensors_vec_t *mag_orientation )

This function populates the .heading field in mag_orientation with the correct angular data (0-359°). Heading increases when rotating clockwise around the specified axis.

Arguments
  • axis: The given axis (SENSOR_AXIS_X, SENSOR_AXIS_Y, or SENSOR_AXIS_Z)
  • event: The raw magnetometer sensor data to use when calculating out heading
  • orientation: The sensors_vec_t object where we will assign an 'orientation.heading' value
Returns
  • true if the operation was successful,
  • false if there was an error

Example

See the 'pitchrollheading' example in the Adafruit_9DOF library for an example of how to use this helper function
  1. sensors_event_t mag_event;
  2. sensors_vec_t orientation;
  3. /* Calculate the heading using the magnetometer */
  4. mag.getEvent(&mag_event);
  5. if (dof.magGetOrientation(SENSOR_AXIS_Z, &mag_event, &orientation))
  6. {
  7. /* 'orientation' should have valid .heading data now */
  8. Serial.print(F("Heading: "));
  9. Serial.print(orientation.heading);
  10. Serial.print(F("; "));
  11. }

bool magTiltCompensation ( sensors_axis_t axis, sensors_event_t *mag_event, sensors_event_t *accel_event )

This function uses the accelerometer data provided in accel_event to compensate the magnetic sensor measurements in mag_event to compensate for situations where the sensor is tilted (the pitch and roll angles are not equal to 0°).

Arguments
  • axis: The given axis (SENSOR_AXIS_X, SENSOR_AXIS_Y, or SENSOR_AXIS_Z) that is parallel to the gravity of the Earth
  • mag_event: The raw magnetometer data to adjust for tilt
  • accel_event: The accelerometer event data to use to determine the tilt when compensating the mag_event values
Returns
  • true if the operation was successful,
  • false if there was an error

Example

  1. sensors_event_t accel_event;
  2. sensors_event_t mag_event;
  3.  
  4. ...
  5.  
  6. // Get a sensor event from the accelerometer and magnetometer
  7. accel.getEvent(&accel_event);
  8. mag.getEvent(&mag_event);
  9.  
  10. if (dof.magTiltCompensation(SENSOR_AXIS_Z, &mag_event, &accel_event))
  11. {
  12. // Do something with the compensated data in mag_event!
  13. }
  14. else
  15. {
  16. // Oops ... something went wrong (probably bad data)
  17. }

Example Sketch

If you run the pitchrollheading sketch in the examples folder, you can see a practical example using these helper functions above, which should result in output similar to the image below:

46

Design Files

Dimensions (Inches)

47

Schematic

48

 

Overview

Introduction

In this article, you are going to build a weather measurement station that will automatically send data to the cloud using the Temboo service. When building home automation projects, we love to connect our devices together wirelessly and to the web, especially using WiFi. One solution is to use WiFi breakout boards or shields, for example using the CC3000 WiFi chip, connect it to an Arduino board, and build your own code for the WiFi communication & remote interface. In this article, I will show you another approach using the Arduino Yun & Temboo.

24

Introduced in 2013 by Arduino, the Arduino Yun is a powerful Arduino board with onboard WiFi & a small Linux machine. Especially, it is really easy to interface with the web service Temboo, which is what we are going to use in this project. We will automatically send data to a Google Docs spreadsheet, which can be accessed from anywhere.

Connections

25

For this project, you will of course need the Arduino Yun board. You will also need a DHT11 (or DHT22) sensor, along with a 4.7K resistor, for humidity measurements. For pressure & temperature measurements, I used a BMP085 sensor on a simple breakout board, but you can also use the newer Adafruit BMP180 sensor board, which works with the same library. For light levels measurements, I used a photocell with a 10K Ohm resistor. Finally, I used a breadboard and some male-male jumper wires.

On the software side, you will need the Arduino IDE in the latest version (in Beta when this article was written). You will also need the DHT library, the BMP085 or BMP180 library, and the unified sensor library. To install a library, simply put the folder in your /libraries/ folder of you main Arduino folder. This tutorial also assumes that your Arduino Yun is already connected to your WiFi network. If you need help with that, please follow the dedicated tutorials on the Arduino website.

You will also need a Google account for the rest of the project. If you don’t have one yet, please create one, for example by going on the Google Drive page.

26

 

The hardware connections for this project are actually quite simple: we have to connect the DHT11 sensor, and then the part responsible for the light level measurement with the photocell. First, connect the Arduino Yun +5V pin to the red rail on the breadboard, and the ground pin to the blue rail.

Then, connect pin number 1 of the DHT11 sensor to the red rail on the breadboard, and pin number 4 the blue rail. Also connect pin number 2 to pin number 8 of the Arduino Yun. To finish up with the DHT11 sensor, connect the 4.7k Ohm between pin number 1 and 2 of the sensor.

For the photocell, first place the cell in series with the 10k Ohm resistor on the breadboard. Then, connect the other end of the photocell to the red rail on the breadboard, and the other end of the resistor to the ground. Finally, connect the common pin to the Arduino Yun analog pin A0.

For the BMP085 or BMP180 sensor, connect the VIN pin to the +5V, GND to Ground, SCL to Arduino Yun pin number 3, and SDA pin to Arduino Yun pin number 2. The following picture summarises the hardware connection:

27

Before connecting the project to the cloud, we'll test every sensors individually with a test sketch that simply uses the conventional Arduino part of the Yun. The first step in the code is to import the correct libraries:
  1. #include "DHT.h"
  2. #include <Wire.h>
  3. #include <Adafruit_Sensor.h>
  4. #include <Adafruit_BMP085_U.h>
We need to define the pin & type of the DHT sensor:
  1. #define DHTPIN 8
  2. #define DHTTYPE DHT11
And create the instances for the DHT sensor & BMP sensor:
  1. DHT dht(DHTPIN, DHTTYPE);
  2. Adafruit_BMP085_Unified bmp = Adafruit_BMP085_Unified(10085);

In the setup() function, we can initialise the BMP sensor:

  1. bmp.begin()
In the loop() part of the sketch, we make the different measurements, for example humidity, temperature & light level:
  1. // Measure the humidity
  2. float humidity = dht.readHumidity();
  3.  
  4. // Measure light level
  5. int lightLevel = analogRead(A0);
  6.  
  7. // Measure pressure & temperature from BMP sensor
  8. sensors_event_t event;
  9. bmp.getEvent(&event);
  10. float pressure = event.pressure;
These different measurements will then be printed on the Serial monitor. Of course, you can find the complete sketch on our GitHub repository for this project. You can now upload the sketch to the board & open the Serial monitor. This is what you should see:

28

f that works, it means all your hardware connections are correct, and you can move to the next part of the project.

Setting up your Temboo account

Before you can upload data to Google Docs, you need to have a Temboo account. Go over to theTemboo website and enter your email to start the account creation process:

29

You will also be prompted to enter an account name:

30

After that step, you will be asked to give a name to your first app, and you will be given an API key for your app. Please keep at hand your account name, app name, and API key, you will need them soon. In case you forgot to write these down, you can always go in "My account" and click on the "Manage" button next to "Applications" to get it back:

31

You will also need to follow a procedure to create a Google application, and at the end get a Google client ID, client secret & access token. The Temboo website explains this procedure very well, and you can find the whole procedure at:

https://www.temboo.com/library/Library/Google/Spreadsheets/

Arduino sketch

Now, we are going to build the Arduino sketch. You need to import all the libraries for the Arduino Yun web & bridge functionalities. You can read more about starting out with Temboo & Yun here:https://www.temboo.com/arduino/yun/

These are all the libraries used in this project:

  1. #include <Bridge.h>
  2. #include <Temboo.h>
  3. #include <Process.h>
  4. #include <Wire.h>
  5. #include <Adafruit_Sensor.h>
  6. #include <Adafruit_BMP085_U.h>

I also placed all my Temboo account information in a separate file, please make sure that you update your personal account information in this file:

  1. #include "TembooAccount.h"

You also need to set your own informations about your Google account:

  1. const String GOOGLE_CLIENT_ID = "your-google-client-id";
  2. const String GOOGLE_CLIENT_SECRET = "your-google-client-secret";
  3. const String GOOGLE_REFRESH_TOKEN = "your-google-refresh-token";
  4. const String SPREADSHEET_TITLE = "your-spreadsheet-title";

In the setup() part of the sketch, we initialise the Arduino Bridge library:

  1. Bridge.begin();

We also start a date process, to automatically send the measurements date to Google Docs:

  1. time = millis();
  2. if (!date.running()) {
  3. date.begin("date");
  4. date.addParameter("+%D-%T");
  5. date.run();
  6. }

In the loop() part, the most important line is:

  1. runAppendRow(humidity, lightLevel, pressure, temperature, altitude);

Which calls the function to automatically send the data to the Google Docs spreadsheet. I won’t get into the details of these two functions, but of course you will find all the code in the GitHub repository of this project.

The loop() of the Arduino sketch is repeated every 10 minutes with a delay() function, as these variables are usually changing slowly over time.

Using the project

It's now time to test our project. First, we'll do some configuration in Google Docs. Create a new spreadsheet in Google Docs, name it (I named mine "Yun"), and set the title of each columns in the first row, like the picture below:

32

Finally, you are ready to test the project. Upload the code to the Arduino Yun board, open the Google Docs spreadsheet in your browser again, and wait a moment. After a while, the first measurement should appear:

33

I also used the built-in plotting functions of Google Docs to plot my data as it comes in. For example, I used the simple "Line" chart type to plot the light level. This is the result over some hours in the morning, showing that the light level is slowly rising:

34

And over the same period of time, I plotted the evolution of the temperature & humidity:

35

The really nice thing about this is that it is updated automatically as data comes in, and it can be accessed from anywhere: you just need your Google username & password!

You just learned in this project how to send measurements from your Arduino Yun board to Google Docs, so this data can be accessed from anywhere. You also saw how to build automated email alerts based on the data in your home. You can of course improve this project in many ways. The first one is to add more sensors to the project, for example a wind speed sensor or a smoke sensor. You could even add an USB camera to store pictures on an SD card, using the Yun SD card reader.

You can of course use many Arduino Yun boards, for example in different parts of your home. You can also customise the email alert part: you can build more complex alerts based on the measured data, or set the project to email you the sensor data at a regular time interval. If you have other ideas to improve this project, please share!

Overview

Staring at a computer monitor all day is quite stressful. Moving your gaze from the cold, white light of a monitor to warmer indoor light is especially jarring to your senses. Programs like f.lux and Redshiftwere created to ease this strain by adjusting the color temperature of your monitor. However these programs don't measure color temperature of light in the environment and instead guess the temperature based on location, time of day, and sunrise/sunset time.

This project will show you how to build hardware that measures the temperature of ambient light and automatically adjusts your monitor color to match. With just a simple RGB color sensor and an Arduino or FT232H-based cable, your computer can easily sense and react to light in its environment.

Before building this project, it will be helpful to familiarize yourself with the color sensor guide.

Hardware

You'll need the following parts to build this project:
Arduino Uno, Micro, or other Arduino which supports USB serial and I2C communication.
15

Optionally an FTDI FT232H chip or cable, either 5 volt or 3.3 volt version will work.  This cable can be used to communicate with the color sensor in place of the Arduino.

Note that the code to talk to the chip only works with Linux or MacOS X--if you're on Windows stick with using an Arduino.

16
Right angle header to solder on the color sensor for flush mounting to a monitor.
17
Female to male extension cables for connecting to the color sensor.
18
Velcro or other means to attach the sensor to the front of your monitor.
19

RGB Color Sensor

You can use the Flora RGB color sensor too, but the breakout board sensor will be easier to mount to a right angle header.

20

Assembly

The assembly of this project is very simple. Cut the right angle header to size and solder it to the color sensor. Connect the color sensor to the Arduino as follows:

  • Color sensor 5V to Arduino 5V
  • Color sensor GND to Arduino ground
  • Color sensor SDA to Arduino SDA (analog 4 on older Arduinos, check your your board pinout to be sure)
  • Color sensor SCL to Arduino SCL (analog 5 on older Arduinos, see above to check others)
  • Color sensor LED to Arduino ground to disable the built-in LED.
21

Above you can see a picture of the hardware connected to an Arduino Nano.

If you're using the FT232H cable instead of the Arduino, connect it to the sensor as follows:

  • If using the 5V cable: color sensor 5V to cable power (red)
  • If using the 3.3V cable: color sensor 3.3V to cable power (red)
  • Color sensor GND to cable ground wire (black)
  • Color sensor SDA to both the cable green and yellow wires to duplex the sent and received I2C data.
  • Color sensor SCL to cable clock wire (orange)
  • Color sensor LED to cable ground wire (black)

I found it was easiest to cut a few female to male extension cables up and solder them into 2-into-1 Y adapters to connect the SDA -> green and yellow, and GND & LED -> ground connections.

22

Above you can see a picture of the hardware connected to a 3.3 volt version of the FT232H cable.

If you have questions about using the FT232H cable, check out its data sheet here or this application note on using the cable to talk I2C.

Software

Dependencies

You'll need to download and install the following dependencies for this project's software:
Adafruit TCS34725 Color Sensor Arduino Library
If you aren't sure how to install an Arduino library, check out this tutorial.

Python
The software for this guide is written in python and should work with either python 2.7 or 3+ (although it was primarily tested against version 2.7).

Once you have python installed, follow these steps depending on your platform:

Mac OS X

Install NumPy with one of the binary packages here.

Install the PIP python package manager by executing the following commands in a terminal:

wget https://raw.github.com/pypa/pip/master/contrib/get-pip.py
python get-pip.py

Finally, install the colormath and pyserial library by executing in a terminal:

pip install colormath==1.0.9 pyserial

If you plan to use the FT232H cable, download and install the X code command line tools by following the steps in the answer here. You will also want to install the homebrew package manager too. Once those are installed you can install the required libftdi and libmpsse dependencies by executing in a terminal:

brew install libftdi
brew install swig
wget https://libmpsse.googlecode.com/files/libmpsse-1.3.tar.gz
tar xvfz libmpsse-1.3.tar.gz
cd libmpsse-1.3
./configure
make
sudo make install

Linux

These steps are written for Ubuntu, but should be straightforward to adapt to other distributions. In a terminal execute the following commands:

sudo apt-get install python-numpy python-pip
pip install colormath pyserial

If you plan to use the FT232H cable, execute the following commands to install the required software:

sudo apt-get install python-dev libftdi-dev swig
wget https://libmpsse.googlecode.com/files/libmpsse-1.3.tar.gz
tar xvfz libmpsse-1.3.tar.gz
cd libmpsse-1.3
./configure
make
sudo make install

Windows

Install NumPy from one of the binary installers here.

Install PIP by downloading the get-pip.py file, opening a command window, navigating to the directory with the file, and executing:

python get-pip.py

Note you might need to add python to your path to be able to run scripts from the command line.This blog post has a simple set of instructions to add python to your path.

Now execute the following command to install the required colormath and pyserial library:

pip install colormath pyserial

At this point all the dependencies for Windows are installed. Unfortunately you won't be able to use the FT232H cable with Windows because the libmpsse library doesn't support it. Stick to using an Arduino to communicate with the color sensor on Windows.

Also note that the software for this project has only been tested on a virtual machine running Windows. Everything should work on a real machine, but if you have issues send them to the github repository for the project.

Download Project Software

Download the software for this project from its github repository by clicking this button:

Download Software

Unzip the archive and you will find an Arduino sketch, AutoColorTemp_Sketch, and a collection of python scripts.

If you're using an Arduino for this project, load the sketch in Arduino and upload it to your hardware. If you open the serial monitor at 115200 baud you should be able to send a question mark character ? and see the current RGB color (in floating point, with values from 0-1.0) printed.

Software Usage

To run the software for this project, make sure you've assembled the hardware and connected it to your computer. Open a terminal and navigate to the directory with the downloaded python scripts and execute the following command:

python run.py --help

You should see a display of all the command line parameters for the program. Take note that either the --arduino or --ftdi parameters are required to run the program.

For example to run the program with Arduino hardware connected to /dev/ttyUSB0, execute:

python run.py --arduino /dev/ttyUSB0

Or to run with an Arduino connected to COM4 on Windows, execute:

python run.py --arduino COM4

To use the FTDI cable you need to specify the --ftdi option instead of the --arduino option. No port or other parameter is required when using the --ftdi option.

However, before the software is run with the --ftdi option you must disable the built in kernel driver for FTDI devices!
Unfortunately the driver built in to recent Linux and Mac OS X kernels is not compatible with the libftdi library and must be temporarily disabled. The provided run_ftdi_linux.shand run_ftdi_macos.sh shell scripts can be run to automatically disable and re-enable the drivers when running the software. These shells scripts need to be run as root with the sudo command.

For example to run with FTDI hardware on a Mac, execute:

sudo ./run_ftdi_macos.sh --ftdi

Or on Linux execute:

sudo ./run_ftdi_linux.sh --ftdi

Be aware when the program is running the FTDI drivers will be disabled so you will not be able to program an Arduino or communicate with other FTDI-based devices!

Once the software is running it will query the color sensor every 10 seconds, compute the temperature of the measured color, and adjust the gamma of the primary display to match the measured color temperature. Make sure to disable or close programs like f.lux before running the software as they might interfere with the gamma adjustment!

Try shining different colored lights on the sensor to trick it into seeing extreme temperatures (orange, white, or light blue LEDs work best--other colors will be too extreme).

You can press Ctrl-C at any time to quit the application.

Future Work

This project is a great example of using an Arduino or FT232H-based cable to send sensor data to your computer. Using an RGB color sensor you can make your computer aware of the environment and change monitor color temperature based on ambient lighting. Some interesting ways you might extend this project include:

  • Flip the sensor around to read color displayed by your monitor and build a calibration tool to adjust colors for perfect display accuracy.
  • Use the color sensor to play different music depending on the color of light in the room. Play exciting music to boost productivity in the morning and afternoon, and more relaxed music in the evening and night.
  • Build a color matching game for kids where the computer asks to see items of a specific color.
  • Extend the Adalight project to measure ambient light and adjust itself to match the color.

Overview

Capacitive touch breakout boards are an excellent way to use household objects as inputs on your Raspberry Pi. Any conductive object can act as a switch when connected to sensor boards, including potatoes, apples, spoons and pencil graphite.

1

The capacitive touch sensors detect when you touch the board's pad or an object connected to the board. Humans carry a small electrical charge. When you touch a capacitive touch sensor it will detect this charge.

With some simple wiring to the Raspberry Pi and a few lines of Python, you've got a fun and easy way to control your projects and games. For example at the end of this guide we'll show you how to control Minecraft: Pi Edition using a apples.

There are three breakout boards that this guide will show you how to use with your Raspberry Pi.

Momentary

The momentary capacitive touch sensor will be active as long as something is touching it. The LED shows whether a touch has been detected.

The board has a large touch-pad. The small copper hole near the touch-pad can be used to connect the board to capacitive items such as a drawing made with pencil graphite.


2

Toggle

The toggle capacitive touch sensor will activate when you press it and deactivate when you press it a second time. The LED will light up to indicate whether your touch has been detected.

Like the momentary sensor, this sensor has a large touch-pad. The small copper hole near the touch-pad allows you to use a wire to connect your board to everyday objects, like a spoon, which can then be used as an input.

3

5-Pad

The 5-Pad capacitive touch sensor offers a total of 5 inputs on one board. It is very similar to the momentary board, but includes more inputs. Unlike the other boards it does not have any pads, instead the pins on the right of the board are used to detect touch. These pins can be connected to wires, which can be attached to everyday objects, like bananas.

4

Assembly

Assembling the capacitive touch sensors is very straightforward and can be achieved with minimal soldering.

If you're new to soldering, check out the Adafruit Guide to Excellent Soldering.

Headers

Cut the headers and place them onto a solderless breadboard.

5

Place the Board

Place the boards onto the headers and check that they are spaced correctly.

6

Solder

Solder the pins with a soldering iron.

To get the momentary and toggle boards to lie flat on the headers, solder a single pin. Reheat the solder on the pin and adjust the board until you are happy with its positioning.

7

Admire

Take a moment to sit back and admire your work.

8

Wiring

In this section we'll learn how to wire up the sensor boards to a Raspberry Pi. For this you will need:

  • A capacitive touch sensor (momentary, toggle or 5-pad)
  • A solderless breadboard
  • Breadboarding/jumper wire
  • An Adafruit Pi Cobbler and ribbon cable (available pre-soldered) or male-female jumper wire
  • A 10k resistor (no resistors are required for the 5-pad board)
  • Apples, potatoes, bannanas or another fun object that you can connect the board to
  • A Raspberry Pi Model A or Model B
  • Power supply, mouse, monitor, monitor cable, keyboard and SD card for the Raspberry Pi

Momentary Board Wiring

9

When wiring my boards I prefer to use Adafruit's Pi Cobbler to connect my Raspberry Pi to the breadboard, but you can also use jumper wire to connect to the Raspberry Pi's GPIO instead.

Toggle Board Wiring

The wiring for the momentary and toggle breakouts is not identical. The momentary board uses 4 header pins whereas the toggle board uses 5 header pins. The VCC is in a different position on the two boards.

10

5-Pad Sensor Wiring

The 5-pad capacitive breakout works in the same way as the momentary and toggle breakouts. It has more inputs than the other boards and therefore requires more GPIO pins on the Raspberry Pi.

Although there are 5 inputs on the 5-pad board, only one output can be active and transmitted to the Pi at a time.

Each of the input wires can be connected to objects. I like to use apples and potatoes.

11

LEDs

When you press the pad on the board the LED should light up. You must have your Raspberry Pi switched on and connected to the board in order for this to happen. Even if you're not running any programs that use the GPIOs, the LEDs will still light up as the boards are connected to the power and ground pins on the Pi.

If it works, well done, you're ready to move onto creating a Python program that uses the board.

The 5-pad board has 5 LEDs, one for each input.

Connecting to Objects

Each of the boards can be connected to everyday objects that are conductive. This includes fruit, vegetables, plants, metals, animals, conductive fabrics, pencil graphite and conductive paint to name a few.

With some objects you may find that the sensor will be activated when your hand is near the object, but not touching it. This is normal and very common with fruits and vegetables that contain a lot of water.

Adafruit also stocks a number of materials which are excellent for connecting your sensors to:

Materials that are not conductive will not work. Plastics, wood, fabric and glass are all not conductors.

A tip: Although your novel idea of using raspberries with your capacitive touch sensor and your Raspberry Pi may seem like a stroke of genius, the raspberries are very soft and will quickly turn to mush. Try using firmer fruit instead, like an apple or a melon.

Programming

These example programs show you how to use the capacitive touch sensors with Python and the Raspberry Pi's GPIO. It is relatively straightforward to adapt the programs to do different things. Just change the lines with print "pressed".

Two versions of the code are provided. One will continuously print output to the terminal while the touch sensor is pressed. The other will only print output once, irrelevant of how long the pad is pressed. Both pieces of code will work with the momentary and toggle boards.

Code for 5-pad board can be found on the next page of the guide.

Installing the GPIO Module

In order to use the Python code you need to have the RPi.GPIO module installed. The Python GPIO module is pre-installed on all of the latest Raspbian images so it's likely that it's already installed. If it is not installed follow the steps in Adafruit's Raspberry Pi Lesson 4. GPIO Setup

Make sure you have connected the boards using the wiring instructions in the previous section before continuing.

Continuous Output

This version of the code will continuously print output while the pad is pressed.

  1. import time
  2. import RPi.GPIO as GPIO
  3. GPIO.setmode(GPIO.BCM)
  4.  
  5. padPin = 23
  6. GPIO.setup(padPin, GPIO.IN)
  7.  
  8.  
  9. while True:
  10. padPressed = GPIO.input(padPin)
  11.  
  12. if padPressed:
  13. print "pressed"
  14. time.sleep(0.1)

12

Single Output

This version of the Python code will only print an output once each time the sensor detects a touch.

  1. import time
  2. import RPi.GPIO as GPIO
  3. GPIO.setmode(GPIO.BCM)
  4.  
  5. padPin = 23
  6. GPIO.setup(padPin, GPIO.IN)
  7.  
  8.  
  9. alreadyPressed = False
  10.  
  11. while True:
  12. padPressed = GPIO.input(padPin)
  13.  
  14. if padPressed and not alreadyPressed:
  15. print "pressed"
  16. alreadyPressed = padPressed
  17. time.sleep(0.1)

13

Running the Code

Open a terminal. Move to the directory that you saved the code and type in the following command (change the file name to whatever you called your Python file):

  1. sudo python capacitiveTouch.py

Programming the 5-Pad Sensor

The code for the 5-pad capacitive touch sensor can be found below. It cannot be swapped with either of the single pad boards as they are wired differently.
  1. import RPi.GPIO as GPIO
  2. import time
  3.  
  4. GPIO.setmode(GPIO.BCM)
  5.  
  6. #set the GPIO input pins
  7. pad0 = 22
  8. pad1 = 27
  9. pad2 = 17
  10. pad3 = 24
  11. pad4 = 23
  12.  
  13. GPIO.setup(pad0, GPIO.IN)
  14. GPIO.setup(pad1, GPIO.IN)
  15. GPIO.setup(pad2, GPIO.IN)
  16. GPIO.setup(pad3, GPIO.IN)
  17. GPIO.setup(pad4, GPIO.IN)
  18.  
  19. pad0alreadyPressed = False
  20. pad1alreadyPressed = False
  21. pad2alreadyPressed = False
  22. pad3alreadyPressed = False
  23. pad4alreadyPressed = False
  24.  
  25.  
  26. while True:
  27. pad0pressed = not GPIO.input(pad0)
  28. pad1pressed = not GPIO.input(pad1)
  29. pad2pressed = not GPIO.input(pad2)
  30. pad3pressed = not GPIO.input(pad3)
  31. pad4pressed = not GPIO.input(pad4)
  32. if pad0pressed and not pad0alreadyPressed:
  33. print "Pad 0 pressed"
  34. pad0alreadyPressed = pad0pressed
  35.  
  36. if pad1pressed and not pad1alreadyPressed:
  37. print "Pad 1 pressed"
  38. pad1alreadyPressed = pad1pressed
  39.  
  40. if pad2pressed and not pad2alreadyPressed:
  41. print "Pad 2 pressed"
  42. pad2alreadyPressed = pad2pressed
  43.  
  44. if pad3pressed and not pad3alreadyPressed:
  45. print "Pad 3 pressed"
  46. pad3alreadyPressed = pad3pressed
  47.  
  48. if pad4pressed and not pad4alreadyPressed:
  49. print "Pad 4 pressed"
  50. pad4alreadyPressed = pad4pressed
  51.  
  52. time.sleep(0.1)

14

Running the Code

Open a terminal. Move to the directory that you saved the code and type in the following command (change the file name to whatever you called your Python file):

  1. sudo python 5pad.py
The program works very similar to the programs for the momentary and toggle sensor boards. If you're having trouble understanding how the code works for the 5-pad, have a look at the code on the previous section of this guide first.

Controlling Minecraft: Pi Edition

The GPIO pins on the Raspberry Pi are one of the reasons for its popularity. In this guide we've used the GPIO to connect to capacitive touch sensors. This has a range of applications and allows you to create some really creative projects.

The Raspberry Pi has a special version of Minecraft that can be programmed with Python. Combining Minecraft on the Raspberry Pi with our capacitive touch sensors allows us to create programs with limitless potential for creativity and fun.

Install Minecraft: Pi Edition

Before we begin you'll need to have Minecraft: Pi Edition installed on your Raspberry Pi. To install Minecraft Pi you can use this guide on the Adafruit Learning System.

Copy the API

In order to connect to a Minecraft game you will need to copy the API.

Open a terminal and create a new directory named Minecraft within the Documents directory with the following command:

mkdir ~/Documents/Minecraft

Next, we will copy the API into this folder with the following command:

cp -r ~/mcpi/api/python/ ~/Documents/Minecraft

Super Jump

This code uses the capacitive touch pad with Minecraft: Pi Edition to make the player jump 10 blocks into the air when the pad is pressed.

This code works best with the momentary board, though can be used with the toggle board and can be adapted for the 5-pad board.

  1. import RPi.GPIO as GPIO
  2. import time
  3. import mcpi.minecraft as minecraft
  4. mc = minecraft.Minecraft.create()
  5.  
  6. GPIO.setmode(GPIO.BCM)
  7.  
  8. padPin = 23
  9.  
  10. GPIO.setup(padPin, GPIO.IN)
  11.  
  12. alreadyPressed = False
  13.  
  14. while True:
  15. padPressed = GPIO.input(padPin)
  16.  
  17. if padPressed and not alreadyPressed:
  18. pos = mc.player.getPos()
  19. x = pos.x
  20. y = pos.y + 10
  21. z = pos.z
  22. mc.player.setPos(x, y, z)
  23. alreadyPressed = padPressed
  24. time.sleep(0.1)

Melons

This code will place a melon block at the current position of the player. If you hold down the touch pad of the capacitive touch sensor or use toggle sensor, a trail of melons will be created wherever the player walks. This example works particularly well with the toggle sensor board.

  1. import RPi.GPIO as GPIO
  2. import time
  3. import mcpi.minecraft as minecraft
  4. mc = minecraft.Minecraft.create()
  5.  
  6. GPIO.setmode(GPIO.BCM)
  7.  
  8. padPin = 23
  9.  
  10. GPIO.setup(padPin, GPIO.IN)
  11.  
  12. # melon block
  13. blockType = 103
  14.  
  15. while True:
  16. padPressed = GPIO.input(padPin)
  17.  
  18. if padPressed:
  19. pos = mc.player.getPos()
  20. x = pos.x
  21. y = pos.y
  22. z = pos.z
  23. mc.setBlock(x, y, z, blockType)
  24.  
  25. time.sleep(0.1)

Control Panel (5-Pad Board)

In the last example we use the 5-pad capacitive touch sensor board to do 5 different things in Minecraft Pi.

This is what each pad does:

0 - Teleports the player to co-ordinates (0, 0, 0)
1 - Places a flower at the player's position
2 - Places explosive TNT at the player's position
3 - Checks if the player is in water
4 - Toggles whether or not blocks can be smashed

  1. import RPi.GPIO as GPIO
  2. import time
  3. import mcpi.minecraft as minecraft
  4. mc = minecraft.Minecraft.create()
  5.  
  6. GPIO.setmode(GPIO.BCM)
  7.  
  8. #set the GPIO input pins
  9. pad0 = 22
  10. pad1 = 27
  11. pad2 = 17
  12. pad3 = 24
  13. pad4 = 23
  14.  
  15. GPIO.setup(pad0, GPIO.IN)
  16. GPIO.setup(pad1, GPIO.IN)
  17. GPIO.setup(pad2, GPIO.IN)
  18. GPIO.setup(pad3, GPIO.IN)
  19. GPIO.setup(pad4, GPIO.IN)
  20.  
  21. pad0alreadyPressed = False
  22. pad3alreadyPressed = False
  23. pad4alreadyPressed = False
  24.  
  25. immutable = False
  26. tnt = 46
  27. water = 9
  28. flowers = 38
  29.  
  30. while True:
  31. pad0pressed = not GPIO.input(pad0)
  32. pad1pressed = not GPIO.input(pad1)
  33. pad2pressed = not GPIO.input(pad2)
  34. pad3pressed = not GPIO.input(pad3)
  35. pad4pressed = not GPIO.input(pad4)
  36.  
  37. if pad0pressed and not pad0alreadyPressed:
  38. #teleport
  39. x = 0
  40. y = 0
  41. z = 0
  42. mc.player.setPos(x, y, z)
  43. pad0alreadyPressed = pad0pressed
  44.  
  45. if pad1pressed:
  46. #Flowers
  47. pos = mc.player.getPos()
  48. x = pos.x
  49. y = pos.y
  50. z = pos.z
  51. mc.setBlock(x, y, z, flowers)
  52.  
  53. if pad2pressed:
  54. #TNT
  55. pos = mc.player.getPos()
  56. x = pos.x
  57. y = pos.y
  58. z = pos.z
  59. mc.setBlock(x, y, z, tnt, 1)
  60.  
  61. if pad3pressed and not pad3alreadyPressed:
  62. #Chat message: Are in water?
  63. pos = mc.player.getPos()
  64. block = mc.getBlock(pos.x, pos.y, pos.z)
  65. inWater = block == water
  66. mc.postToChat("In water: " + str(inWater))
  67. pad3alreadyPressed = pad3pressed
  68.  
  69. if pad4pressed and not pad4alreadyPressed:
  70. #Immutable
  71. immutable = not immutable
  72. mc.setting("world_immutable", immutable)
  73. mc.postToChat("Immutable: " + str(immutable))
  74. pad4alreadyPressed = pad4pressed
  75.  
  76. time.sleep(0.1)

Running the Code

To run any of the examples on this page you will need to be in Minecraft game world on your Raspberry Pi. You will get an error if you don't have Minecraft open or if you're on the title screen.

All of these examples use the same wiring as the rest of this guide.

The code runs like any other Python program that uses the GPIO. You can run it from the terminal on your Raspberry Pi with the following command (change the name of the program):

  1. sudo python superJump.py

Inside the Whistle

 

51

The Whistle is an activity monitor for dogs. It clips onto the collar and tracks your dog's motion throughout the day. The Whistle joins your home wifi network to report stats to the iOS/Android app even when you're not home.

The Whistle also has bluetooth, and reports on who your dog was spending time with if you've added multiple owners to the device. It's also waterproof. So we wanted to get inside to see all the tech crammed into such a small space.

52

The Whistle charges with a special USB charging port containing pogo pins. The pogo pins press up on metal tabs in the waterproof enclosure to cause contact to the circuit board for charging, but stay not connected when the device is in use.

53

After prying off both bits of metal, we found a glued plastic disc on top that diffuses the LEDs and keeps the water out. This was hard to remove, and we did our best not to mangle the device by carefully cutting into it with flush diagonal snips.

 

This is the circuitry after being removed from the plastic enclosure. We mangled the flex connector to the LED PCB during disassembly. The rechargeable lipoly battery is labeled 200mAh and has a third wire attached for temperature monitoring. In this photo the text is clearly legible on the Atheros chip (click any photo to enlarge).

  • Atheros AR4100 integrated wifi module

55

This is the back of the board, where you can see the springy charging contacts, test points, and programming connector.

The flex PCB contains the ten LEDs used for different indications during Whistle's operation.

56

This photo makes it easier to read the labels on the non-Atheros chips.
In the photo above:

  • Upper right big square: Freescale MK60DN512 microprocessor
  • Upper left big rectangle: r32MB Spansion flash storage
  • Lowest big square: Texas Instruments CC2564 dual bluetooth/BTLE module
  • marked NXK: Texas Instruments lipoly charger
  • marked C3H: LIS3DH triple axis accelerometer
  • marked BYH: 3.3v and 1.8v buck converter

 

Inside the Narrative Clip

 

41

Plug the device into your computer to charge it up and upload the photos to the Narrative service, which then delivers the photos to the Narrative app (iOS/Android)

4442 43

45

What's inside this charming little square? We took apart the Narrative Clip to see what drives its camera and senses the world around it.

 

On the back of the clip, the black plastic is held securely in place by the metal clip. However it can be pried loose with the edge of a utility knife and delicately twisted away from the main body to reveal the 125mAh lipoly battery.

The metal clip is secured by two small hex screws.

46 47 48

After removing the metal clip, the flexible gasket and circuit board can be delicately removed from the front plastic enclosure, inside of which lives the GPS antenna.

49

We identified several of the chips on the board:

  • Atmel AT91SAM9G25 Arm processor
  • SanDisk SDIN7DU2-8G Flash card
  • Linear LTC3557 USB Power Manager with Li-Ion Charger and Three Step-Down Regulators
  • ST LIS3DH 3-axis accelerometer
  • CellGuide ACLYS GPS module
  • TI LC07A hex level shifter
  • MT 256Mb Memory (MT48H16M16LFBF-75)

50

Overview

21

It's summer and you're sweating and your hair's all frizzy and all you really want to know is why the weatherman said this morning that today's relative humidity would max out at a perfectly reasonable 52% when it feels more like 77%. Enter the HTU21D-F Temperature + Humidity Sensor - the best way to prove the weatherman wrong!

22

This I2C digital humidity sensor is an accurate and intelligent alternative to the much simplerHumidity and Temperature Sensor - SHT15 Breakout It has a typical accuracy of ±2% with an operating range that's optimized from 5% to 95% RH. Operation outside this range is still possible - just the accuracy might drop a bit. The temperature output has an accuracy of ±1°C from -30~90°C. If you're looking to measure temperature more accurately, we recommend the MCP9808 High Accuracy I2C Temperature Sensor Breakout Board.

23

Such a lovely chip - so we spun up a breakout board that includes the Filtered version (the white bit of plastic which is a PTFE filter to keep the sensor clean), a 3.3V regulator and I2C level shifting circuitry. This lets you use it safely with any kind of microcontroller with 3.3V-5V power or logic. Each order comes with one fully assembled and tested PCB breakout and a small piece of header. You'll need to solder the header onto the PCB but it's fairly easy and takes only a few minutes even for a beginner.

Pinouts

The HTU21D-F is a I2C sensor. That means it uses the two I2C data/clock wires available on most microcontrollers, and can share those pins with other sensors as long as they don't have an address collision. For future reference, the I2C address is 0x40 and you can't change it!

24

Power Pins:

  • Vin - this is the power pin. Since the chip uses 3 VDC, we have included a voltage regulator on board that will take 3-5VDC and safely convert it down. To power the board, give it the same power as the logic level of your microcontroller - e.g. for a 5V micro like Arduino, use 5V
  • 3v3 - this is the 3.3V output from the voltage regulator, you can grab up to 100mA from this if you like
  • GND - common ground for power and logic

I2C Logic pins:

  • SCL - I2C clock pin, connect to your microcontrollers I2C clock line.
  • SDA - I2C data pin, connect to your microcontrollers I2C data line.

Assembly

25

Prepare the header strip:

Cut the strip to length if necessary. It will be easier to solder if you insert it into a breadboard - long pins down

26

Add the breakout board:

Place the breakout board over the pins so that the short pins poke through the breakout pads

27

And Solder!

Be sure to solder all pins for reliable electrical contact.

(For tips on soldering, be sure to check out ourGuide to Excellent Soldering).

 

28 29

 

You're done! Check your solder joints visually and continue onto the next steps

30

Wiring & Test

You can easily wire this breakout to any microcontroller, we'll be using an Arduino. For another kind of microcontroller, just make sure it has I2C, then port the code - its pretty simple stuff!

31

  • Connect Vin to the power supply, 3-5V is fine. Use the same voltage that the microcontroller logic is based off of. For most Arduinos, that is 5V
  • Connect GND to common power/data ground
  • Connect the SCL pin to the I2C clock SCL pin on your Arduino. On an UNO & '328 based Arduino, this is also known as A5, on a Mega it is also known as digital 21 and on a Leonardo/Micro, digital 3
  • Connect the SDA pin to the I2C data SDA pin on your Arduino. On an UNO & '328 based Arduino, this is also known as A4, on a Mega it is also known as digital 20 and on a Leonardo/Micro, digital 2

The HTU21D-F has a default I2C address of 0x40 and cannot be changed!

Download Adafruit_HTU21DF

To begin reading sensor data, you will need to download Adafruit_HTU21DF_Library from our github repository. You can do that by visiting the github repo and manually downloading or, easier, just click this button to download the zip

Rename the uncompressed folder Adafruit_HTU21DF and check that the Adafruit_HTU21DF folder contains Adafruit_HTU21DF.cpp and Adafruit_HTU21DF.h

Place the Adafruit_HTU21DF library folder your arduinosketchfolder/libraries/ folder.
You may need to create the libraries subfolder if its your first library. Restart the IDE.

Load Demo

Open up File->Examples->Adafruit_HTU21DF->HTU21DFtest and upload to your Arduino wired up to the sensor

32

Thats it! Now open up the serial terminal window at 9600 speed to begin the test.

33

You can try breathing on the sensor to increase the humidity. The sensor reacts very fast!

Library Reference

The library we have is simple and easy to use

You can create the Adafruit_HTU21DF object with:

  1. Adafruit_HTU21DF htu = Adafruit_HTU21DF()

There are no pins to set since you must use the I2C bus!

Then initialize the sensor with:

  1. htu.begin()

this function returns True if the sensor was found and responded correctly and False if it was not found

Once initialized, you can query the temperature in °C with

  1. htu.readTemperature()

Which will return floating point (decimal + fractional) temperature. You can convert to Fahrenheit by multiplying by 1.8 and adding 32 as you have learned in grade school!

Reading the humidity is equally simple. Call

  1. htu.readHumidity()
to read the humidity also as a floating point value between 0 and 100 (this reads % humidity)

Downloads

Datasheet for the HTU21D-F (the -F part is for the PTFE Filter, which is the white insert on top of the sensor)

Schematics

34

PCB Print

Dimensions in Inches!

35

Overview

1

Fans of the BMP085/BMP180 will want to take a look at the new BMP183 - an SPI spin on the old familiar classic. This precision sensor from Bosch is the best low-cost sensing solution for measuring barometric pressure and temperature. Because pressure changes with altitude you can also use it as an altimeter! 2

The BMP183 is the next-generation of sensors from Bosch, and is the fraternal twin of the BMP180 - with a low altitude noise of 0.25m and the same fast conversion time. It has the same specifications, but uses SPI instead of I2C. This is great for users where there is an I2C address collision, they want more than one sensor on a single microcontroller, more flexibility on pin usage, or just prefer the simplicity of SPI.

3

The sensor is soldered onto a PCB and comes with a 3.3V regulator (so you can use it with 3-5V power), SPI level shifter (so you can use it with 3-5V logic).

Pinouts

4

Power Pins:

  • Vin - this is the power pin. Since the chip uses 3 VDC, we have included a voltage regulator on board that will take 3-5VDC and safely convert it down. To power the board, give it the same power as the logic level of your microcontroller - e.g. for a 5V micro like Arduino, use 5V
  • 3Vo - this is the 3.3V output from the voltage regulator, you can grab up to 100mA from this if you like
  • GND - common ground for power and logic

SPI Logic pins:

All pins going into the breakout have level shifting circuitry to make them 3-5V logic level safe. Use whatever logic level is on Vin!

  • SCK - This is the SPI Clock pin, its an input to the chip
  • SDO - this is the Serial Data Out / Master In Slave Out pin, for data sent from the BMP183 to your processor
  • SDI - this is the Serial Data In / Master Out Slave In pin, for data sent from your processor to the BMP183
  • CS - this is the Chip Select pin, drop it low to start an SPI transaction. Its an input to the chip
If you want to connect multiple BMP183's to one microcontroller, have them share the SDI, SDO and SCK pins. Then assign each one a unique CS pin.

Assembly

5

Prepare the header strip:

Cut the strip to length if necessary. It will be easier to solder if you insert it into a breadboard - long pins down

6

Add the breakout board:

Place the breakout board over the pins so that the short pins poke through the breakout pads7

And Solder!

Be sure to solder all pins for reliable electrical contact.

(For tips on soldering, be sure to check out our

8 9 10

You're done! Check your solder joints visually and continue onto the next steps

11

Wiring and Test

You can easily wire this breakout to any microcontroller, we'll be using an Arduino. For another kind of microcontroller, as long as you have 4 available pins it is possible to 'bit-bang SPI'. Check out the library, then port the code.

12

Since this is a SPI sensor, we can use hardware or 'software' SPI. To make wiring identical on all Arduinos, we'll begin with 'software' SPI. The following pins should be used:

  • Connect Vin to the power supply, 3V or 5V is fine. Use the same voltage that the microcontroller logic is based off of. For most Arduinos, that is 5V
  • Connect GND to common power/data ground
  • Connect the SCK pin to Digital #13 but any pin can be used later
  • Connect the SDO pin to Digital #12 but any pin can be used later
  • Connect the SDI pin to Digital #11 but any pin can be used later
  • Connect the CS pin Digital #10 but any pin can be used later

Later on, once we get it working, we can adjust the library to use hardware SPI if you desire, or change the pins to other

Download Adafruit_BMP183 library

To begin reading sensor data, you will need to download Adafruit_BMP183 from our github repository. You can do that by visiting the github repo and manually downloading or, easier, just click this button to download the zip

                                                                        Download Adafruit BMP183 library

Rename the uncompressed folder Adafruit_BMP183 and check that the Adafruit_BMP183 folder contains Adafruit_BMP183.cpp and Adafruit_BMP183.h

Place the Adafruit_BMP183 library folder your arduinosketchfolder/libraries/ folder.
You may need to create the libraries subfolder if its your first library. Restart the IDE.

Load Demo

Open up File->Examples->Adafruit_BMP183->BMP183test and upload to your Arduino wired up to the sensor

13

Once uploaded to your Arduino, open up the serial console at 9600 baud speed to see data being printed out

14

Temperature is calculated in degrees C, you can convert this to F by using the classic F = C * 9/5 + 32 equation.

Pressure is returned in the SI units of Pascals. 100 Pascals = 1 hPa = 1 millibar. Often times barometric pressure is reported in millibar or inches-mercury. For future reference 1 pascal =0.000295333727 inches of mercury, or 1 inch Hg = 3386.39 Pascal. So if you take the pascal value of say 100734 and divide by 3389.39 you'll get 29.72 inches-Hg.

You can also calculate Altitude. However, you can only really do a good accurate job of calculating altitude if you know the hPa pressure at sea level for your location and day! The sensor is quite precise but if you do not have the data updated for the current day then it can be difficult to get more accurate than 10 meters.

Library Reference

You can start out by creating a BMP183 object with either software SPI (where all four pins can be any I/O) using
  1. Adafruit_BMP183 bmp = Adafruit_BMP183(BMP183_CLK, BMP183_SDO, BMP183_SDI, BMP183_CS);
Or you can use hardware SPI. With hardware SPI you must use the hardware SPI pins for your Arduino - and each arduino type has different pins! Check the SPI reference to see what pins to use.
In this case, you can use any CS pin, but the other three pins are fixed
  1. Adafruit_BMP183 bmp = Adafruit_BMP183(BMP183_CS);
Once started, you can initialize the sensor with
  1. bmp.begin()
begin() will return True if the sensor was found, and False if not. If you get a False value back, check your wiring!
Reading temperature and pressure is easy, just call:
  1. bmp.getTemperature()
  2. bmp.getPressure()
Temperature is always a floating point, in Centigrade. Pressure is a 32 bit integer with the pressure in Pascals. You may need to convert to a different value to match it with your weather report

It's also possible to turn the BMP183 into an altimeter. If you know the pressure at sea level, the library can calculate the current barometric pressure into altitude

  1. bmp.getAltitude(seaLevelPressure)

However, you can only really do a good accurate job of calculating altitude if you know the hPa pressure at sea level for your location and day! The sensor is quite precise but if you do not have the data updated for the current day then it can be difficult to get more accurate than 10 meters.

Pass in the current sea level pressure in hPa - so the value will be somewhere around ~1000. You can also test with the generic 1013.25 value.

Using BMP183 Unified

The unified sensor library is for slightly more advanced users - it provides a more 'unified' structure for all sensors that Adafruit sells. It mimics the Android sensor platform, and is good for people who are comfortable with data structures.

Download Adafruit_BMP183_Unified library

To begin reading sensor data, you will need to download Adafruit_BMP183_U from our github repository. You can do that by visiting the github repo and manually downloading or, easier, just click this button to download the zip

Download BMP183 Unified Library

Rename the uncompressed folder Adafruit_BMP183_U and check that the Adafruit_BMP183_U folder contains Adafruit_BMP183_U.cpp and Adafruit_BMP183_U.h

Place the Adafruit_BMP183_U library folder your arduinosketchfolder/libraries/ folder.
You may need to create the libraries subfolder if its your first library. Restart the IDE.

Download Adafruit_Sensor

We also have a core sensor library that helps manage sensor readings. So, just like the BMP183 library, download Adafruit_Sensor

Download Adafruit_Sensor

Load Demo

Open up File->Examples->Adafruit_BMP180_Unified->BMP183test and upload to your Arduino wired up to the sensor

15

Upload & open up the serial console at 9600 to see the data printed out

16

F.A.Q.s

How come the altitude calculation is wrong? Is my BMP sensor broken?

No, your sensor is likely just fine. The altitude calculation depends on knowing the barometric pressure at sea level

If you do not set the correct sea level pressure for your location FOR THE CURRENT DAY it will not be able to calculate the altitude accurately

Barometric pressure at sea level changes daily based on the weather!

Downloads

17

PCB Fabrication Print

Dimensions in Inches

18

Overview

1

UFO Drones

This summer light up the night sky and fly safe with your drone. In this project, we'll show you how you can upgrade the IRIS quad copper with LED NeoPixel rings and 3d printed prop guards. These parts provide extra protection to your propellers and are extremely light weight.

What do I need to know?

If you've soldered a battery or wired up your own drone, you'll be surprised just how easy this project is! If your just starting out, here's a few guides to help you get started.

light_hero2-looping

Prerequisite Guides

  • Introducing Trinket
  • NeoPixel UberGuide
  • Collin's Lab: Soldering

You'll need a few tools and parts to get this project lit up.

Parts

  • 4 16xNeoPixel Rings
  • 1 Trinket 5V micro-controller
  • 1 1200mAh Lithium Polymer Battery
  • 1 PowerBoost 500
  • 1 IRIS autonomous multicopter

Tools & Supplies

  • 1 Wire Wrap Spool (3 separate colors are best!)
  • 1 Slide Switch
  • 2 JST Extension Cable
  • Soldering Iron
  • Solder
  • Heat Shrink Pack

3D Printing

 Download STLS

The tall legs and propeller guards are printed in high impact strength PET material to provide support. You can get a spool of T-Glaze filament from your favorite filament supplier.

TGLAZE 50c (heated bed) /230c extruder (40 extrude /50 travel speeds)
or 60c (heated bed) / 235c extruder (60 extrude /70 travel speeds)

PET+ 270c (50/60 speeds)

2

4 iris-prop-guard.stl
1 iris-box.stl
1 iris-cover.stl
4 iris-ring-cap.stl
4 iris-ring-clip.stl
4 iris-ring-holder.stl
ABS/PLA @240
TG @270
20% Infill
2 Shells
0.2 Layer height
5-6 hours for all pieces

iris-prop-guard.stl
The prop guard needs a minimum print build volume of 250mm x 150mm x 100mm. No raft or support needed. Fits IRIS classic.

iris+prop-guard-half-left.stl and iris+prop-guard-half-right.stl
Updated files for IRIS+. Guard must be printed in two parts to fit on most build platforms since the propellers are larger.

iris-box.stl
The box is designed to fit the 1200mAh battery, trinket, powerboost 500 and slide switch. No raft or support needed.

iris-cover.stl
This part is the cover to the enclosure box. No raft or support needed.

iris-ring-cap.stl
This part should be printed in translucent filament material to protect and diffuse the LED light from the NeoPixel rings.

iris-ring-clip.stl
This is the mount that clips onto the arm of the IRIS. It needs support material to print the overhanging parts.

iris-ring-holder.stl
This part is designed to house the 16x NeoPixel Ring. No raft or support needed.

Download tall legs and ARM mount

You can download the tall legs and arm mount for IRIS from thingiverse designed by Brendan22

Circuit Diagram

3

Circuit Diagram

The illustration is intended to be used only as a reference. The image above outlines each component and wired connections. The Trinket, Powerboost 500, 1200mAh lipo battery and switch slide will be housed inside the iris-box.stl part.

Prepping the Components

Before assembling 3D printed parts, you'll need to prepare the circuit. If this is your first project using NeoPixels and Arduino micro-controllers, it's a good idea to prototype your circuit with a breadboard.

Slide Switch Adapter

Shorten a JST extension cable to about 10mm long by cutting the positive and negative cables with wire cutters. Use wire stripers to strip the ends of the positive and negative wires. Apply a bit of rosin to the stripped ends and tin the tips of the wires. Add a piece of shrink tubing to the positive wire and solder them together by holding them in place with a third-helping-hand.

4

Trinket 5V

You will need to solder a female JST connection cable to the positive and negative power pads on the back of the PCB. This will allow you to plug in the male JST cable from the PowerBoost 500 5V out to the Trinket.

The following lists the pin outs for connecting the 5V Trinket to the 16x NeoPixel ring.

Trinket #0 to NeoRing IN
Trinket GND to NeoRing GND
Trinket BAT+ to NeoRing PWR

5

PowerBoost 500

Check out the PowerBoost introduction guide for more information on this module. In this circuit, you simply need to solder a male JST connection cable to the GND and 5V pins and connect that to the Trinket. The slide switch adapter will connect to the female EN (+) and GND (-) port on the PowerBoost 500.

NeoPixel Ring Chain

The four NeoPixel rings will be connected in a chain that will allow power, ground and data signal to distribute between them.

Each NeoPixel ring will need to share power and ground connections. The data pins are chained by connecting the first ring's OUT pin to the IN pin of the proceeding ring. You will need to measure the lengths of each wire so that they are long enough to chain together.

Powering 64 NeoPixel LEDs

In order to power all 4 of the 16x NeoPixel rings, we suggest using a Powerboost 500 module to increase the voltage of the 1200mAh lithium polymer battery from 3.7v to 5v. This will give better color over the long wires and high current draw.

Setting up Arduino IDE

You'll need the Adafruit Arduino IDE and the special config for using the Trinket. Follow theintroduction to Trinket guide for a full tutorial.

Once your Arduino IDE is setup for the 5V Trinket, create a new sketch. Paste in the example code. Goto file menu tools > Board > Adafruit Trinket 8Mhz. Then Tools > Programmer > USBtinyISP. Plug in a USB mini cable connecting your computer to the Trinket. Wait for the red LED to blink and get the upload code button.

Arduino Sketch

Use the code below to make the NeoPixel Ring LED's animate between two patterns. A spinning glow and a random spark effect.

  1. // Low power NeoPixel goggles example. Makes a nice blinky display
  2. // with just a few LEDs on at any time...uses MUCH less juice than
  3. // rainbow display!
  4.  
  5. #include <Adafruit_NeoPixel.h>
  6.  
  7. #define PIN 0
  8.  
  9. Adafruit_NeoPixel pixels = Adafruit_NeoPixel(64, PIN);
  10.  
  11. uint8_t mode = 1, // Current animation effect
  12. offset = 0; // Position of spinny eyes
  13. uint32_t color = 0x00ffe6; // Start red
  14. uint32_t prevTime;
  15.  
  16. void setup() {
  17. pixels.begin();
  18. pixels.setBrightness(255); // 1/3 brightness
  19. prevTime = millis();
  20. }
  21.  
  22. void loop() {
  23. uint8_t i;
  24. uint32_t t;
  25.  
  26. switch(mode) {
  27.  
  28. case 0: // Random sparks - just one LED on at a time!
  29. i = random(64);
  30. pixels.setPixelColor(i, color);
  31. pixels.show();
  32. delay(10);
  33. pixels.setPixelColor(i, 64);
  34. break;
  35. case 1: // Spinny wheels (8 LEDs on at a time)
  36. for(i=0; i<64; i++) {
  37. uint32_t c = 0;
  38. if(((offset + i) & 7) < 4) c = color; // 4 pixels on...
  39. pixels.setPixelColor( i, c); // First eye
  40. pixels.setPixelColor(32-i, c); // Second eye (flipped)
  41. }
  42. pixels.show();
  43. offset++;
  44. delay(40);
  45. break;
  46. }
  47.  
  48. t = millis();
  49. if((t - prevTime) > 8000) { // Every 8 seconds...
  50. mode++; // Next mode
  51. if(mode > 1) { // End of modes?
  52. mode = 0; // Start modes over
  53. color >>= 0 ; // Next color R->G->B
  54. if(!color) color = 0x00ffe6; // Reset to red
  55. }
  56. for(i=0; i<16; i++) pixels.setPixelColor(i, 0);
  57. prevTime = t;
  58. }
  59. }

Assembly

6

Prep 3D Printed Parts

Start by using flat pliers to remove the support material from the iris-box.stl enclosure. Grip onto a chuck of material, twist and pull off all the supports underneath the slide switch clips, usb holes, and all four screw mounts.

7

Carefully insert the slide switch adapter side-ways into the opening from inside the enclosure.

8

Solder Wires to Trinket

Position the Trinket inside the enclosure and align the enclosure over the bottom of the IRIS. Measure and cut three wires that will be needed to connect the first NeoPixel ring to the Trinket. Use a panavise jr. to assist holding the Trinket in place while your solder.

9

Fit Wires Inside Enclosure

Carefully insert the three wires through the slit and hole, on the side of the enclosure.

10

Mount Trinket to enclosure

Remove the support material around the slide switch and USB opening. Align the USB port on the Trinket to the USB port hole on the enclosure and use two 2.9mm (#4 x 3/8') plat phillips screws to secure it to the enclosure.

11

Make sure to tightly fasten the screw so that its flush with the outside of the enclosure box.

12

Mount Enclosure to IRIS

Position the enclosure on to the bottom of IRIS and line up the mounting holes near the battery door. Use two 3.4mm(#6-32 x 1/2') flat phillips screws with nut to attach the box to the body.

13

Install Power Circuit

Insert the 1200mAh lithium polymer battery into the enclosure with the corners fitting under the tabs and plug it into the slide switch adapter.

14

Place the Power Boost 500 on top of the battery and connect it to the Slide Switch and Trinket.

15

Sealing Enclosure

Adjust the wires and components inside the enclosure, close and snap shut the enclosure. Use 4 (#4 x 3/8') phillips screws to securely close the iris-cover.stl to the iris-box.stl part.

16

Install Mount Adapters

Attach iris-ring-clip.stl by fitting it through the bottom of each leg.

17

Clip the hooks on to the top of the prop arms by angling the clips up higher.

18

Once both hooks are snapped into the prop arm, push the front part of the ring clip on to the logo cutout. It should click into place.

19

Install the iris-ring-holder.stl part on to the bottom of the iris-ring-clip.stl part. Use the #6-32x1/2' flat phillips screws with nuts to join the two mounts together and add a nut to secure the mount.

20

Wiring First NeoPixel Ring

Choose an arm you'd wish to house the first NeoPixel ring and measure the lengths of wire that will be needed to reach the enclosure box. Solder three wires to the IN, GND and PWR pin on the NeoPixel ring. These three wires need to be soldered to the on the D0, GND and 5V pins on the 5V Trinket. Use a panovise jr. to hold the NeoPixel ring in place while you solder.

21

Hide the Wires

Pop off the clips holding the wires on the bottom of each arm and tuck the wires from the NeoPixel ring in the cavity and secure them with the clips. A flat head screw driver can assist with removing the clips.

22

Fit NeoPixel Wiring into Mount

Slide the wires through the slit of the opening in the iris-ring-holder.stl and position the 3 wires in so it doesn't kink when you press the NeoPixel ring into the part.

23

Install NeoPixel Ring into Mount

Place the NeoPixel Ring inside the iris-ring-holder.stl. Make sure all of the wires are tucked inside the holder carefully, try not to bend or kink!

24

Install Tall Legs

Make space for the legs near the ends of the arms by moving the wire clips after the Leg mounts.

25

Install Prop Guards

Place the prop guards between iris-ring-clip.stl and iris-ring-holder.stl

26

Secure Mounts

Use the 3.4mm screws to secure all three pieces together.

27

Tighten the nut to lock all three parts into place.

28

Install LED Diffuser

Slip the diffuser cover over the top of the rings and snap it on to iris-ring-holder.stl

29

Conceal Wiring and Tidy Up

Use a couple pieces of electrical tape to secure and hide all to the wires.

 

1

Overview

1

When the future is dazzlingly-bright, this ultra-high-range luminosity sensor will help you measure it. The TSL2591 luminosity sensor is an advanced digital light sensor, ideal for use in a wide range of light situations. Compared to low cost CdS cells, this sensor is more precise, allowing for exact lux calculations and can be configured for different gain/timing ranges to detect light ranges from up to 188uLux up to 88,000 Lux on the fly.

The best part of this sensor is that it contains both infrared and full spectrum diodes! That means you can separately measure infrared, full-spectrum or human-visible light. Most sensors can only detect one or the other, which does not accurately represent what human eyes see (since we cannot perceive the IR light that is detected by most photo diodes)

2

This sensor is much like the TSL2561 but with a wider range (and the interface code is different). This sensor has a massive 600,000,000:1 dynamic range! Unlike the TSL2561 you cannot change the I2C address either, so keep that in mind.

3

The built in ADC means you can use this with any microcontroller, even if it doesn't have analog inputs. The current draw is extremely low, so its great for low power data-logging systems. about 0.4mA when actively sensing, and less than 5 uA when in power-down mode.

Pinouts

The TSL2591 is a I2C sensor. That means it uses the two I2C data/clock wires available on most microcontrollers, and can share those pins with other sensors as long as they don't have an address collision. For future reference, the I2C address is 0x29 and you can't change it!

4

Power Pins:

  • Vin - this is the power pin. Since the chip uses 3 VDC, we have included a voltage regulator on board that will take 3-5VDC and safely convert it down. To power the board, give it the same power as the logic level of your microcontroller - e.g. for a 5V micro like Arduino, use 5V
  • 3vo - this is the 3.3V output from the voltage regulator, you can grab up to 100mA from this if you like
  • GND - common ground for power and logic

I2C Logic pins:

  • SCL - I2C clock pin, connect to your microcontrollers I2C clock line.
  • SDA - I2C data pin, connect to your microcontrollers I2C data line.

Other Pins:

  • INT - this is the INTerrupt pin from the sensor. It can be programmed to do a couple different things by noodling with the i2c registers. For example trigger when a conversion is done, or when the light level has changed a lot, etc. We don't have library support for this pin

Assembly

5

Prepare the header strip:

Cut the strip to length if necessary. It will be easier to solder if you insert it into a breadboard - long pins down

6

Add the breakout board:

Place the breakout board over the pins so that the short pins poke through the breakout pads

7

And Solder!

Be sure to solder all pins for reliable electrical contact.

(For tips on soldering, be sure to check out our

8

9

10

You're done! Check your solder joints visually and continue onto the next steps

11

Wiring & Test

You can easily wire this breakout to any microcontroller, we'll be using an Arduino. For another kind of microcontroller, just make sure it has I2C, then port the code - its pretty simple stuff!

12

  • Connect Vin to the power supply, 3-5V is fine. Use the same voltage that the microcontroller logic is based off of. For most Arduinos, that is 5V
  • Connect GND to common power/data ground
  • Connect the SCL pin to the I2C clock SCL pin on your Arduino. On an UNO & '328 based Arduino, this is also known as A5, on a Mega it is also known as digital 21 and on a Leonardo/Micro, digital 3
  • Connect the SDA pin to the I2C data SDA pin on your Arduino. On an UNO & '328 based Arduino, this is also known as A4, on a Mega it is also known as digital 20 and on a Leonardo/Micro, digital 2

The TSL2591 has a default I2C address of 0x29 and cannot be changed!

Download Adafruit_TSL2591

To begin reading sensor data, you will need to download Adafruit_TSL2591_Library from our github repository. You can do that by visiting the github repo and manually downloading or, easier, just click this button to download the zip

Rename the uncompressed folder Adafruit_TSL2591 and check that the Adafruit_TSL2591 folder contains Adafruit_TSL2591.cpp and Adafruit_TSL2591.h

Place the Adafruit_TSL2591 library folder your arduinosketchfolder/libraries/ folder.
You may need to create the libraries subfolder if its your first library. Restart the IDE.

We also have a great tutorial on Arduino library installation at:
http://learn.adafruit.com/adafruit-all-about-arduino-libraries-install-use

Download Adafruit_Sensor

The TSL2591 library uses the Adafruit_Sensor support backend so that readings can be normalized between sensors. You can grab Adafruit_Sensor from the github repo or just click the button below.

Install like you did with Adafruit_TSL2591

Load Demo

Open up File->Examples->Adafruit_TSL2591->tsl2591 and upload to your Arduino wired up to the sensor

13

Thats it! Now open up the serial terminal window at 9600 speed to begin the test.

14

Try covering with your hand or shining a lamp onto the sensor to experiment with the light levels!

Library Reference

The Adafruit_TSL2591 library contains a number of public functions to help you get started with this sensor.

Constructor

To create an instance of the Adafruit_TSL2591 driver, simple declare an appropriate object, along with a 32-bit numeric value to identify this sensor (in case you have several TSL2591s and want to track them separately in a logging system).

  1. Adafruit_TSL2591 tsl = Adafruit_TSL2591(2591);

Gain and Timing

You can adjust the gain settings and integration time of the sensor to make it more or less sensitive to light, depending on the environment where the sensor is being used.

The gain can be set to one of the following values (though the last value, MAX, has limited use in the real world given the extreme amount of gain applied):

  • TSL2591_GAIN_LOW: Sets the gain to 1x (bright light)
  • TSL2591_GAIN_MEDIUM: Sets the gain to 25x (general purpose)
  • TSL2591_GAIN_HIGH: Sets the gain to 428x (low light)
  • TSL2591_GAIN_MAX: Sets the gain to 9876x (extremely low light)

Gain can be read or set via the following functions:

  • void setGain(tsl2591Gain_t gain);
  • tsl2591Gain_t getGain();

The integration time can be set between 100 and 600ms, and the longer the integration time the more light the sensor is able to integrate, making it more sensitive in low light the longer the integration time. The following values can be used:

  • TSL2591_INTEGRATIONTIME_100MS
  • TSL2591_INTEGRATIONTIME_200MS
  • TSL2591_INTEGRATIONTIME_300MS
  • TSL2591_INTEGRATIONTIME_400MS
  • TSL2591_INTEGRATIONTIME_500MS
  • TSL2591_INTEGRATIONTIME_600MS

The integration time can be read or set via the following functions:

  • void setTiming (tsl2591IntegrationTime_t integration);
  • tsl2591IntegrationTime_t getTiming();

An example showing how these functions are used can be seen in the code below:

  1. /**************************************************************************/
  2. /*
  3. Configures the gain and integration time for the TSL2561
  4. */
  5. /**************************************************************************/
  6. void configureSensor(void)
  7. {
  8. // You can change the gain on the fly, to adapt to brighter/dimmer light situations
  9. //tsl.setGain(TSL2591_GAIN_LOW); // 1x gain (bright light)
  10. tsl.setGain(TSL2591_GAIN_MED); // 25x gain
  11. //tsl.setGain(TSL2591_GAIN_HIGH); // 428x gain
  12. // Changing the integration time gives you a longer time over which to sense light
  13. // longer timelines are slower, but are good in very low light situtations!
  14. tsl.setTiming(TSL2591_INTEGRATIONTIME_100MS); // shortest integration time (bright light)
  15. //tsl.setTiming(TSL2591_INTEGRATIONTIME_200MS);
  16. //tsl.setTiming(TSL2591_INTEGRATIONTIME_300MS);
  17. //tsl.setTiming(TSL2591_INTEGRATIONTIME_400MS);
  18. //tsl.setTiming(TSL2591_INTEGRATIONTIME_500MS);
  19. //tsl.setTiming(TSL2591_INTEGRATIONTIME_600MS); // longest integration time (dim light)
  20.  
  21. /* Display the gain and integration time for reference sake */
  22. Serial.println("------------------------------------");
  23. Serial.print ("Gain: ");
  24. tsl2591Gain_t gain = tsl.getGain();
  25. switch(gain)
  26. {
  27. case TSL2591_GAIN_LOW:
  28. Serial.println("1x (Low)");
  29. break;
  30. case TSL2591_GAIN_MED:
  31. Serial.println("25x (Medium)");
  32. break;
  33. case TSL2591_GAIN_HIGH:
  34. Serial.println("428x (High)");
  35. break;
  36. case TSL2591_GAIN_MAX:
  37. Serial.println("9876x (Max)");
  38. break;
  39. }
  40. Serial.print ("Timing: ");
  41. Serial.print((tsl.getTiming() + 1) * 100, DEC);
  42. Serial.println(" ms");
  43. Serial.println("------------------------------------");
  44. Serial.println("");
  45. }

Unified Sensor API

The Adafruit_TSL2591 library makes use of the Adafruit unified sensor framework to provide sensor data in a standardized format and scale. If you wish to make use of this framweork, the two key functions that you need to work with are getEvent and getSensor, as described below:

void getEvent(sensors_event_t*)

This function will read a single sample from the sensor and return it in a generic sensors_event_t object. To use this function, you simply pass in a sensors_event_t reference, which will be populated by the function, and then read the results, as shown in the following code:

  1. /**************************************************************************/
  2. /*
  3. Performs a read using the Adafruit Unified Sensor API.
  4. */
  5. /**************************************************************************/
  6. void unifiedSensorAPIRead(void)
  7. {
  8. /* Get a new sensor event */
  9. sensors_event_t event;
  10. tsl.getEvent(&event);
  11. /* Display the results (light is measured in lux) */
  12. Serial.print("[ "); Serial.print(event.timestamp); Serial.print(" ms ] ");
  13. if ((event.light == 0) |
  14. (event.light > 4294966000.0) |
  15. (event.light <-4294966000.0))
  16. {
  17. /* If event.light = 0 lux the sensor is probably saturated */
  18. /* and no reliable data could be generated! */
  19. /* if event.light is +/- 4294967040 there was a float over/underflow */
  20. Serial.println("Invalid data (adjust gain or timing)");
  21. }
  22. else
  23. {
  24. Serial.print(event.light); Serial.println(" lux");
  25. }
  26. }
Note that some checks need to be performed on the sensor data in case the sensor saturated. If saturation happens, please adjust the gain and integration time up or down to change the sensor's sensitivity and output range.

void getSensor(sensor_t*)

This function returns some basic information about the sensor, and operates in a similar fashion to getEvent. You pass in an empty sensor_t reference, which will be populated by this function, and we can then read the results and retrieve some key details about the sensor and driver, as shown in the code below:

  1. /**************************************************************************/
  2. /*
  3. Displays some basic information on this sensor from the unified
  4. sensor API sensor_t type (see Adafruit_Sensor for more information)
  5. */
  6. /**************************************************************************/
  7. void displaySensorDetails(void)
  8. {
  9. sensor_t sensor;
  10. tsl.getSensor(&sensor);
  11. Serial.println("------------------------------------");
  12. Serial.print ("Sensor: "); Serial.println(sensor.name);
  13. Serial.print ("Driver Ver: "); Serial.println(sensor.version);
  14. Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id);
  15. Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println(" lux");
  16. Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println(" lux");
  17. Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println(" lux");
  18. Serial.println("------------------------------------");
  19. Serial.println("");
  20. delay(500);
  21. }

Raw Data Access API

If you don't wish to use the Unified Sensor API, you can access the raw data for this sensor via the following three functions:

  • uint16_t getLuminosity (uint8_t channel );
  • uint32_t getFullLuminosity ( );
  • uint32_t calculateLux ( uint16_t ch0, uint16_t ch1 );

getLuminosity can be used to read either the visible spectrum light sensor, or the infrared light sensor. It will return the raw 16-bit sensor value for the specified channel, as shown in the code below:

  1. /**************************************************************************/
  2. /*
  3. Shows how to perform a basic read on visible, full spectrum or
  4. infrared light (returns raw 16-bit ADC values)
  5. */
  6. /**************************************************************************/
  7. void simpleRead(void)
  8. {
  9. // Simple data read example. Just read the infrared, fullspecrtrum diode
  10. // or 'visible' (difference between the two) channels.
  11. // This can take 100-600 milliseconds! Uncomment whichever of the following you want to read
  12. uint16_t x = tsl.getLuminosity(TSL2591_VISIBLE);
  13. //uint16_t x = tsl.getLuminosity(TSL2561_FULLSPECTRUM);
  14. //uint16_t x = tsl.getLuminosity(TSL2561_INFRARED);
  15.  
  16. Serial.print("[ "); Serial.print(millis()); Serial.print(" ms ] ");
  17. Serial.print("Luminosity: ");
  18. Serial.println(x, DEC);
  19. }
getFullLuminosity reads both the IR and full spectrum sensors at the same time to allow tigher correlation between the values, and then separates them in SW. The function returns a 32-bit value which needs to be split into two 16-bit values, as shown in the code below:
  1. /**************************************************************************/
  2. /*
  3. Show how to read IR and Full Spectrum at once and convert to lux
  4. */
  5. /**************************************************************************/
  6. void advancedRead(void)
  7. {
  8. // More advanced data read example. Read 32 bits with top 16 bits IR, bottom 16 bits full spectrum
  9. // That way you can do whatever math and comparisons you want!
  10. uint32_t lum = tsl.getFullLuminosity();
  11. uint16_t ir, full;
  12. ir = lum >> 16;
  13. full = lum & 0xFFFF;
  14. Serial.print("[ "); Serial.print(millis()); Serial.print(" ms ] ");
  15. Serial.print("IR: "); Serial.print(ir); Serial.print(" ");
  16. Serial.print("Full: "); Serial.print(full); Serial.print(" ");
  17. Serial.print("Visible: "); Serial.print(full - ir); Serial.print(" ");
  18. Serial.print("Lux: "); Serial.println(tsl.calculateLux(full, ir));
  19. }

calculateLux can be used to take both the infrared and visible spectrum sensor data and roughly correlate with the equivalent SI lux value, based on a formula from the silicon vendor that takes into account the sensor properties and the integration time and gain settings of the device.

To calculate the lux, simple call calculateLux(full, ir), where 'full' and 'ir' are raw 16-bit values taken from one of the two raw data functions above. See the code sample above for an example of calculating lux.

Downloads Datasheets

15

Layout

(Dimensions are in Inches)

16

 

Overview

21

Add lots of touch sensors to your next microcontroller project with this easy-to-use 12-channel capacitive touch sensor breakout board, starring the MPR121. This chip can handle up to 12 individual touch pads.

22

The MPR121 has support for only I2C, which can be implemented with nearly any microcontroller. You can select one of 4 addresses with the ADDR pin, for a total of 48 capacitive touch pads on one I2C 2-wire bus. Using this chip is a lot easier than doing the capacitive sensing with analog inputs: it handles all the filtering for you and can be configured for more/less sensitivity.

23

This sensor comes as a tiny hard-to-solder chip so we put it onto a breakout board for you. Since it's a 3V-only chip, we added a 3V regulator and I2C level shifting so its safe to use with any 3V or 5V microcontroller/processor like Arduino. We even added an LED onto the IRQ line so it will blink when touches are detected, making debugging by sight a bit easier on you. Comes with a fully assembled board, and a stick of 0.1" header so you can plug it into a breadboard. For contacts, we suggest using copper foil or pyralux, then solder a wire that connects from the foil pad to the breakout.

Pinouts

 

24

The little chip in the middle of the PCB is the actual MPR121 sensor that does all the capacitive sensing and filtering. We add all the extra components you need to get started, and 'break out' all the other pins you may want to connect to onto the PCB. For more details you can check out the schematics in the Downloads page.

Power Pins

The sensor on the breakout requires 3V power. Since many customers have 5V microcontrollers like Arduino, we tossed a 3.3V regulator on the board. Its ultra-low dropout so you can power it from 3.3V-5V just fine.

  • Vin - this is the power pin. Since the chip uses 3 VDC, we have included a voltage regulator on board that will take 3-5VDC and safely convert it down. To power the board, give it the same power as the logic level of your microcontroller - e.g. for a 5V micro like Arduino, use 5V
  • 3Vo - this is the 3.3V output from the voltage regulator, you can grab up to 100mA from this if you like
  • GND - common ground for power and logic

I2C Pins

  • SCL - I2C clock pin, connect to your microcontrollers I2C clock line.
  • SDA - I2C data pin, connect to your microcontrollers I2C data line.

IRQ and ADDR Pins

  • ADDR is the I2C address select pin. By default this is pulled down to ground with a 100K resistor, for an I2C address of 0x5A. You can also connect it to the 3Vo pin for an address of 0x5B, the SDA pin for 0x5C or SCL for address 0x5D
  • IRQ is the Interrupt Request signal pin. It is pulled up to 3.3V on the breakout and when the sensor chip detects a change in the touch sense switches, the pin goes to 0V until the data is read over i2c

Assembly

23

Prepare the header strip:

Cut the strip to length if necessary. It will be easier to solder if you insert it into a breadboard - long pins down

25

Add the breakout board:

Place the breakout board over the pins so that the short pins poke through the breakout pads

26

And Solder!

Be sure to solder all pins for reliable electrical contact.

27

28

You're done! Check your solder joints visually and continue onto the next steps

Wiring

You can easily wire this breakout to any microcontroller, we'll be using an Arduino. For another kind of microcontroller, just make sure it has I2C, then port the code - its pretty simple stuff!

29

  • Connect Vin to the power supply, 3-5V is fine. Use the same voltage that the microcontroller logic is based off of. For most Arduinos, that is 5V
  • Connect GND to common power/data ground
  • Connect the SCL pin to the I2C clock SCL pin on your Arduino. On an UNO & '328 based Arduino, this is also known as A5, on a Mega it is also known as digital 21 and on a Leonardo/Micro, digital 3
  • Connect the SDA pin to the I2C data SDA pin on your Arduino. On an UNO & '328 based Arduino, this is also known as A4, on a Mega it is also known as digital 20 and on a Leonardo/Micro, digital 2

The MPR121 ADDR pin is pulled to ground and has a default I2C address of 0x5A
You can adjust the I2C address by connecting ADDR to other pins:

  • ADDR not connected: 0x5A
  • ADDR tied to 3V: 0x5B
  • ADDR tied to SDA: 0x5C
  • ADDR tied to SCL: 0x5D

We suggest sticking with the default for the test demo, you can always change it later.

Download Adafruit_MPR121

To begin reading sensor data, you will need to download Adafruit_MPR121_Library from our github repository. You can do that by visiting the github repo and manually downloading or, easier, just click this button to download the zip

Rename the uncompressed folder Adafruit_MPR121 and check that the Adafruit_MPR121 folder contains Adafruit_MPR121.cpp and Adafruit_MPR121.h

Place the Adafruit_MPR121 library folder your arduinosketchfolder/libraries/ folder.
You may need to create the libraries subfolder if its your first library. Restart the IDE.

We also have a great tutorial on Arduino library installation at:
http://learn.adafruit.com/adafruit-all-about-arduino-libraries-install-use

Load Demo

Open up File->Examples->Adafruit_MPR121->MPR121test and upload to your Arduino wired up to the sensor

30

Thats it! Now open up the serial terminal window at 9600 speed to begin the test.

31

Make sure you see the "MPR121 found!" text which lets you know that the sensor is wired correctly.

Now touch the 12 pads with your fingertip to activate the touch-detection

32

For most people, that's all you'll need! Our code keeps track of the 12 'bits' for each touch and has logic to let you know when a contect is touched or released.

If you're feeling more advanced, you can see the 'raw' data from the chip. Basically, what it does it keep track of the capacitance it sees with "counts". There's some baseline count number that depends on the temperature, humidity, PCB, wire length etc. Where's a dramatic change in number, its considered that a person touched or released the wire.

Comment this "return" line to activate that mode:

  1. // comment out this line for detailed data from the sensor!
  2. return;

Then reupload. Open up the serial console again - you'll see way more text

Each reading has 12 columns. One for each sensor, #0 to #11. There's two rows, one for the 'baseline' and one for the current filtered data reading. When the current reading is within about 12 counts of the baseline, that's considered untouched. When the reading is more than 12 counts smaller than the baseline, the chi

p reports a touch.37
Most people don't need raw data too much, but it can be handy if doing intense debugging. It can be helpful if you are tweaking your sensors to get good responsivity.

Library Reference

Since the sensors use I2C, there's no pins to be defined during instantiation. You can just use:

Adafruit_MPR121 cap = Adafruit_MPR121();

When you initialize the sensor, pass in the I2C address. It can range from 0x5A (default) to 0x5D

cap.begin(0x5A)

begin() returns true if the sensor was found on the I2C bus, and false if not.

Touch detection

99% of users will be perfectly happy just querying what sensors are currentlt touched. You can read all at once with
cap.touched()
Which returns a 16 bit value. Each of the bottom 12 bits refers to one sensor. So if you want to test if the #4 is touched, you can use

if (cap.touched() & (1 << 4)) { do something }

You can check its not touched with:

if (! (cap.touched() & (1 << 4)) ) { do something }

Raw Data

You can grab the current baseline and filtered data for each sensor with

filteredData(sensornumber);
baselineData(sensornumber);

It returns a 16-bit number which is the number of counts, there's no unit like "mg" or "capacitance". The baseline is initialized to the current ambient readings when the sensor begin() is called - you can always reinitialize by re-calling begin()! The baseline will drift a bit, that's normal! It is trying to compensate for humidity and other environmental changes.

If you need to change the threshholds for touch detection, you can do that with

setThreshholds(uint8_t touch, uint8_t release)

By default, the touch threshhold is 12 counts, and the release is 6 counts. It's reset to these values whenever you call begin() by the way.

Electrodes

38

Once you have the MPR121 breakout working you'll want to construct electrodes. These are large conductive piece of copper, foil, paint, etc that will act as the "thing you touch"

Remember that electrodes must be electrically conductive! We suggest copper foil tape, conductive fabrics, ITO, pyralux flex PCB, etc. We have tons of great conductive materials in our Materials category. Some can be soldered to, others can be clipped to with alligator chips.

Remember, it doesn't have to be metal to be electrically conductive. Other things that work are tap or salt water, many kinda of food, even fruit!

We suggest soldering a wire to the electrode pad on the breakout and then soldering or clipping it to whatever you want your electrode to be.

This means that whenever you attach an alligator clip, or a large piece of copper, or whatever your electrode is, the capacitive sense chip will detect it and may think you're touching it. What you have to do is recalibrate the sensor. The easiest way to do that is to restart the python sketch since calibration is done when the chip is initialized. So, basically...

connect all your wires, electrodes, fruit, etc...then start up the capacitive touch program!

Downloads Datasheets

Breakout Board Schematic

39

Fabrication Print

Dimensions in Inches

40

 

Overview

1

Unlike most of the other temperature sensors we have, this breakout has a really cool IR sensor from TI that can measure the temperature of an object without touching it.

The TMP007 is the latest thermopile sensor from TI, and is an update of the TMP006. The internal math engine does all the temperature calculations so its easier to integrate - you can read the die and target temperatures directly over I2C. The TMP007 also has better transient management, so you don't get as much over/undershoot when the temperature changes a lot.

2

Simply point the sensor towards what you want to measure and it will detect the temperature by absorbing IR waves emitted. The embedded thermopile sensor generates a very very small voltage depending on how much IR there is, and using some math, that micro voltage can be used to calculate the temperature. It also takes the measurement over an area so it can be handy for determining the average temperature of something.

3

This sensor comes as a ultra-small 0.5mm pitch BGA, too hard to solder by hand. So we stuck it on an easy-to-work-with breakout board. The sensor works with 2.5V to 5V logic so it requires no logic level shifting. There are two address pins and using a funky method of connecting the pins you can have up to 8 TMP007's connected to one i2c bus. We also include a small piece of 0.1" breakaway header so you can easily solder to and use this sensor on a breadboard. Two mounting holes make it easy to attach to an enclosure.

Pinouts

4

5

Assembly

6

Prepare the header strip:

Cut the strip to length if necessary. It will be easier to solder if you insert it into a breadboard - long pins down

7

Add the breakout board:

Place the breakout board over the pins so that the short pins poke through the breakout pads

8

And Solder!

Be sure to solder all pins for reliable electrical contact.

9

10 11

You're done! Check your solder joints visually and continue onto the next steps

12

Arduino Wiring

You can easily wire this sensor to any microcontroller, we'll be using an Arduino

13

  • Connect Vdd to the power supply, 3V or 5V is fine. Use the same voltage that the microcontroller logic is based off of. For most Arduinos, that is 5V
  • Connect GND to common power/data ground
  • Connect the SCL pin to the I2C clock SCL pin on your Arduino. On an UNO & '328 based Arduino, this is also known as A5, on a Mega it is also known as digital 21 and on a Leonardo/Micro, digital 3
  • Connect the SDA pin to the I2C data SDA pin on your Arduino. On an UNO & '328 based Arduino, this is also known as A4, on a Mega it is also known as digital 20 and on a Leonardo/Micro, digital 2

The TMP007 has a default I2C address of 0x40 but you can set the address to any of 8 values between 0x40 and 0x47 so you can have up to 8 of these sensors all sharing the same SCL/SDA pins.

Download Adafruit_TMP007

To begin reading sensor data, you will need to download Adafruit_TMP007 from our github repository. You can do that by visiting the github repo and manually downloading or, easier, just click this button to download the zip

Rename the uncompressed folder Adafruit_TMP007 and check that the Adafruit_TMP007 folder contains Adafruit_TMP007.cpp and Adafruit_TMP007.h

Place the Adafruit_TMP007 library folder your arduinosketchfolder/libraries/ folder.
You may need to create the libraries subfolder if its your first library. Restart the IDE.

Load Demo

Open up File->Examples->Adafruit_TMP007->tmp007 and upload to your Arduino wired up to the sensor

14

Thats it! Now open up the serial terminal window at 9600 speed to see the temperature in real time. You can try putting your hand or a cold glass of water over the sensor (not touching) to see the thermopile sensor adjust!

15

Library Reference
The TMP007 library is pretty straight forward! Start by creating the Adafruit_TMP007 object with:
  1. Adafruit_TMP007 tmp007;
Or with an i2c address assigned
  1. Adafruit_TMP007 tmp007(0x41); // start with a diferent i2c address!
Then you can initialize & configure
  1. tmp007.begin()
or, to set the samples/reading with:
  1. tmp007.begin(TMP007_CFG_1SAMPLE)
We suggest the default, 16 samples for best accuracy. begin() will return true or false based on whether it found the sensor, check it using an if statment like so:
  1. if (! tmp007.begin()) {
  2. Serial.println("No sensor found");
  3. while (1);
  4. }
Now you can read the Die temperature (the temperature of the physical sensor itself) and Object temperature (the temperature of the stuff in front of the sensor)
  1. tmp007.readObjTempC();
  2. tmp007.readDieTempC();

The readings are floating point values, in degrees C.

Then wait 4 seconds between readings to get a new reading!

  1. delay(4000); // 4 seconds per reading for 16 samples per reading

Downloads Datasheet

16

PCB Fabrication Print

Dimensions in Inches

17

 

Overview

1

Add motion, direction and orientation sensing to your Arduino project with this all-in-one 9-DOF sensor. Inside the chip are three sensors, one is a classic 3-axis accelerometer, which can tell you which direction is down towards the Earth (by measuring gravity) or how fast the board is accelerating in 3D space. The other is a 3-axis magnetometer that can sense where the strongest magnetic force is coming from, generally used to detect magnetic north. The third is a 3-axis gyroscope that can measure spin and twist. By combining this data you can REALLY orient yourself.

2

When we saw the new LSM9DS0 from ST micro we thought - wow this could really make for a great breakout, at a very nice price! Design your own activity or motion tracker with all the data... We spun up a breakout board and Flora breakout that has all the extra circuitry you'll want, depending on whether you are using it with the Adafruit Flora or an Arduino (or other microcontroller)

3

The breakout board version of this sensor has both I2C and SPI interfaces. Attaching it to the Arduino is simple, power Vin and GND with 3-5VDC, and wire up I2C data on SCL and SDA, and you're ready to go! More advanced users can use SPI, our library has support for both. The breakout comes fully assembled and tested, with some extra header so you can use it on a breadboard. Four mounting holes make for a secure connection, and we put the popular power+data pins on one side, and the interrupt pins on the other side for a nice & compact breakout.

4

The Flora version has just I2C interface for a super-small design. Attaching it to the FLORA is simple: line up the sensor so its adjacent to the SDA/SCL pins and sew conductive thread from the 3V, SDA, SCL and GND pins. They line up perfectly so you will not have any crossed lines. You can only connect one of these sensors to your FLORA, but you can connect other I2C sensors/outputs by using the set of SCL/SDA pins on the opposite side.

Pinouts

We have two versions of this sensor, a compact and sewable Flora sensor and also a more extensive breadboard-friendly breakout. They use the same chip sensor, of course, and the same firmware code. However there's some differences about the pinouts!

Flora Sewable Version Pinouts

5

Power Pins

There's two power pins, 3V and GND. The 3V has to be regulated 'cleanly' from the Flora. There's no on-board polarity or regulation! The GND pin is the ground for both power and signal.

Data pins

Flora uses a chainable I2C data path for sensors, all the sensors share the same SCL and SDA pins. These pins have 10K pullups to 3V but they do not have level shifting so they are only for use with 3V logic boards such as Flora!

Breadboard-Friendly Breakout Version

6

Power Pins

The sensor on the breakout requires 3V power. Since many customers have 5V microcontrollers like Arduino, we tossed a 3.3V regulator on the board. Its ultra-low dropout so you can power it from 3.3V-5V just fine.

  • Vin - this is the power pin. Since the chip uses 3 VDC, we have included a voltage regulator on board that will take 3-5VDC and safely convert it down. To power the board, give it the same power as the logic level of your microcontroller - e.g. for a 5V micro like Arduino, use 5V
  • 3V3 - this is the 3.3V output from the voltage regulator, you can grab up to 100mA from this if you like
  • GND - common ground for power and logic

I2C Pins

  • SCL - I2C clock pin, connect to your microcontrollers I2C clock line. This pin is level shifted so you can use 3-5V logic, and there's a 10K pullup on this pin.
  • SDA - I2C data pin, connect to your microcontrollers I2C data line. This pin is level shifted so you can use 3-5V logic, and there's a 10K pullup on this pin.

SPI Pins

If you're interested in using SPI to interface with the LSM9DS0, you can!

  • SCL - this is also the SPI clock pin, it's level shifted so you can use 3-5V logic input
  • SDA - this is also the SPI MOSI pin, it's level shifted so you can use 3-5V logic input
  • CSG - this is the Gyro subchip Chip Select, it's level shifted so you can use 3-5V logic input
  • CSXM - this is the Accelerometer & Magnetometer subchip Select, it's level shifted so you can use 3-5V logic input
  • SDOG - this is the Gyro subchip MISO pin - it's 3V logic out, but can be read properly by 5V logic chips.
  • SDOXM - this is the Accelerometer & Magnetometer subchip MISO pin - it's 3V logic out, but can be read properly by 5V logic chips.

Interrupt & Misc Pins

Since there's so many sensors in the LSM9DS0, there's quite a number of interrupt outputs.

  • DEN - this is a pin that can be used to dynamically enable/disable the Gyro. There's actually no documentation on it but it seems you can try it out by enabling the trigger with
    write8(GYROTYPE, 0x21, 0xC0);
    which will let you use DEN to turn on/off gyro output (level trigger). This pin is level shifted.
  • INT1 & INT2 - These are interrupts from the accelerometer/magnetometer subchip. We don't have specific library support for these so check the datasheet for what you can make these indicate. They are 3V-logic outputs
  • DRDY - this is the Gyro subchip data ready output. We don't have specific library support for these so check the datasheet for how you can set the registers to enable this pin. It is a 3V-logic output.
  • INTG - This is the interrupt from the Gyro subchip. We don't have specific library support for it so check the datasheet for what you can make it indicate. It is a 3V-logic output.

Assembly

If you have the breadboard version of this sensor, you'll want to solder some header onto the sensor so it can be used in a breadboard. The Flora version does not require any extra assembly

7

Prepare the header strip:

Cut the strip to length if necessary. It will be easier to solder if you insert it into a breadboard - long pins down

8

Add the breakout board:

Place the breakout board over the pins so that the short pins poke through the breakout pads

9

And Solder!

Be sure to solder all pins for reliable electrical contact.

Solder the longer power/data strip first

10

11

12

If you plan to use the interrupts and/or you want the board to sit flatter in a breadboard, solder up the other strip!

sensors_solder4

You're done! Check your solder joints visually and continue onto the next steps

13

Wiring for Flora

Flora uses conductive thread or aligator clips, connect up the 3V/SDA/SCL/GND pins to the matching pins in the north-west quarter of the Flora board. We suggest alligator clips to test, then sew in with thread once it works

14

Wiring for Arduino

You can easily wire this breakout to any microcontroller, we'll be using an Arduino. For another kind of microcontroller, just make sure it has I2C or SPI, then port the code - its pretty simple stuff!

Let's start with just I2C interfacing since it requires the fewest # of wires:

15

  • Connect Vin to the power supply, 3-5V is fine. Use the same voltage that the microcontroller logic is based off of. For most Arduinos, that is 5V
  • Connect GND to common power/data ground
  • Connect the SCL pin to the I2C clock SCL pin on your Arduino. On an UNO & '328 based Arduino, this is also known as A5, on a Mega it is also known as digital 21 and on a Leonardo/Micro, digital 3
  • Connect the SDA pin to the I2C data SDA pin on your Arduino. On an UNO & '328 based Arduino, this is also known as A4, on a Mega it is also known as digital 20 and on a Leonardo/Micro, digital 2

Download Adafruit_LSM9DS0

To begin reading sensor data, you will need to download the Adafruit_LSM9DS0 Library from our github repository. You can do that by visiting the github repo and manually downloading or, easier, just click this button to download the zip

Rename the uncompressed folder Adafruit_LSM9DS0 and check that the Adafruit_LSM9DS0 folder contains Adafruit_LSM9DS0.cpp and Adafruit_LSM9DS0.h

Place the Adafruit_LSM9DS0 library folder your arduinosketchfolder/libraries/ folder.
You may need to create the libraries subfolder if its your first library. Restart the IDE.

We also have a great tutorial on Arduino library installation at:
http://learn.adafruit.com/adafruit-all-about-arduino-libraries-install-use

Download Adafruit_Sensor

The Adafruit_LSM9DS0 library uses the Adafruit_Sensor support backend so that readings can be normalized between sensors. You can grab Adafruit_Sensor from the github repo or just click the button below.

Install like you did with Adafruit_LSM9DS0

Restart the IDE!

Load Demo Sketch

Now you can open up File->Examples->Adafruit_LSM9DS0->lsm9doftest and upload to your Arduino wired up to the sensor

16

Then open up the Serial console at 9600 baud to read the raw data output in 'counts'. This is data directly from the sensor, and isn't in any particular units.

17

This output is not terribly useful for most people - its simpler but does not have adjusted output units. Instead, we suggest the sensorapi demo. Upload that to the Arduino and open up the Serial console again.

This time, you'll get the outputs in m/s*s, gauss an degrees-per-second

18

We suggest using this Adafruit_Sensor interface version, since it will let you swap sensors without having to worry about units compatibility. Try twisting and moving the board around to see the sensors change value.

Library Reference

The library we have is simple and easy to use

You can create the Adafruit_LSM9DS0 object with:

  1. Adafruit_LSM9DS0 lsm = Adafruit_LSM9DS0(); // i2c sensor

I2C does not have pins, as they are fixed in hardware.

If you're using "hardware" SPI, you will have to wire up the pins as follows:

  • SCL -> SPI CLK
  • SDA -> SPI MOSI
  • SDO_XM & SDO_G -> SPI MISO (both together)

You can determine the hardware SPI pins for your Arduino here Then pick two pins for the CS lines

  1. Adafruit_LSM9DS0 lsm = Adafruit_LSM9DS0(LSM9DS0_XM_CS, LSM9DS0_GYRO_CS);
If you don't want to use the hardware SPI, you can also try the soft SPI capability, which is bitbanged. You can basically use any pins you like!
  1. Adafruit_LSM9DS0 lsm = Adafruit_LSM9DS0(LSM9DS0_SCLK, LSM9DS0_MISO, LSM9DS0_MOSI, LSM9DS0_XM_CS, LSM9DS0_GYRO_CS);

Begin!

To initialize the sensor, call lsm.begin() which will check the sensor can be found. It returns true/false depending on these checks. We suggest you wrap begin() in a statement that will check if the sensor was located:

  1. if(!lsm.begin())
  2. {
  3. /* There was a problem detecting the LSM9DS0 ... check your connections */
  4. Serial.print(F("Ooops, no LSM9DS0 detected ... Check your wiring!"));
  5. while(1);
  6. }

Set Ranges

These chips have tons of registers, we basically provide interface code for the most useful stuff, such as setting the range. Each subsensor has it's own range. Higher ranges have less precision but can measure larger movements!
Set up the ranges with the setup functions:

  1. // 1.) Set the accelerometer range
  2. lsm.setupAccel(lsm.LSM9DS0_ACCELRANGE_2G);
  3. //lsm.setupAccel(lsm.LSM9DS0_ACCELRANGE_4G);
  4. //lsm.setupAccel(lsm.LSM9DS0_ACCELRANGE_6G);
  5. //lsm.setupAccel(lsm.LSM9DS0_ACCELRANGE_8G);
  6. //lsm.setupAccel(lsm.LSM9DS0_ACCELRANGE_16G);
  7. // 2.) Set the magnetometer sensitivity
  8. lsm.setupMag(lsm.LSM9DS0_MAGGAIN_2GAUSS);
  9. //lsm.setupMag(lsm.LSM9DS0_MAGGAIN_4GAUSS);
  10. //lsm.setupMag(lsm.LSM9DS0_MAGGAIN_8GAUSS);
  11. //lsm.setupMag(lsm.LSM9DS0_MAGGAIN_12GAUSS);
  12.  
  13. // 3.) Setup the gyroscope
  14. lsm.setupGyro(lsm.LSM9DS0_GYROSCALE_245DPS);
  15. //lsm.setupGyro(lsm.LSM9DS0_GYROSCALE_500DPS);
  16. //lsm.setupGyro(lsm.LSM9DS0_GYROSCALE_2000DPS);
Choose whichever range you like, after you begin() the sensor!

Read data

Read data using the Adafruit_Sensor API by first creating four events, one for each sub-sensor:

  1. sensors_event_t accel, mag, gyro, temp;
Then pass these into the getEvent function
  1. lsm.getEvent(&accel, &mag, &gyro, &temp);

The data is snapshotted at once, so you can read and manage the data later.

For the Accelerometer event you can read accel.acceleration.x, accel.acceleration.y oraccel.acceleration.z which are in meters/second*second.

For the Magnetometer event you can read mag.magnetic.x, mag.magnetic.y or mag.magnetic.zwhich are in gauss.

For the Gyro event you can read gyro.gyro.x, gyro.gyro.y or gyro.gyro.z, which are in degrees-per-second (dps)

The temperature event data is in temp.temperature, in degrees C

Why is the temperature value weird on my LSM9DSO?

While there is a temperature sensor inside the LSM9DSO, unfortunately there isn't enough information provided in the datasheet to properly interpret or convert the values.  We've made our best guess at interpreting the data, but you may need to incorporate an external temperature sensor if you require accurate temperature values in your system.

This is a known and long-standing issue with this sensor (example), and to our knowledge ST has never addressed it or provided the extra information needed to accurately interpret the raw temperature data.

Downloads Datasheets

Breakout Board Schematic

19

Breakout Board PCB Print

Dimensions in Inches

20

Flora Breakout Schematics

21

Flora Breakout PCB Print

Dimensions in Inches

22

 

Overview

21

You can detect motion, tilt and basic orientation with a digital accelerometer - and the MMA8451 is a great accelerometer to start with. It's low cost, but high precision with 14-bit ADC. It has a wide usage range, from +-2g up to +-8g yet is easy to use with Arduino or another microcontroller
The MMA8451 is a miniature little accelerometer from Freescale, who are (by this point) masters at the accelerometer-design game. It's designed for use in phones, tablets, smart watches, and more, but works just as well in your Arduino project. Of the MMA8451/MMA8452/MMA8453 family, the MMA8451 is the most precise with a built in 14-bit ADC. The accelerometer also has built in tilt/orientation detection so i can tell you whether your project is being held in landscape or portrait mode, and whether it is tilted forward or back

22

This sensor communicates over I2C so you can share it with a bunch of other sensors on the same two I2C pins. There's an address selection pin so you can have accelerometers share an I2C bus. Please note this chip requires repeated-start I2C support (in case you are looking to port this to another processor)

23

To get you going fast, we spun up a breakout board for this little guy. Since it's a 3V sensor, we add a low-dropout 3.3V regulator and level shifting circuitry on board. That means its perfectly safe for use with 3V or 5V power and logic.

Pinouts

24

The little chip in the middle of the PCB is the actual MMA8451 sensor that does all the motion sensing. We add all the extra components you need to get started, and 'break out' all the other pins you may want to connect to onto the PCB. For more details you can check out the schematics in the Downloads page.

Power Pins

The sensor on the breakout requires 3V power. Since many customers have 5V microcontrollers like Arduino, we tossed a 3.3V regulator on the board. Its ultra-low dropout so you can power it from 3.3V-5V just fine.

  • Vin - this is the power pin. Since the chip uses 3 VDC, we have included a voltage regulator on board that will take 3-5VDC and safely convert it down. To power the board, give it the same power as the logic level of your microcontroller - e.g. for a 5V micro like Arduino, use 5V
  • 3Vo - this is the 3.3V output from the voltage regulator, you can grab up to 100mA from this if you like
  • GND - common ground for power and logic

I2C Pins

  • SCL - I2C clock pin, connect to your microcontrollers I2C clock line.
  • SDA - I2C data pin, connect to your microcontrollers I2C data line.

INT and ADDR Pins

  • A is the I2C Address select pin. By default this is pulled down to ground with a 10K resistor, for an I2C address of 0x1C. You can also connect it to the 3Vo pin for an address of 0x1D
  • I1 and I2 are the Interrupt #1 and #2 signal pins. These pins are for more advanced usage, where you want to be alerted by the chip say when data is ready to read, or if it detects a large motion. We don't have direct support in the example Arduino library for these pins, so please check the datasheet for the I2C commands

Assembly

25

Prepare the header strip:

Cut the strip to length if necessary. It will be easier to solder if you insert it into a breadboard - long pins down

26

Add the breakout board:

Place the breakout board over the pins so that the short pins poke through the breakout pads

27

And Solder!

Be sure to solder all pins for reliable electrical contact.

28

29

You're done! Check your solder joints visually and continue onto the next steps

30

Wiring & Test

You can easily wire this breakout to any microcontroller, we'll be using an Arduino. For another kind of microcontroller, just make sure it has I2C with repeated-start support, then port the code - its pretty simple stuff!

31

  • Connect Vin to the power supply, 3-5V is fine. Use the same voltage that the microcontroller logic is based off of. For most Arduinos, that is 5V
  • Connect GND to common power/data ground
  • Connect the SCL pin to the I2C clock SCL pin on your Arduino. On an UNO & '328 based Arduino, this is also known as A5, on a Mega it is also known as digital 21 and on a Leonardo/Micro, digital 3
  • Connect the SDA pin to the I2C data SDA pin on your Arduino. On an UNO & '328 based Arduino, this is also known as A4, on a Mega it is also known as digital 20 and on a Leonardo/Micro, digital 2

The MMA8451 has a default I2C address of 0x1D and can be changed to 0x1C by tying the A pin to GND

Download Adafruit_MMA8451

To begin reading sensor data, you will need to download the Adafruit_MMA8451_Library from our github repository. You can do that by visiting the github repo and manually downloading or, easier, just click this button to download the zip

Rename the uncompressed folder Adafruit_MMA8451 and check that the Adafruit_MMA8451 folder contains Adafruit_MMA8451.cpp and Adafruit_MMA8451.h

Place the Adafruit_MMA8451 library folder your arduinosketchfolder/libraries/ folder.
You may need to create the libraries subfolder if its your first library. Restart the IDE.

We also have a great tutorial on Arduino library installation at:
http://learn.adafruit.com/adafruit-all-about-arduino-libraries-install-use

Download Adafruit_Sensor

The MMA8451 library uses the Adafruit_Sensor support backend so that readings can be normalized between sensors. You can grab Adafruit_Sensor from the github repo or just click the button below.

Install like you did with Adafruit_MMA8451

Load Demo

Open up File->Examples->Adafruit_MMA8451->MMA8451demo and upload to your Arduino wired up to the sensor

32

Thats it! Now open up the serial terminal window at 9600 speed to begin the test.

33

There's three lines of output from the sensor.

Example for line 1:

X: 45 Y: -672 Z: 734

This is the "raw count" data from the sensor, its a number from -8192 to 8191 (14 bits) that measures over the set range. The range can be set to 2G, 4G or 8G

Example for line 2:

X: -0.07 Y: 0.09 Z: 0.98 m/s^2

This is the Adafruit_Sensor'ified nice output which is in m/s*s, the SI units for measuring acceleration. No matter what the range is set to, it will give you the same units, so its nice to use this instead of mucking with the raw counts

Example for line 3:

Portrait Up Front

This is the output of the orientaiton detection inside the chip. Since inexpensive accelerometers are often used to detect orientation and tilt, this sensor has it built in. The orientation can be Portrait or Landscape, then Up/Down or Left/Right and finally tilted forward or tilted back. Note that if the sensor is tilted less than 30 degrees it cannot determine the forward/back orientation. If you play with twisting the board around you'll get the hang of it.

Library Reference

The library we have is simple and easy to use

You can create the Adafruit_MMA8451 object with:

  1. Adafruit_MMA8451 mma = Adafruit_MMA8451();

There are no pins to set since you must use the I2C bus!

Then initialize the sensor with:

  1. mma.begin()
this function returns True if the sensor was found and responded correctly and False if it was not found. We suggest something like this:
  1. if (! mma.begin()) {
  2. Serial.println("Couldnt start")
  3. while (1);
  4. }
  5. Serial.println("MMA8451 found!");

Set & Get Range

You can set the accelerometer max range to ±2g, ±4g or ±8g with

  1. mma.setRange(MMA8451_RANGE_2_G);
  2. mma.setRange(MMA8451_RANGE_4_G);
  3. mma.setRange(MMA8451_RANGE_8_G);
And read what the current range is with
  1. mma.getRange()
Which returns 1 for ±2g, 2 for ±4g and 3 for ±8g

Read Raw Count Data

You can read the raw counts data with

  1. mma.read();
The x, y and z data is then available in mma.x, mma.y and mma.z
All three are read in one transaction.

Reading Normalized Adafruit_Sensor data

We recommend using the Adafruit_Sensor interface which allows reading into an event structure. First create a new event structure

  1. sensors_event_t event;
Then read the event whenever you want
  1. mma.getEvent(&event);
The normalized SI unit data is available in event.acceleration.x, event.acceleration.y andevent.acceleration.z

Read Orientation

The sensor has built in tilt/orientation detection. You can read the current orientation with

  1. mma.getOrientation();

The return value ranges from 0 to 7

  • 0: Portrait Up Front
  • 1: Portrait Up Back
  • 2: Portrait Down Front
  • 3: Portrait Down Back
  • 4: Landscape Right Front
  • 5: Landscape Right Back
  • 6: Landscape Left Front
  • 7: Landscape Left Back

Downloads

Schematics

34

Fabrication print

Dimensions are in Inches

35