IP Configuration

This commit is contained in:
Gašper Dobrovoljc 2023-03-11 15:11:03 +01:00
commit ec125f27db
No known key found for this signature in database
GPG Key ID: 0E7E037018CFA5A5
662 changed files with 103738 additions and 0 deletions

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
.pio
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/ipch

10
.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,10 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"platformio.platformio-ide"
],
"unwantedRecommendations": [
"ms-vscode.cpptools-extension-pack"
]
}

39
include/README Normal file
View File

@ -0,0 +1,39 @@
This directory is intended for project header files.
A header file is a file containing C declarations and macro definitions
to be shared between several project source files. You request the use of a
header file in your project source file (C, C++, etc) located in `src` folder
by including it, with the C preprocessing directive `#include'.
```src/main.c
#include "header.h"
int main (void)
{
...
}
```
Including a header file produces the same results as copying the header file
into each source file that needs it. Such copying would be time-consuming
and error-prone. With a header file, the related declarations appear
in only one place. If they need to be changed, they can be changed in one
place, and programs that include the header file will automatically use the
new version when next recompiled. The header file eliminates the labor of
finding and changing all the copies as well as the risk that a failure to
find one copy will result in inconsistencies within a program.
In C, the usual convention is to give header files names that end with `.h'.
It is most portable to use only letters, digits, dashes, and underscores in
header file names, and at most one dot.
Read more about using header files in official GCC documentation:
* Include Syntax
* Include Operation
* Once-Only Headers
* Computed Includes
https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html

View File

@ -0,0 +1,277 @@
/*!
* @file Adafruit_MPR121.cpp
*
* @mainpage Adafruit MPR121 arduino driver
*
* @section intro_sec Introduction
*
* This is a library for the MPR121 I2C 12-chan Capacitive Sensor
*
* Designed specifically to work with the MPR121 sensor from Adafruit
* ----> https://www.adafruit.com/products/1982
*
* These sensors use I2C to communicate, 2+ pins are required to
* interface
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit and open-source hardware by purchasing
* products from Adafruit!
*
* @section author Author
*
* Written by Limor Fried/Ladyada for Adafruit Industries.
*
* @section license License
*
* BSD license, all text here must be included in any redistribution.
*/
#include "Adafruit_MPR121.h"
// uncomment to use autoconfig !
//#define AUTOCONFIG // use autoconfig (Yes it works pretty well!)
/*!
* @brief Default constructor
*/
Adafruit_MPR121::Adafruit_MPR121() {}
/*!
* @brief Begin an MPR121 object on a given I2C bus. This function resets
* the device and writes the default settings.
* @param sensibility5C
* together with sensibility5D sets the sensibility of the touch sensors
* @param sensibility5D
* @param i2caddr
* the i2c address the device can be found on. Defaults to 0x5A.
* @param *theWire
* Wire object
* @param touchThreshold
* touch detection threshold value
* @param releaseThreshold
* release detection threshold value
* @returns true on success, false otherwise
*/
bool Adafruit_MPR121::begin(uint8_t sensibility5C, uint8_t sensibility5D,
uint8_t i2caddr, TwoWire *theWire,
uint8_t touchThreshold, uint8_t releaseThreshold) {
if (i2c_dev) {
delete i2c_dev;
}
i2c_dev = new Adafruit_I2CDevice(i2caddr, theWire);
if (!i2c_dev->begin()) {
return false;
}
// soft reset
writeRegister(MPR121_SOFTRESET, 0x63);
delay(1);
for (uint8_t i = 0; i < 0x7F; i++) {
// Serial.print("$"); Serial.print(i, HEX);
// Serial.print(": 0x"); Serial.println(readRegister8(i));
}
writeRegister(MPR121_ECR, 0x80);
// writeRegister(MPR121_ECR, 0x0);
uint8_t c = readRegister8(MPR121_CONFIG2);
if (c != 0x24) return false;
setThresholds(touchThreshold, releaseThreshold);
writeRegister(MPR121_MHDR, 0x01);
writeRegister(MPR121_NHDR, 0x01);
writeRegister(MPR121_NCLR, 0x0E);
writeRegister(MPR121_FDLR, 0x00);
writeRegister(MPR121_MHDF, 0x01);
writeRegister(MPR121_NHDF, 0x05);
writeRegister(MPR121_NCLF, 0x01);
writeRegister(MPR121_FDLF, 0x00);
writeRegister(MPR121_NHDT, 0x00);
writeRegister(MPR121_NCLT, 0x00);
writeRegister(MPR121_FDLT, 0x00);
// writeRegister(MPR121_DEBOUNCE, 0x32);
// change this values to extend the range of the sensibility of the sensors
writeRegister(MPR121_CONFIG1, sensibility5C);
writeRegister(MPR121_CONFIG2, sensibility5D);
#ifdef AUTOCONFIG
writeRegister(MPR121_AUTOCONFIG0, 0x2B);
// writeRegister(MPR121_AUTOCONFIG0, 0x20);
// correct values for Vdd = 3.3V
writeRegister(MPR121_UPLIMIT, 200); // ((Vdd - 0.7)/Vdd) * 256
writeRegister(MPR121_TARGETLIMIT, 180); // UPLIMIT * 0.9
writeRegister(MPR121_LOWLIMIT, 130); // UPLIMIT * 0.65
#endif
// enable X electrodes and start MPR121
byte ECR_SETTING =
0b10000000 + 12; // 5 bits for baseline tracking & proximity disabled + X
// amount of electrodes running (12)
writeRegister(MPR121_ECR, ECR_SETTING); // start with above ECR setting
return true;
}
/*!
* @brief DEPRECATED. Use Adafruit_MPR121::setThresholds(uint8_t touch,
* uint8_t release) instead.
* @param touch
* see Adafruit_MPR121::setThresholds(uint8_t touch, uint8_t
* *release)
* @param release
* see Adafruit_MPR121::setThresholds(uint8_t touch, *uint8_t
* release)
*/
void Adafruit_MPR121::setThreshholds(uint8_t touch, uint8_t release) {
setThresholds(touch, release);
}
/*!
* @brief Set the touch and release thresholds for all 13 channels on the
* device to the passed values. The threshold is defined as a
* deviation value from the baseline value, so it remains constant
* even baseline value changes. Typically the touch threshold is a little bigger
* than the release threshold to touch debounce and hysteresis. For typical
* touch application, the value can be in range 0x05~0x30 for example. The
* setting of the threshold is depended on the actual application. For the
* operation details and how to set the threshold refer to application note
* AN3892 and MPR121 design guidelines.
* @param touch
* the touch threshold value from 0 to 255.
* @param release
* the release threshold from 0 to 255.
*/
void Adafruit_MPR121::setThresholds(uint8_t touch, uint8_t release) {
// set all thresholds (the same)
for (uint8_t i = 0; i < 12; i++) {
writeRegister(MPR121_TOUCHTH_0 + 2 * i, touch);
writeRegister(MPR121_RELEASETH_0 + 2 * i, release);
}
}
/*!
* @brief Read the filtered data from channel t. The ADC raw data outputs
* run through 3 levels of digital filtering to filter out the high
* frequency and low frequency noise encountered. For detailed information on
* this filtering see page 6 of the device datasheet.
* @param t
* the channel to read
* @returns the filtered reading as a 10 bit unsigned value
*/
uint16_t Adafruit_MPR121::filteredData(uint8_t t) {
if (t > 12) return 0;
return readRegister16(MPR121_FILTDATA_0L + t * 2);
}
/*!
* @brief Read the baseline value for the channel. The 3rd level filtered
* result is internally 10bit but only high 8 bits are readable
* from registers 0x1E~0x2A as the baseline value output for each channel.
* @param t
* the channel to read.
* @returns the baseline data that was read
*/
uint16_t Adafruit_MPR121::baselineData(uint8_t t) {
if (t > 12) return 0;
uint16_t bl = readRegister8(MPR121_BASELINE_0 + t);
return (bl << 2);
}
/**
* @brief Read the touch status of all 13 channels and the over current
* status in a 16 bit integer.
* @returns a 16 bit integer where the 12 lower bits contain the touch status of
* the 12 touch sensors. Then, the 13th bit contains the status of the proximiti sensor,
* if used. The highest bit contains the status of the over current flag.
*/
uint16_t Adafruit_MPR121::touched(void) {
uint16_t t = readRegister16(MPR121_TOUCHSTATUS_L);
return t & 0x9FFF;
}
/*!
* @brief Read the contents of an 8 bit device register.
* @param reg the register address to read from
* @returns the 8 bit value that was read.
*/
uint8_t Adafruit_MPR121::readRegister8(uint8_t reg) {
Adafruit_BusIO_Register thereg = Adafruit_BusIO_Register(i2c_dev, reg, 1);
return (thereg.read());
}
/*!
* @brief Check if during the configuration or the auto-configuration the sensors
went out of range, hence no touch could be sensed. Only the 2 ightest bits are checked
because they are the bits that inform about this error. Even if the ids of the failing
channels are set in the lowest bits, this is not used here.
* @returns true if the configuration or the auto-configuration could not be performed.
*/
bool Adafruit_MPR121::wentOutOfRange(void) {
uint16_t e = readRegister8(MPR121_STATUS_H);
// check for bits 1100 0000.
return (e & 0xC0);
}
/*!
* @brief Check if the sensor had an over current, hence it's in an error status an no
* sensing could be performed. It does it by checking the highest bit of the touched array
* (see page 11 in sensor documnetation).
* @param touched the array with the results of the touch check, where the highest contains
* the error status
* @returns true if the sensor had an over current, false otherwise
*/
bool Adafruit_MPR121::hadOverCurrent(uint16_t touched) {
return (touched & 0x8000);
}
/*!
* @brief Read the contents of a 16 bit device register.
* @param reg the register address to read from
* @returns the 16 bit value that was read.
*/
uint16_t Adafruit_MPR121::readRegister16(uint8_t reg) {
Adafruit_BusIO_Register thereg =
Adafruit_BusIO_Register(i2c_dev, reg, 2, LSBFIRST);
return (thereg.read());
}
/*!
@brief Writes 8-bits to the specified destination register
@param reg the register address to write to
@param value the value to write
*/
void Adafruit_MPR121::writeRegister(uint8_t reg, uint8_t value) {
// MPR121 must be put in Stop Mode to write to most registers
bool stop_required = true;
// first get the current set value of the MPR121_ECR register
Adafruit_BusIO_Register ecr_reg =
Adafruit_BusIO_Register(i2c_dev, MPR121_ECR, 1);
uint8_t ecr_backup = ecr_reg.read();
if ((reg == MPR121_ECR) || ((0x73 <= reg) && (reg <= 0x7A))) {
stop_required = false;
}
if (stop_required) {
// clear this register to set stop mode
ecr_reg.write(0x00);
}
Adafruit_BusIO_Register the_reg = Adafruit_BusIO_Register(i2c_dev, reg, 1);
the_reg.write(value);
if (stop_required) {
// write back the previous set ECR settings
ecr_reg.write(ecr_backup);
}
}

View File

@ -0,0 +1,119 @@
/*!
* @file Adafruit_MPR121.h
*
* This is a library for the MPR121 12-Channel Capacitive Sensor
*
* Designed specifically to work with the MPR121 board.
*
* Pick one up today in the adafruit shop!
* ------> https://www.adafruit.com/product/1982
*
* These sensors use I2C to communicate, 2+ pins are required to interface
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit andopen-source hardware by purchasing products
* from Adafruit!
*
* Limor Fried/Ladyada (Adafruit Industries).
*
* BSD license, all text above must be included in any redistribution
*/
#ifndef ADAFRUIT_MPR121_H
#define ADAFRUIT_MPR121_H
#include "Arduino.h"
#include <Adafruit_BusIO_Register.h>
#include <Adafruit_I2CDevice.h>
// The default I2C address
#define MPR121_I2CADDR_DEFAULT 0x5A ///< default I2C address
#define MPR121_TOUCH_THRESHOLD_DEFAULT 12 ///< default touch threshold value
#define MPR121_RELEASE_THRESHOLD_DEFAULT 6 ///< default relese threshold value
/*!
* Device register map
*/
enum {
MPR121_TOUCHSTATUS_L = 0x00,
MPR121_TOUCHSTATUS_H = 0x01,
MPR121_STATUS_L = 0x02,
MPR121_STATUS_H = 0x03,
MPR121_FILTDATA_0L = 0x04,
MPR121_FILTDATA_0H = 0x05,
MPR121_BASELINE_0 = 0x1E,
MPR121_MHDR = 0x2B,
MPR121_NHDR = 0x2C,
MPR121_NCLR = 0x2D,
MPR121_FDLR = 0x2E,
MPR121_MHDF = 0x2F,
MPR121_NHDF = 0x30,
MPR121_NCLF = 0x31,
MPR121_FDLF = 0x32,
MPR121_NHDT = 0x33,
MPR121_NCLT = 0x34,
MPR121_FDLT = 0x35,
MPR121_TOUCHTH_0 = 0x41,
MPR121_RELEASETH_0 = 0x42,
MPR121_DEBOUNCE = 0x5B,
MPR121_CONFIG1 = 0x5C,
MPR121_CONFIG2 = 0x5D,
MPR121_CHARGECURR_0 = 0x5F,
MPR121_CHARGETIME_1 = 0x6C,
MPR121_ECR = 0x5E,
MPR121_AUTOCONFIG0 = 0x7B,
MPR121_AUTOCONFIG1 = 0x7C,
MPR121_UPLIMIT = 0x7D,
MPR121_LOWLIMIT = 0x7E,
MPR121_TARGETLIMIT = 0x7F,
MPR121_GPIODIR = 0x76,
MPR121_GPIOEN = 0x77,
MPR121_GPIOSET = 0x78,
MPR121_GPIOCLR = 0x79,
MPR121_GPIOTOGGLE = 0x7A,
MPR121_SOFTRESET = 0x80,
};
//.. thru to 0x1C/0x1D
/*!
* @brief Class that stores state and functions for interacting with MPR121
* proximity capacitive touch sensor controller.
*/
class Adafruit_MPR121 {
public:
// Hardware I2C
Adafruit_MPR121();
bool begin(uint8_t sensibility5C, uint8_t sensibility5D,
uint8_t i2caddr = MPR121_I2CADDR_DEFAULT,
TwoWire *theWire = &Wire,
uint8_t touchThreshold = MPR121_TOUCH_THRESHOLD_DEFAULT,
uint8_t releaseThreshold = MPR121_RELEASE_THRESHOLD_DEFAULT);
uint16_t filteredData(uint8_t t);
uint16_t baselineData(uint8_t t);
uint8_t readRegister8(uint8_t reg);
uint16_t readRegister16(uint8_t reg);
void writeRegister(uint8_t reg, uint8_t value);
uint16_t touched(void);
// Add deprecated attribute so that the compiler shows a warning
void setThreshholds(uint8_t touch, uint8_t release)
__attribute__((deprecated));
void setThresholds(uint8_t touch, uint8_t release);
// Function that checks if any of the sensors went our of rance
bool wentOutOfRange();
// Function that checks if any of the sensors had an overcurrent
bool hadOverCurrent(uid_t touched);
private:
Adafruit_I2CDevice *i2c_dev = NULL;
};
#endif

View File

@ -0,0 +1,17 @@
# Adafruit MPR121 Library [![Build Status](https://github.com/adafruit/Adafruit_MPR121/workflows/Arduino%20Library%20CI/badge.svg)](https://github.com/adafruit/Adafruit_MPR121/actions)
<a href="https://www.adafruit.com/products/1982"><img src="https://cdn-shop.adafruit.com/970x728/1982-00.jpg" height="300"/></a>
Tested and works great with the Adafruit MPR121
* https://www.adafruit.com/products/1982
* https://www.adafruit.com/product/2024
* https://www.adafruit.com/product/2340
Check out the links above for our tutorials and wiring diagrams.
These sensors use I2C to communicate, 2+ pins are required to interface
Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit!
Written by Limor Fried/Ladyada (Adafruit Industries).
MIT license, all text above must be included in any redistribution

View File

@ -0,0 +1,6 @@
Adafruit_MPR121 KEYWORD1
begin KEYWORD2
filteredData KEYWORD2
baselineData KEYWORD2
touched KEYWORD2
setThresholds KEYWORD2

View File

@ -0,0 +1,10 @@
name=Adafruit MPR121
version=1.1.0
author=Adafruit <info@adafruit.com>
maintainer=Adafruit <info@adafruit.com>
sentence=Arduino library for the MPR121-based capacitive sensors in the Adafruit shop.
paragraph=Designed specifically to work with the MPR121 Breakout in the Adafruit shop.
category=Sensors
url=https://github.com/adafruit/Adafruit_MPR121
architectures=*
depends=Adafruit BusIO

View File

@ -0,0 +1,46 @@
Thank you for opening an issue on an Adafruit Arduino library repository. To
improve the speed of resolution please review the following guidelines and
common troubleshooting steps below before creating the issue:
- **Do not use GitHub issues for troubleshooting projects and issues.** Instead use
the forums at http://forums.adafruit.com to ask questions and troubleshoot why
something isn't working as expected. In many cases the problem is a common issue
that you will more quickly receive help from the forum community. GitHub issues
are meant for known defects in the code. If you don't know if there is a defect
in the code then start with troubleshooting on the forum first.
- **If following a tutorial or guide be sure you didn't miss a step.** Carefully
check all of the steps and commands to run have been followed. Consult the
forum if you're unsure or have questions about steps in a guide/tutorial.
- **For Arduino projects check these very common issues to ensure they don't apply**:
- For uploading sketches or communicating with the board make sure you're using
a **USB data cable** and **not** a **USB charge-only cable**. It is sometimes
very hard to tell the difference between a data and charge cable! Try using the
cable with other devices or swapping to another cable to confirm it is not
the problem.
- **Be sure you are supplying adequate power to the board.** Check the specs of
your board and plug in an external power supply. In many cases just
plugging a board into your computer is not enough to power it and other
peripherals.
- **Double check all soldering joints and connections.** Flakey connections
cause many mysterious problems. See the [guide to excellent soldering](https://learn.adafruit.com/adafruit-guide-excellent-soldering/tools) for examples of good solder joints.
- **Ensure you are using an official Arduino or Adafruit board.** We can't
guarantee a clone board will have the same functionality and work as expected
with this code and don't support them.
If you're sure this issue is a defect in the code and checked the steps above
please fill in the following fields to provide enough troubleshooting information.
You may delete the guideline and text above to just leave the following details:
- Arduino board: **INSERT ARDUINO BOARD NAME/TYPE HERE**
- Arduino IDE version (found in Arduino -> About Arduino menu): **INSERT ARDUINO
VERSION HERE**
- List the steps to reproduce the problem below (if possible attach a sketch or
copy the sketch code in too): **LIST REPRO STEPS BELOW**

View File

@ -0,0 +1,26 @@
Thank you for creating a pull request to contribute to Adafruit's GitHub code!
Before you open the request please review the following guidelines and tips to
help it be more easily integrated:
- **Describe the scope of your change--i.e. what the change does and what parts
of the code were modified.** This will help us understand any risks of integrating
the code.
- **Describe any known limitations with your change.** For example if the change
doesn't apply to a supported platform of the library please mention it.
- **Please run any tests or examples that can exercise your modified code.** We
strive to not break users of the code and running tests/examples helps with this
process.
Thank you again for contributing! We will try to test and integrate the change
as soon as we can, but be aware we have many GitHub repositories to manage and
can't immediately respond to every request. There is no need to bump or check in
on a pull request (it will clutter the discussion of the request).
Also don't be worried if the request is closed or not integrated--sometimes the
priorities of Adafruit's GitHub code (education, ease of use) might not match the
priorities of the pull request. Don't fret, the open source community thrives on
forks and GitHub makes it easy to keep your changes in a forked repo.
After reviewing the guidelines above you can delete this text from the pull request.

View File

@ -0,0 +1,187 @@
/***************************************************
This is a library for the MCP23008 i2c port expander
These displays use I2C to communicate, 2 pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
****************************************************/
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#ifdef __AVR_ATtiny85__
#include <TinyWireM.h>
#define Wire TinyWireM
#else
#include <Wire.h>
#endif
#ifdef __AVR
#include <avr/pgmspace.h>
#elif defined(ESP8266)
#include <pgmspace.h>
#endif
#include "Adafruit_MCP23008.h"
////////////////////////////////////////////////////////////////////////////////
// RTC_DS1307 implementation
void Adafruit_MCP23008::begin(uint8_t addr) {
if (addr > 7) {
addr = 7;
}
i2caddr = addr;
Wire.begin();
// set defaults!
Wire.beginTransmission(MCP23008_ADDRESS | i2caddr);
#if ARDUINO >= 100
Wire.write((byte)MCP23008_IODIR);
Wire.write((byte)0xFF); // all inputs
Wire.write((byte)0x00);
Wire.write((byte)0x00);
Wire.write((byte)0x00);
Wire.write((byte)0x00);
Wire.write((byte)0x00);
Wire.write((byte)0x00);
Wire.write((byte)0x00);
Wire.write((byte)0x00);
Wire.write((byte)0x00);
#else
Wire.send(MCP23008_IODIR);
Wire.send(0xFF); // all inputs
Wire.send(0x00);
Wire.send(0x00);
Wire.send(0x00);
Wire.send(0x00);
Wire.send(0x00);
Wire.send(0x00);
Wire.send(0x00);
Wire.send(0x00);
Wire.send(0x00);
#endif
Wire.endTransmission();
}
void Adafruit_MCP23008::begin(void) {
begin(0);
}
void Adafruit_MCP23008::pinMode(uint8_t p, uint8_t d) {
uint8_t iodir;
// only 8 bits!
if (p > 7)
return;
iodir = read8(MCP23008_IODIR);
// set the pin and direction
if (d == INPUT) {
iodir |= 1 << p;
} else {
iodir &= ~(1 << p);
}
// write the new IODIR
write8(MCP23008_IODIR, iodir);
}
uint8_t Adafruit_MCP23008::readGPIO(void) {
// read the current GPIO input
return read8(MCP23008_GPIO);
}
void Adafruit_MCP23008::writeGPIO(uint8_t gpio) {
write8(MCP23008_GPIO, gpio);
}
void Adafruit_MCP23008::digitalWrite(uint8_t p, uint8_t d) {
uint8_t gpio;
// only 8 bits!
if (p > 7)
return;
// read the current GPIO output latches
gpio = readGPIO();
// set the pin and direction
if (d == HIGH) {
gpio |= 1 << p;
} else {
gpio &= ~(1 << p);
}
// write the new GPIO
writeGPIO(gpio);
}
void Adafruit_MCP23008::pullUp(uint8_t p, uint8_t d) {
uint8_t gppu;
// only 8 bits!
if (p > 7)
return;
gppu = read8(MCP23008_GPPU);
// set the pin and direction
if (d == HIGH) {
gppu |= 1 << p;
} else {
gppu &= ~(1 << p);
}
// write the new GPIO
write8(MCP23008_GPPU, gppu);
}
uint8_t Adafruit_MCP23008::digitalRead(uint8_t p) {
// only 8 bits!
if (p > 7)
return 0;
// read the current GPIO
return (readGPIO() >> p) & 0x1;
}
uint8_t Adafruit_MCP23008::read8(uint8_t addr) {
Wire.beginTransmission(MCP23008_ADDRESS | i2caddr);
#if ARDUINO >= 100
Wire.write((byte)addr);
#else
Wire.send(addr);
#endif
Wire.endTransmission();
Wire.requestFrom(MCP23008_ADDRESS | i2caddr, 1);
#if ARDUINO >= 100
return Wire.read();
#else
return Wire.receive();
#endif
}
void Adafruit_MCP23008::write8(uint8_t addr, uint8_t data) {
Wire.beginTransmission(MCP23008_ADDRESS | i2caddr);
#if ARDUINO >= 100
Wire.write((byte)addr);
Wire.write((byte)data);
#else
Wire.send(addr);
Wire.send(data);
#endif
Wire.endTransmission();
}

View File

@ -0,0 +1,56 @@
/***************************************************
This is a library for the MCP23008 i2c port expander
These displays use I2C to communicate, 2 pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
****************************************************/
#ifndef _ADAFRUIT_MCP23008_H
#define _ADAFRUIT_MCP23008_H
// Don't forget the Wire library
#ifdef __AVR_ATtiny85__
#include <TinyWireM.h>
#else
#include <Wire.h>
#endif
class Adafruit_MCP23008 {
public:
void begin(uint8_t addr);
void begin(void);
void pinMode(uint8_t p, uint8_t d);
void digitalWrite(uint8_t p, uint8_t d);
void pullUp(uint8_t p, uint8_t d);
uint8_t digitalRead(uint8_t p);
uint8_t readGPIO(void);
void writeGPIO(uint8_t);
private:
uint8_t i2caddr;
uint8_t read8(uint8_t addr);
void write8(uint8_t addr, uint8_t data);
};
#define MCP23008_ADDRESS 0x20
// registers
#define MCP23008_IODIR 0x00
#define MCP23008_IPOL 0x01
#define MCP23008_GPINTEN 0x02
#define MCP23008_DEFVAL 0x03
#define MCP23008_INTCON 0x04
#define MCP23008_IOCON 0x05
#define MCP23008_GPPU 0x06
#define MCP23008_INTF 0x07
#define MCP23008_INTCAP 0x08
#define MCP23008_GPIO 0x09
#define MCP23008_OLAT 0x0A
#endif

View File

@ -0,0 +1,19 @@
To download, click "Download Source" in the top right corner. Then install as indicated in our tutorial:
--> http://www.ladyada.net/library/arduino/libraries.html
in a folder called Adafruit_MCP23008.
This is very much beta, it seems to work fine but its not optimized and doesn't currently suport the interrupt capability of the chip
Currently it can do: setting pin directions, inputs and outputs and turning on/off the pull-up resistors
To use:
Connect pin #1 of the expander to Analog 5 (i2c clock)
Connect pin #2 of the expander to Analog 4 (i2c data)
Connect pins #3, 4 and 5 of the expander to ground (address selection)
Connect pin #6 and 18 of the expander to 5V (power and reset disable)
Connect pin #9 of the expander to ground (common ground)
Pins 10 thru 17 are your input/output pins
Check the datasheet for more info: http://ww1.microchip.com/downloads/en/DeviceDoc/21919b.pdf
Enjoy and send pull requests!

View File

@ -0,0 +1,31 @@
#include <Wire.h>
#include "Adafruit_MCP23008.h"
// Basic pin reading and pullup test for the MCP23008 I/O expander
// public domain!
// Connect pin #1 of the expander to Analog 5 (i2c clock)
// Connect pin #2 of the expander to Analog 4 (i2c data)
// Connect pins #3, 4 and 5 of the expander to ground (address selection)
// Connect pin #6 and 18 of the expander to 5V (power and reset disable)
// Connect pin #9 of the expander to ground (common ground)
// Input #0 is on pin 10 so connect a button or switch from there to ground
Adafruit_MCP23008 mcp;
void setup() {
mcp.begin(); // use default address 0
mcp.pinMode(0, INPUT);
mcp.pullUp(0, HIGH); // turn on a 100K pullup internally
pinMode(13, OUTPUT); // use the p13 LED as debugging
}
void loop() {
// The LED will 'echo' the button
digitalWrite(13, mcp.digitalRead(0));
}

View File

@ -0,0 +1,34 @@
#include <Wire.h>
#include "Adafruit_MCP23008.h"
// Basic toggle test for i/o expansion. flips pin #0 of a MCP23008 i2c
// pin expander up and down. Public domain
// Connect pin #1 of the expander to Analog 5 (i2c clock)
// Connect pin #2 of the expander to Analog 4 (i2c data)
// Connect pins #3, 4 and 5 of the expander to ground (address selection)
// Connect pin #6 and 18 of the expander to 5V (power and reset disable)
// Connect pin #9 of the expander to ground (common ground)
// Output #0 is on pin 10 so connect an LED or whatever from that to ground
Adafruit_MCP23008 mcp;
void setup() {
mcp.begin(); // use default address 0
mcp.pinMode(0, OUTPUT);
}
// flip the pin #0 up and down
void loop() {
delay(100);
mcp.digitalWrite(0, HIGH);
delay(100);
mcp.digitalWrite(0, LOW);
}

View File

@ -0,0 +1,20 @@
#######################################
# Syntax Coloring Map for MCP23008
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
MCP23008 KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
pullUp KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################

View File

@ -0,0 +1,9 @@
name=Adafruit MCP23008 library
version=1.0.2
author=Adafruit
maintainer=Adafruit <info@adafruit.com>
sentence=Arduino Library for the MCP23008 (and '9) I2C I/O expander
paragraph=Arduino Library for the MCP23008 (and '9) I2C I/O expander
category=Signal Input/Output
url=https://github.com/adafruit/Adafruit-MCP23008-library
architectures=*

View File

@ -0,0 +1,321 @@
/*!
* @file Adafruit_AM2320.cpp
*
* @mainpage Adafruit AM2320 Temperature & Humidity Unified Sensor driver
*
* @section intro_sec Introduction
*
* This is the documentation for Adafruit's AM2320 driver for the
* Arduino platform. It is designed specifically to work with the
* Adafruit AM2320 breakout: https://www.adafruit.com/products/xxxx
*
* These sensors use I2C to communicate, 2 pins (SCL+SDA) are required
* to interface with the breakout.
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit and open-source hardware by purchasing
* products from Adafruit!
*
* @section dependencies Dependencies
*
* This library depends on <a href="https://github.com/adafruit/Adafruit_Sensor">
* Adafruit_Sensor</a> being present on your system. Please make sure you have
* installed the latest version before using this library.
*
* @section author Author
*
* Written by Limor Fried for Adafruit Industries.
*
* @section license License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include "Adafruit_AM2320.h"
/**************************************************************************/
/*!
@brief Instantiates a new AM2320 class
@param theI2C Optional pointer to a TwoWire object that should be used for I2C communication. Defaults to &Wire.
@param tempSensorId the id that should be used for the temperature sensor. Defaults to -1
@param humiditySensorId the id that should be used for the humidity sensor. Defaults to -1
*/
/**************************************************************************/
Adafruit_AM2320::Adafruit_AM2320(TwoWire *theI2C, int32_t tempSensorId, int32_t humiditySensorId):
_temp(this, tempSensorId),
_humidity(this, humiditySensorId),
_i2c(theI2C)
{}
/**************************************************************************/
/*!
@brief Setups the hardware
@return true
*/
/**************************************************************************/
bool Adafruit_AM2320::begin() {
_i2caddr = 0x5C; // fixed addr
_i2c->begin();
return true;
}
/**************************************************************************/
/*!
@brief read the temperature from the device
@return the temperature reading as a floating point value
*/
/**************************************************************************/
float Adafruit_AM2320::readTemperature() {
uint16_t t = readRegister16(AM2320_REG_TEMP_H);
float ft;
if (t == 0xFFFF) return NAN;
// check sign bit - the temperature MSB is signed , bit 0-15 are magnitude
if(t & 0x8000){
ft = -(int16_t)(t&0x7fff);
}
else {
ft = (int16_t)t;
}
return ft / 10.0;
}
/**************************************************************************/
/*!
@brief read the humidity from the device
@return the humidity reading as a floating point value
*/
/**************************************************************************/
float Adafruit_AM2320::readHumidity() {
uint16_t h = readRegister16(AM2320_REG_HUM_H);
if (h == 0xFFFF) return NAN;
float fh = h;
return fh / 10.0;
}
/**************************************************************************/
/*!
@brief read 2 bytes from a hardware register
@param reg the register to read
@return the read value as a 2 byte unsigned integer
*/
/**************************************************************************/
uint16_t Adafruit_AM2320::readRegister16(uint8_t reg) {
// wake up
Wire.beginTransmission(_i2caddr);
Wire.write(0x00);
Wire.endTransmission();
delay(10); // wait 10 ms
// send a command to read register
Wire.beginTransmission(_i2caddr);
Wire.write(AM2320_CMD_READREG);
Wire.write(reg);
Wire.write(2); // 2 bytes
Wire.endTransmission();
delay(2); // wait 2 ms
// 2 bytes preamble, 2 bytes data, 2 bytes CRC
Wire.requestFrom(_i2caddr, (uint8_t)6);
if (Wire.available() != 6)
return 0xFFFF;
uint8_t buffer[6];
for (int i=0; i<6; i++) {
buffer[i] = Wire.read();
//Serial.print("byte #"); Serial.print(i); Serial.print(" = 0x"); Serial.println(buffer[i], HEX);
}
if (buffer[0] != 0x03) return 0xFFFF; // must be 0x03 modbus reply
if (buffer[1] != 2) return 0xFFFF; // must be 2 bytes reply
uint16_t the_crc = buffer[5];
the_crc <<= 8;
the_crc |= buffer[4];
uint16_t calc_crc = crc16(buffer, 4); // preamble + data
//Serial.print("CRC: 0x"); Serial.println(calc_crc, HEX);
if (the_crc != calc_crc)
return 0xFFFF;
// All good!
uint16_t ret = buffer[2];
ret <<= 8;
ret |= buffer[3];
return ret;
}
/**************************************************************************/
/*!
@brief perfor a CRC check to verify data
@param buffer the pointer to the data to check
@param nbytes the number of bytes to calculate the CRC over
@return the calculated CRC
*/
/**************************************************************************/
uint16_t Adafruit_AM2320::crc16(uint8_t *buffer, uint8_t nbytes) {
uint16_t crc = 0xffff;
for (int i=0; i<nbytes; i++) {
uint8_t b = buffer[i];
crc ^= b;
for (int x=0; x<8; x++) {
if (crc & 0x0001) {
crc >>= 1;
crc ^= 0xA001;
} else {
crc >>= 1;
}
}
}
return crc;
}
/**************************************************************************/
/*!
@brief set the name of the sensor
@param sensor a pointer to the sensor
*/
/**************************************************************************/
void Adafruit_AM2320::setName(sensor_t* sensor) {
strncpy(sensor->name, "AM2320", sizeof(sensor->name) - 1);
}
/**************************************************************************/
/*!
@brief set minimum delay to a fixed value of 2 seconds
@param sensor a pointer to the sensor
*/
/**************************************************************************/
void Adafruit_AM2320::setMinDelay(sensor_t* sensor) {
sensor->min_delay = 2000000L; // 2 seconds (in microseconds)
}
/**************************************************************************/
/*!
@brief create a temperature sensor instance
@param parent the pointer to the parent sensor
@param id the id value for the sensor
*/
/**************************************************************************/
Adafruit_AM2320::Temperature::Temperature(Adafruit_AM2320* parent, int32_t id):
_parent(parent),
_id(id)
{}
/**************************************************************************/
/*!
@brief read the temperature from the device and populate a sensor_event_t with the value
@param event a pointer to the event to populate
@return true
*/
/**************************************************************************/
bool Adafruit_AM2320::Temperature::getEvent(sensors_event_t* event) {
// Clear event definition.
memset(event, 0, sizeof(sensors_event_t));
// Populate sensor reading values.
event->version = sizeof(sensors_event_t);
event->sensor_id = _id;
event->type = SENSOR_TYPE_AMBIENT_TEMPERATURE;
event->timestamp = millis();
event->temperature = _parent->readTemperature();
return true;
}
/**************************************************************************/
/*!
@brief populate a sensor_t with data for this sensor
@param sensor a pointer to the sensor_t to populate
*/
/**************************************************************************/
void Adafruit_AM2320::Temperature::getSensor(sensor_t* sensor) {
// Clear sensor definition.
memset(sensor, 0, sizeof(sensor_t));
// Set sensor name.
_parent->setName(sensor);
// Set version and ID
sensor->version = AM2320_SENSOR_VERSION;
sensor->sensor_id = _id;
// Set type and characteristics.
sensor->type = SENSOR_TYPE_AMBIENT_TEMPERATURE;
_parent->setMinDelay(sensor);
// This isn't documented, of course
sensor->max_value = 80.0F;
sensor->min_value = -20.0F;
sensor->resolution = 2.0F;
}
/**************************************************************************/
/*!
@brief create a humidity sensor instance
@param parent the pointer to the parent sensor
@param id the id value for the sensor
*/
/**************************************************************************/
Adafruit_AM2320::Humidity::Humidity(Adafruit_AM2320* parent, int32_t id):
_parent(parent),
_id(id)
{}
/**************************************************************************/
/*!
@brief read the humidity from the device and populate a sensor_event_t with the value
@param event a pointer to the event to populate
@return true
*/
/**************************************************************************/
bool Adafruit_AM2320::Humidity::getEvent(sensors_event_t* event) {
// Clear event definition.
memset(event, 0, sizeof(sensors_event_t));
// Populate sensor reading values.
event->version = sizeof(sensors_event_t);
event->sensor_id = _id;
event->type = SENSOR_TYPE_RELATIVE_HUMIDITY;
event->timestamp = millis();
event->relative_humidity = _parent->readHumidity();
return true;
}
/**************************************************************************/
/*!
@brief populate a sensor_t with data for this sensor
@param sensor a pointer to the sensor_t to populate
*/
/**************************************************************************/
void Adafruit_AM2320::Humidity::getSensor(sensor_t* sensor) {
// Clear sensor definition.
memset(sensor, 0, sizeof(sensor_t));
// Set sensor name.
_parent->setName(sensor);
// Set version and ID
sensor->version = AM2320_SENSOR_VERSION;
sensor->sensor_id = _id;
// Set type and characteristics.
sensor->type = SENSOR_TYPE_RELATIVE_HUMIDITY;
_parent->setMinDelay(sensor);
// This isn't documented, of course
sensor->max_value = 100.0F;
sensor->min_value = 0.0F;
sensor->resolution = 1.0F;
}

View File

@ -0,0 +1,122 @@
/*!
* @file Adafruit_AM2320.h
*
* This is a library for the AM2320 Temperature & Humidity Unified Sensor breakout board
* ----> https://www.adafruit.com/products/xxxx
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit and open-source hardware by purchasing
* products from Adafruit!
*
* Written by Limor Fried for Adafruit Industries.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#ifndef ADAFRUIT_AM2320
#define ADAFRUIT_AM2320
#define AM2320_SENSOR_VERSION 1 ///< the sensor version
#define AM2320_CMD_READREG 0x03 ///< read register command
#define AM2320_REG_TEMP_H 0x02 ///< temp register address
#define AM2320_REG_HUM_H 0x00 ///< humidity register address
#include <Adafruit_Sensor.h>
#include <Wire.h>
/**************************************************************************/
/*!
@brief Class that stores state and functions for interacting with AM2320 Temperature & Humidity Unified Sensor
*/
/**************************************************************************/
class Adafruit_AM2320 {
public:
Adafruit_AM2320(TwoWire *theI2C = &Wire, int32_t tempSensorId=-1, int32_t humiditySensorId=-1);
bool begin();
float readTemperature();
float readHumidity();
uint16_t readRegister16(uint8_t reg);
uint16_t crc16(uint8_t *buffer, uint8_t nbytes);
/**************************************************************************/
/*!
@brief temperature sensor class
*/
/**************************************************************************/
class Temperature : public Adafruit_Sensor {
public:
Temperature(Adafruit_AM2320* parent, int32_t id);
bool getEvent(sensors_event_t* event);
void getSensor(sensor_t* sensor);
private:
Adafruit_AM2320* _parent; ///< the parent sensor object
int32_t _id; ///< the sensor id
};
/**************************************************************************/
/*!
@brief humidity sensor class
*/
/**************************************************************************/
class Humidity : public Adafruit_Sensor {
public:
Humidity(Adafruit_AM2320* parent, int32_t id);
bool getEvent(sensors_event_t* event);
void getSensor(sensor_t* sensor);
private:
Adafruit_AM2320* _parent; ///< the parent sensor object
int32_t _id; ///< the sensor id
};
/**************************************************************************/
/*!
@brief get the temperature sensor object belonging to this class
@return the temperature sensor object
*/
/**************************************************************************/
Temperature temperature() {
return _temp;
}
/**************************************************************************/
/*!
@brief get the humidity sensor object belonging to this class
@return the humidity sensor object
*/
/**************************************************************************/
Humidity humidity() {
return _humidity;
}
private:
Temperature _temp; ///< the temperature sensor object
Humidity _humidity; ///< the humidity sensor object
TwoWire *_i2c; ///< the TwoWire object used for I2C connumication
uint8_t _i2caddr; ///< the i2c address the device can be found on
void setName(sensor_t* sensor);
void setMinDelay(sensor_t* sensor);
};
#endif

View File

@ -0,0 +1,15 @@
# Adafruit AM2320 Library [![Build Status](https://travis-ci.org/adafruit/Adafruit_AM2320.svg?branch=master)](https://travis-ci.org/adafruit/Adafruit_AM2320)
<img src="https://cdn-shop.adafruit.com/970x728/1947-05.jpg" height="300"/>
This is a library for the Adafruit AM2320 Temperature & Humidity Unified Sensor
* https://www.adafruit.com/products/3721
Also supports AM2320 chips (and maybe other compatible chips!)
Check out the links above for our tutorials and wiring diagrams. This chip uses I2C to communicate
Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
MIT license, all text above must be included in any redistribution

View File

@ -0,0 +1,21 @@
#include "Adafruit_Sensor.h"
#include "Adafruit_AM2320.h"
Adafruit_AM2320 am2320 = Adafruit_AM2320();
void setup() {
Serial.begin(9600);
while (!Serial) {
delay(10); // hang out until serial port opens
}
Serial.println("Adafruit AM2320 Basic Test");
am2320.begin();
}
void loop() {
Serial.print("Temp: "); Serial.println(am2320.readTemperature());
Serial.print("Hum: "); Serial.println(am2320.readHumidity());
delay(2000);
}

View File

@ -0,0 +1,9 @@
name=Adafruit AM2320 sensor library
version=1.1.1
author=Adafruit
maintainer=Adafruit <info@adafruit.com>
sentence=Arduino library for AM2320 I2C Temp & Humidity Sensors
paragraph=Arduino library for AM2320 I2C Temp & Humidity Sensors
category=Sensors
url=https://github.com/adafruit/Adafruit_AM2320
architectures=*

View File

@ -0,0 +1,614 @@
/*!
* @file Adafruit_BME280.cpp
*
* @mainpage Adafruit BME280 humidity, temperature & pressure sensor
*
* @section intro_sec Introduction
*
* Driver for the BME280 humidity, temperature & pressure sensor
*
* These sensors use I2C or SPI to communicate, 2 or 4 pins are required
* to interface.
*
* Designed specifically to work with the Adafruit BME280 Breakout
* ----> http://www.adafruit.com/products/2650
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit and open-source hardware by purchasing
* products from Adafruit!
*
* @section author Author
*
* Written by Kevin "KTOWN" Townsend for Adafruit Industries.
*
* @section license License
*
* BSD license, all text here must be included in any redistribution.
*
*/
#include "Arduino.h"
#include <Wire.h>
#include <SPI.h>
#include "Adafruit_BME280.h"
/**************************************************************************/
/*!
@brief class constructor
*/
/**************************************************************************/
Adafruit_BME280::Adafruit_BME280()
: _cs(-1), _mosi(-1), _miso(-1), _sck(-1)
{ }
/**************************************************************************/
/*!
@brief class constructor if using hardware SPI
@param cspin the chip select pin to use
*/
/**************************************************************************/
Adafruit_BME280::Adafruit_BME280(int8_t cspin)
: _cs(cspin), _mosi(-1), _miso(-1), _sck(-1)
{ }
/**************************************************************************/
/*!
@brief class constructor if using software SPI
@param cspin the chip select pin to use
@param mosipin the MOSI pin to use
@param misopin the MISO pin to use
@param sckpin the SCK pin to use
*/
/**************************************************************************/
Adafruit_BME280::Adafruit_BME280(int8_t cspin, int8_t mosipin, int8_t misopin, int8_t sckpin)
: _cs(cspin), _mosi(mosipin), _miso(misopin), _sck(sckpin)
{ }
/**************************************************************************/
/*!
@brief Initialise sensor with given parameters / settings
@param theWire the I2C object to use
@returns true on success, false otherwise
*/
/**************************************************************************/
bool Adafruit_BME280::begin(TwoWire *theWire)
{
_wire = theWire;
_i2caddr = BME280_ADDRESS;
return init();
}
/**************************************************************************/
/*!
@brief Initialise sensor with given parameters / settings
@param addr the I2C address the device can be found on
@returns true on success, false otherwise
*/
/**************************************************************************/
bool Adafruit_BME280::begin(uint8_t addr)
{
_i2caddr = addr;
_wire = &Wire;
return init();
}
/**************************************************************************/
/*!
@brief Initialise sensor with given parameters / settings
@param addr the I2C address the device can be found on
@param theWire the I2C object to use
@returns true on success, false otherwise
*/
/**************************************************************************/
bool Adafruit_BME280::begin(uint8_t addr, TwoWire *theWire)
{
_i2caddr = addr;
_wire = theWire;
return init();
}
/**************************************************************************/
/*!
@brief Initialise sensor with given parameters / settings
@returns true on success, false otherwise
*/
/**************************************************************************/
bool Adafruit_BME280::begin(void)
{
_i2caddr = BME280_ADDRESS;
_wire = &Wire;
return init();
}
/**************************************************************************/
/*!
@brief Initialise sensor with given parameters / settings
@returns true on success, false otherwise
*/
/**************************************************************************/
bool Adafruit_BME280::init()
{
// init I2C or SPI sensor interface
if (_cs == -1) {
// I2C
_wire -> begin();
} else {
digitalWrite(_cs, HIGH);
pinMode(_cs, OUTPUT);
if (_sck == -1) {
// hardware SPI
SPI.begin();
} else {
// software SPI
pinMode(_sck, OUTPUT);
pinMode(_mosi, OUTPUT);
pinMode(_miso, INPUT);
}
}
// check if sensor, i.e. the chip ID is correct
if (read8(BME280_REGISTER_CHIPID) != 0x60)
return false;
// reset the device using soft-reset
// this makes sure the IIR is off, etc.
write8(BME280_REGISTER_SOFTRESET, 0xB6);
// wait for chip to wake up.
delay(300);
// if chip is still reading calibration, delay
while (isReadingCalibration())
delay(100);
readCoefficients(); // read trimming parameters, see DS 4.2.2
setSampling(); // use defaults
delay(100);
return true;
}
/**************************************************************************/
/*!
@brief setup sensor with given parameters / settings
This is simply a overload to the normal begin()-function, so SPI users
don't get confused about the library requiring an address.
@param mode the power mode to use for the sensor
@param tempSampling the temp samping rate to use
@param pressSampling the pressure sampling rate to use
@param humSampling the humidity sampling rate to use
@param filter the filter mode to use
@param duration the standby duration to use
*/
/**************************************************************************/
void Adafruit_BME280::setSampling(sensor_mode mode,
sensor_sampling tempSampling,
sensor_sampling pressSampling,
sensor_sampling humSampling,
sensor_filter filter,
standby_duration duration) {
_measReg.mode = mode;
_measReg.osrs_t = tempSampling;
_measReg.osrs_p = pressSampling;
_humReg.osrs_h = humSampling;
_configReg.filter = filter;
_configReg.t_sb = duration;
// you must make sure to also set REGISTER_CONTROL after setting the
// CONTROLHUMID register, otherwise the values won't be applied (see DS 5.4.3)
write8(BME280_REGISTER_CONTROLHUMID, _humReg.get());
write8(BME280_REGISTER_CONFIG, _configReg.get());
write8(BME280_REGISTER_CONTROL, _measReg.get());
}
/**************************************************************************/
/*!
@brief Encapsulate hardware and software SPI transfer into one function
@param x the data byte to transfer
@returns the data byte read from the device
*/
/**************************************************************************/
uint8_t Adafruit_BME280::spixfer(uint8_t x) {
// hardware SPI
if (_sck == -1)
return SPI.transfer(x);
// software SPI
uint8_t reply = 0;
for (int i=7; i>=0; i--) {
reply <<= 1;
digitalWrite(_sck, LOW);
digitalWrite(_mosi, x & (1<<i));
digitalWrite(_sck, HIGH);
if (digitalRead(_miso))
reply |= 1;
}
return reply;
}
/**************************************************************************/
/*!
@brief Writes an 8 bit value over I2C or SPI
@param reg the register address to write to
@param value the value to write to the register
*/
/**************************************************************************/
void Adafruit_BME280::write8(byte reg, byte value) {
if (_cs == -1) {
_wire -> beginTransmission((uint8_t)_i2caddr);
_wire -> write((uint8_t)reg);
_wire -> write((uint8_t)value);
_wire -> endTransmission();
} else {
if (_sck == -1)
SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0));
digitalWrite(_cs, LOW);
spixfer(reg & ~0x80); // write, bit 7 low
spixfer(value);
digitalWrite(_cs, HIGH);
if (_sck == -1)
SPI.endTransaction(); // release the SPI bus
}
}
/**************************************************************************/
/*!
@brief Reads an 8 bit value over I2C or SPI
@param reg the register address to read from
@returns the data byte read from the device
*/
/**************************************************************************/
uint8_t Adafruit_BME280::read8(byte reg) {
uint8_t value;
if (_cs == -1) {
_wire -> beginTransmission((uint8_t)_i2caddr);
_wire -> write((uint8_t)reg);
_wire -> endTransmission();
_wire -> requestFrom((uint8_t)_i2caddr, (byte)1);
value = _wire -> read();
} else {
if (_sck == -1)
SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0));
digitalWrite(_cs, LOW);
spixfer(reg | 0x80); // read, bit 7 high
value = spixfer(0);
digitalWrite(_cs, HIGH);
if (_sck == -1)
SPI.endTransaction(); // release the SPI bus
}
return value;
}
/**************************************************************************/
/*!
@brief Reads a 16 bit value over I2C or SPI
@param reg the register address to read from
@returns the 16 bit data value read from the device
*/
/**************************************************************************/
uint16_t Adafruit_BME280::read16(byte reg)
{
uint16_t value;
if (_cs == -1) {
_wire -> beginTransmission((uint8_t)_i2caddr);
_wire -> write((uint8_t)reg);
_wire -> endTransmission();
_wire -> requestFrom((uint8_t)_i2caddr, (byte)2);
value = (_wire -> read() << 8) | _wire -> read();
} else {
if (_sck == -1)
SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0));
digitalWrite(_cs, LOW);
spixfer(reg | 0x80); // read, bit 7 high
value = (spixfer(0) << 8) | spixfer(0);
digitalWrite(_cs, HIGH);
if (_sck == -1)
SPI.endTransaction(); // release the SPI bus
}
return value;
}
/**************************************************************************/
/*!
@brief Reads a signed 16 bit little endian value over I2C or SPI
@param reg the register address to read from
@returns the 16 bit data value read from the device
*/
/**************************************************************************/
uint16_t Adafruit_BME280::read16_LE(byte reg) {
uint16_t temp = read16(reg);
return (temp >> 8) | (temp << 8);
}
/**************************************************************************/
/*!
@brief Reads a signed 16 bit value over I2C or SPI
@param reg the register address to read from
@returns the 16 bit data value read from the device
*/
/**************************************************************************/
int16_t Adafruit_BME280::readS16(byte reg)
{
return (int16_t)read16(reg);
}
/**************************************************************************/
/*!
@brief Reads a signed little endian 16 bit value over I2C or SPI
@param reg the register address to read from
@returns the 16 bit data value read from the device
*/
/**************************************************************************/
int16_t Adafruit_BME280::readS16_LE(byte reg)
{
return (int16_t)read16_LE(reg);
}
/**************************************************************************/
/*!
@brief Reads a 24 bit value over I2C
@param reg the register address to read from
@returns the 24 bit data value read from the device
*/
/**************************************************************************/
uint32_t Adafruit_BME280::read24(byte reg)
{
uint32_t value;
if (_cs == -1) {
_wire -> beginTransmission((uint8_t)_i2caddr);
_wire -> write((uint8_t)reg);
_wire -> endTransmission();
_wire -> requestFrom((uint8_t)_i2caddr, (byte)3);
value = _wire -> read();
value <<= 8;
value |= _wire -> read();
value <<= 8;
value |= _wire -> read();
} else {
if (_sck == -1)
SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0));
digitalWrite(_cs, LOW);
spixfer(reg | 0x80); // read, bit 7 high
value = spixfer(0);
value <<= 8;
value |= spixfer(0);
value <<= 8;
value |= spixfer(0);
digitalWrite(_cs, HIGH);
if (_sck == -1)
SPI.endTransaction(); // release the SPI bus
}
return value;
}
/**************************************************************************/
/*!
@brief Take a new measurement (only possible in forced mode)
*/
/**************************************************************************/
void Adafruit_BME280::takeForcedMeasurement()
{
// If we are in forced mode, the BME sensor goes back to sleep after each
// measurement and we need to set it to forced mode once at this point, so
// it will take the next measurement and then return to sleep again.
// In normal mode simply does new measurements periodically.
if (_measReg.mode == MODE_FORCED) {
// set to forced mode, i.e. "take next measurement"
write8(BME280_REGISTER_CONTROL, _measReg.get());
// wait until measurement has been completed, otherwise we would read
// the values from the last measurement
while (read8(BME280_REGISTER_STATUS) & 0x08)
delay(1);
}
}
/**************************************************************************/
/*!
@brief Reads the factory-set coefficients
*/
/**************************************************************************/
void Adafruit_BME280::readCoefficients(void)
{
_bme280_calib.dig_T1 = read16_LE(BME280_REGISTER_DIG_T1);
_bme280_calib.dig_T2 = readS16_LE(BME280_REGISTER_DIG_T2);
_bme280_calib.dig_T3 = readS16_LE(BME280_REGISTER_DIG_T3);
_bme280_calib.dig_P1 = read16_LE(BME280_REGISTER_DIG_P1);
_bme280_calib.dig_P2 = readS16_LE(BME280_REGISTER_DIG_P2);
_bme280_calib.dig_P3 = readS16_LE(BME280_REGISTER_DIG_P3);
_bme280_calib.dig_P4 = readS16_LE(BME280_REGISTER_DIG_P4);
_bme280_calib.dig_P5 = readS16_LE(BME280_REGISTER_DIG_P5);
_bme280_calib.dig_P6 = readS16_LE(BME280_REGISTER_DIG_P6);
_bme280_calib.dig_P7 = readS16_LE(BME280_REGISTER_DIG_P7);
_bme280_calib.dig_P8 = readS16_LE(BME280_REGISTER_DIG_P8);
_bme280_calib.dig_P9 = readS16_LE(BME280_REGISTER_DIG_P9);
_bme280_calib.dig_H1 = read8(BME280_REGISTER_DIG_H1);
_bme280_calib.dig_H2 = readS16_LE(BME280_REGISTER_DIG_H2);
_bme280_calib.dig_H3 = read8(BME280_REGISTER_DIG_H3);
_bme280_calib.dig_H4 = (read8(BME280_REGISTER_DIG_H4) << 4) | (read8(BME280_REGISTER_DIG_H4+1) & 0xF);
_bme280_calib.dig_H5 = (read8(BME280_REGISTER_DIG_H5+1) << 4) | (read8(BME280_REGISTER_DIG_H5) >> 4);
_bme280_calib.dig_H6 = (int8_t)read8(BME280_REGISTER_DIG_H6);
}
/**************************************************************************/
/*!
@brief return true if chip is busy reading cal data
@returns true if reading calibration, false otherwise
*/
/**************************************************************************/
bool Adafruit_BME280::isReadingCalibration(void)
{
uint8_t const rStatus = read8(BME280_REGISTER_STATUS);
return (rStatus & (1 << 0)) != 0;
}
/**************************************************************************/
/*!
@brief Returns the temperature from the sensor
@returns the temperature read from the device
*/
/**************************************************************************/
float Adafruit_BME280::readTemperature(void)
{
int32_t var1, var2;
int32_t adc_T = read24(BME280_REGISTER_TEMPDATA);
if (adc_T == 0x800000) // value in case temp measurement was disabled
return NAN;
adc_T >>= 4;
var1 = ((((adc_T>>3) - ((int32_t)_bme280_calib.dig_T1 <<1))) *
((int32_t)_bme280_calib.dig_T2)) >> 11;
var2 = (((((adc_T>>4) - ((int32_t)_bme280_calib.dig_T1)) *
((adc_T>>4) - ((int32_t)_bme280_calib.dig_T1))) >> 12) *
((int32_t)_bme280_calib.dig_T3)) >> 14;
t_fine = var1 + var2;
float T = (t_fine * 5 + 128) >> 8;
return T/100;
}
/**************************************************************************/
/*!
@brief Returns the pressure from the sensor
@returns the pressure value (in Pascal) read from the device
*/
/**************************************************************************/
float Adafruit_BME280::readPressure(void) {
int64_t var1, var2, p;
readTemperature(); // must be done first to get t_fine
int32_t adc_P = read24(BME280_REGISTER_PRESSUREDATA);
if (adc_P == 0x800000) // value in case pressure measurement was disabled
return NAN;
adc_P >>= 4;
var1 = ((int64_t)t_fine) - 128000;
var2 = var1 * var1 * (int64_t)_bme280_calib.dig_P6;
var2 = var2 + ((var1*(int64_t)_bme280_calib.dig_P5)<<17);
var2 = var2 + (((int64_t)_bme280_calib.dig_P4)<<35);
var1 = ((var1 * var1 * (int64_t)_bme280_calib.dig_P3)>>8) +
((var1 * (int64_t)_bme280_calib.dig_P2)<<12);
var1 = (((((int64_t)1)<<47)+var1))*((int64_t)_bme280_calib.dig_P1)>>33;
if (var1 == 0) {
return 0; // avoid exception caused by division by zero
}
p = 1048576 - adc_P;
p = (((p<<31) - var2)*3125) / var1;
var1 = (((int64_t)_bme280_calib.dig_P9) * (p>>13) * (p>>13)) >> 25;
var2 = (((int64_t)_bme280_calib.dig_P8) * p) >> 19;
p = ((p + var1 + var2) >> 8) + (((int64_t)_bme280_calib.dig_P7)<<4);
return (float)p/256;
}
/**************************************************************************/
/*!
@brief Returns the humidity from the sensor
@returns the humidity value read from the device
*/
/**************************************************************************/
float Adafruit_BME280::readHumidity(void) {
readTemperature(); // must be done first to get t_fine
int32_t adc_H = read16(BME280_REGISTER_HUMIDDATA);
if (adc_H == 0x8000) // value in case humidity measurement was disabled
return NAN;
int32_t v_x1_u32r;
v_x1_u32r = (t_fine - ((int32_t)76800));
v_x1_u32r = (((((adc_H << 14) - (((int32_t)_bme280_calib.dig_H4) << 20) -
(((int32_t)_bme280_calib.dig_H5) * v_x1_u32r)) + ((int32_t)16384)) >> 15) *
(((((((v_x1_u32r * ((int32_t)_bme280_calib.dig_H6)) >> 10) *
(((v_x1_u32r * ((int32_t)_bme280_calib.dig_H3)) >> 11) + ((int32_t)32768))) >> 10) +
((int32_t)2097152)) * ((int32_t)_bme280_calib.dig_H2) + 8192) >> 14));
v_x1_u32r = (v_x1_u32r - (((((v_x1_u32r >> 15) * (v_x1_u32r >> 15)) >> 7) *
((int32_t)_bme280_calib.dig_H1)) >> 4));
v_x1_u32r = (v_x1_u32r < 0) ? 0 : v_x1_u32r;
v_x1_u32r = (v_x1_u32r > 419430400) ? 419430400 : v_x1_u32r;
float h = (v_x1_u32r>>12);
return h / 1024.0;
}
/**************************************************************************/
/*!
Calculates the altitude (in meters) from the specified atmospheric
pressure (in hPa), and sea-level pressure (in hPa).
@param seaLevel Sea-level pressure in hPa
@returns the altitude value read from the device
*/
/**************************************************************************/
float Adafruit_BME280::readAltitude(float seaLevel)
{
// Equation taken from BMP180 datasheet (page 16):
// http://www.adafruit.com/datasheets/BST-BMP180-DS000-09.pdf
// Note that using the equation from wikipedia can give bad results
// at high altitude. See this thread for more information:
// http://forums.adafruit.com/viewtopic.php?f=22&t=58064
float atmospheric = readPressure() / 100.0F;
return 44330.0 * (1.0 - pow(atmospheric / seaLevel, 0.1903));
}
/**************************************************************************/
/*!
Calculates the pressure at sea level (in hPa) from the specified altitude
(in meters), and atmospheric pressure (in hPa).
@param altitude Altitude in meters
@param atmospheric Atmospheric pressure in hPa
@returns the pressure at sea level (in hPa) from the specified altitude
*/
/**************************************************************************/
float Adafruit_BME280::seaLevelForAltitude(float altitude, float atmospheric)
{
// Equation taken from BMP180 datasheet (page 17):
// http://www.adafruit.com/datasheets/BST-BMP180-DS000-09.pdf
// Note that using the equation from wikipedia can give bad results
// at high altitude. See this thread for more information:
// http://forums.adafruit.com/viewtopic.php?f=22&t=58064
return atmospheric / pow(1.0 - (altitude/44330.0), 5.255);
}

View File

@ -0,0 +1,331 @@
/*!
* @file Adafruit_BME280.h
*
* Designed specifically to work with the Adafruit BME280 Breakout
* ----> http://www.adafruit.com/products/2650
*
* These sensors use I2C or SPI to communicate, 2 or 4 pins are required
* to interface.
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit and open-source hardware by purchasing
* products from Adafruit!
*
* Written by Kevin "KTOWN" Townsend for Adafruit Industries.
*
* BSD license, all text here must be included in any redistribution.
*
*/
#ifndef __BME280_H__
#define __BME280_H__
#if (ARDUINO >= 100)
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include <Adafruit_Sensor.h>
#include <Wire.h>
/**************************************************************************/
/*!
@brief default I2C address
*/
/**************************************************************************/
#define BME280_ADDRESS (0x77)
/*=========================================================================*/
/**************************************************************************/
/*!
@brief Register addresses
*/
/**************************************************************************/
enum
{
BME280_REGISTER_DIG_T1 = 0x88,
BME280_REGISTER_DIG_T2 = 0x8A,
BME280_REGISTER_DIG_T3 = 0x8C,
BME280_REGISTER_DIG_P1 = 0x8E,
BME280_REGISTER_DIG_P2 = 0x90,
BME280_REGISTER_DIG_P3 = 0x92,
BME280_REGISTER_DIG_P4 = 0x94,
BME280_REGISTER_DIG_P5 = 0x96,
BME280_REGISTER_DIG_P6 = 0x98,
BME280_REGISTER_DIG_P7 = 0x9A,
BME280_REGISTER_DIG_P8 = 0x9C,
BME280_REGISTER_DIG_P9 = 0x9E,
BME280_REGISTER_DIG_H1 = 0xA1,
BME280_REGISTER_DIG_H2 = 0xE1,
BME280_REGISTER_DIG_H3 = 0xE3,
BME280_REGISTER_DIG_H4 = 0xE4,
BME280_REGISTER_DIG_H5 = 0xE5,
BME280_REGISTER_DIG_H6 = 0xE7,
BME280_REGISTER_CHIPID = 0xD0,
BME280_REGISTER_VERSION = 0xD1,
BME280_REGISTER_SOFTRESET = 0xE0,
BME280_REGISTER_CAL26 = 0xE1, // R calibration stored in 0xE1-0xF0
BME280_REGISTER_CONTROLHUMID = 0xF2,
BME280_REGISTER_STATUS = 0XF3,
BME280_REGISTER_CONTROL = 0xF4,
BME280_REGISTER_CONFIG = 0xF5,
BME280_REGISTER_PRESSUREDATA = 0xF7,
BME280_REGISTER_TEMPDATA = 0xFA,
BME280_REGISTER_HUMIDDATA = 0xFD
};
/**************************************************************************/
/*!
@brief calibration data
*/
/**************************************************************************/
typedef struct
{
uint16_t dig_T1; ///< temperature compensation value
int16_t dig_T2; ///< temperature compensation value
int16_t dig_T3; ///< temperature compensation value
uint16_t dig_P1; ///< pressure compensation value
int16_t dig_P2; ///< pressure compensation value
int16_t dig_P3; ///< pressure compensation value
int16_t dig_P4; ///< pressure compensation value
int16_t dig_P5; ///< pressure compensation value
int16_t dig_P6; ///< pressure compensation value
int16_t dig_P7; ///< pressure compensation value
int16_t dig_P8; ///< pressure compensation value
int16_t dig_P9; ///< pressure compensation value
uint8_t dig_H1; ///< humidity compensation value
int16_t dig_H2; ///< humidity compensation value
uint8_t dig_H3; ///< humidity compensation value
int16_t dig_H4; ///< humidity compensation value
int16_t dig_H5; ///< humidity compensation value
int8_t dig_H6; ///< humidity compensation value
} bme280_calib_data;
/*=========================================================================*/
/*
class Adafruit_BME280_Unified : public Adafruit_Sensor
{
public:
Adafruit_BME280_Unified(int32_t sensorID = -1);
bool begin(uint8_t addr = BME280_ADDRESS);
void getTemperature(float *temp);
void getPressure(float *pressure);
float pressureToAltitude(float seaLevel, float atmospheric, float temp);
float seaLevelForAltitude(float altitude, float atmospheric, float temp);
void getEvent(sensors_event_t*);
void getSensor(sensor_t*);
private:
uint8_t _i2c_addr;
int32_t _sensorID;
};
*/
/**************************************************************************/
/*!
@brief Class that stores state and functions for interacting with BME280 IC
*/
/**************************************************************************/
class Adafruit_BME280 {
public:
/**************************************************************************/
/*!
@brief sampling rates
*/
/**************************************************************************/
enum sensor_sampling {
SAMPLING_NONE = 0b000,
SAMPLING_X1 = 0b001,
SAMPLING_X2 = 0b010,
SAMPLING_X4 = 0b011,
SAMPLING_X8 = 0b100,
SAMPLING_X16 = 0b101
};
/**************************************************************************/
/*!
@brief power modes
*/
/**************************************************************************/
enum sensor_mode {
MODE_SLEEP = 0b00,
MODE_FORCED = 0b01,
MODE_NORMAL = 0b11
};
/**************************************************************************/
/*!
@brief filter values
*/
/**************************************************************************/
enum sensor_filter {
FILTER_OFF = 0b000,
FILTER_X2 = 0b001,
FILTER_X4 = 0b010,
FILTER_X8 = 0b011,
FILTER_X16 = 0b100
};
/**************************************************************************/
/*!
@brief standby duration in ms
*/
/**************************************************************************/
enum standby_duration {
STANDBY_MS_0_5 = 0b000,
STANDBY_MS_10 = 0b110,
STANDBY_MS_20 = 0b111,
STANDBY_MS_62_5 = 0b001,
STANDBY_MS_125 = 0b010,
STANDBY_MS_250 = 0b011,
STANDBY_MS_500 = 0b100,
STANDBY_MS_1000 = 0b101
};
// constructors
Adafruit_BME280(void);
Adafruit_BME280(int8_t cspin);
Adafruit_BME280(int8_t cspin, int8_t mosipin, int8_t misopin, int8_t sckpin);
bool begin(void);
bool begin(TwoWire *theWire);
bool begin(uint8_t addr);
bool begin(uint8_t addr, TwoWire *theWire);
bool init();
void setSampling(sensor_mode mode = MODE_NORMAL,
sensor_sampling tempSampling = SAMPLING_X16,
sensor_sampling pressSampling = SAMPLING_X16,
sensor_sampling humSampling = SAMPLING_X16,
sensor_filter filter = FILTER_OFF,
standby_duration duration = STANDBY_MS_0_5
);
void takeForcedMeasurement();
float readTemperature(void);
float readPressure(void);
float readHumidity(void);
float readAltitude(float seaLevel);
float seaLevelForAltitude(float altitude, float pressure);
private:
TwoWire *_wire;
void readCoefficients(void);
bool isReadingCalibration(void);
uint8_t spixfer(uint8_t x);
void write8(byte reg, byte value);
uint8_t read8(byte reg);
uint16_t read16(byte reg);
uint32_t read24(byte reg);
int16_t readS16(byte reg);
uint16_t read16_LE(byte reg); // little endian
int16_t readS16_LE(byte reg); // little endian
uint8_t _i2caddr;
int32_t _sensorID;
int32_t t_fine;
int8_t _cs, _mosi, _miso, _sck;
bme280_calib_data _bme280_calib;
// The config register
struct config {
// inactive duration (standby time) in normal mode
// 000 = 0.5 ms
// 001 = 62.5 ms
// 010 = 125 ms
// 011 = 250 ms
// 100 = 500 ms
// 101 = 1000 ms
// 110 = 10 ms
// 111 = 20 ms
unsigned int t_sb : 3;
// filter settings
// 000 = filter off
// 001 = 2x filter
// 010 = 4x filter
// 011 = 8x filter
// 100 and above = 16x filter
unsigned int filter : 3;
// unused - don't set
unsigned int none : 1;
unsigned int spi3w_en : 1;
unsigned int get() {
return (t_sb << 5) | (filter << 2) | spi3w_en;
}
};
config _configReg;
// The ctrl_meas register
struct ctrl_meas {
// temperature oversampling
// 000 = skipped
// 001 = x1
// 010 = x2
// 011 = x4
// 100 = x8
// 101 and above = x16
unsigned int osrs_t : 3;
// pressure oversampling
// 000 = skipped
// 001 = x1
// 010 = x2
// 011 = x4
// 100 = x8
// 101 and above = x16
unsigned int osrs_p : 3;
// device mode
// 00 = sleep
// 01 or 10 = forced
// 11 = normal
unsigned int mode : 2;
unsigned int get() {
return (osrs_t << 5) | (osrs_p << 2) | mode;
}
};
ctrl_meas _measReg;
// The ctrl_hum register
struct ctrl_hum {
// unused - don't set
unsigned int none : 5;
// pressure oversampling
// 000 = skipped
// 001 = x1
// 010 = x2
// 011 = x4
// 100 = x8
// 101 and above = x16
unsigned int osrs_h : 3;
unsigned int get() {
return (osrs_h);
}
};
ctrl_hum _humReg;
};
#endif

View File

@ -0,0 +1,63 @@
# Adafruit BME280 Library [![Build Status](https://travis-ci.org/adafruit/Adafruit_BME280_Library.svg?branch=master)](https://travis-ci.org/adafruit/Adafruit_BME280_Library)
<img src="https://cdn-shop.adafruit.com/970x728/2652-00.jpg" height="300"/>
This is a library for the Adafruit BME280 Humidity, Barometric Pressure + Temp sensor
Designed specifically to work with the Adafruit BME280 Breakout
* http://www.adafruit.com/products/2652
These sensors use I2C or SPI to communicate, up to 4 pins are required to interface
Use of this library also requires [Adafruit_Sensor](https://github.com/adafruit/Adafruit_Sensor)
to be installed on your local system.
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Check out the links above for our tutorials and wiring diagrams
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
To download. click the DOWNLOAD ZIP button, rename the uncompressed folder Adafruit_BME280.
Check that the Adafruit_BME280 folder contains Adafruit_BME280.cpp and Adafruit_BME280.h
Place the Adafruit_BME280 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
<!-- START COMPATIBILITY TABLE -->
## Compatibility
MCU | Tested Works | Doesn't Work | Not Tested | Notes
------------------ | :----------: | :----------: | :---------: | -----
Atmega328 @ 16MHz | X | | |
Atmega328 @ 12MHz | X | | |
Atmega32u4 @ 16MHz | X | | | Use SDA/SCL on pins D2 &amp; D3
Atmega32u4 @ 8MHz | X | | | Use SDA/SCL on pins D2 &amp; D3
ESP8266 | X | | | I2C: just works, SPI: SDA/SCL default to pins 4 &amp; 5 but any two pins can be assigned as SDA/SCL using Wire.begin(SDA,SCL)
ESP32 | X | | | I2C: just works, SPI: SDA/SCL default to pins 4 &amp; 5 but any two pins can be assigned as SDA/SCL using Wire.begin(SDA,SCL)
Atmega2560 @ 16MHz | X | | | Use SDA/SCL on pins 20 &amp; 21
ATSAM3X8E | X | | | Use SDA/SCL on pins 20 &amp; 21
ATSAM21D | X | | |
ATtiny85 @ 16MHz | | X | |
ATtiny85 @ 8MHz | | X | |
Intel Curie @ 32MHz | | | X |
STM32F2 | | | X |
* ATmega328 @ 16MHz : Arduino UNO, Adafruit Pro Trinket 5V, Adafruit Metro 328, Adafruit Metro Mini
* ATmega328 @ 12MHz : Adafruit Pro Trinket 3V
* ATmega32u4 @ 16MHz : Arduino Leonardo, Arduino Micro, Arduino Yun, Teensy 2.0
* ATmega32u4 @ 8MHz : Adafruit Flora, Bluefruit Micro
* ESP8266 : Adafruit Huzzah
* ATmega2560 @ 16MHz : Arduino Mega
* ATSAM3X8E : Arduino Due
* ATSAM21D : Arduino Zero, M0 Pro
* ATtiny85 @ 16MHz : Adafruit Trinket 5V
* ATtiny85 @ 8MHz : Adafruit Gemma, Arduino Gemma, Adafruit Trinket 3V
<!-- END COMPATIBILITY TABLE -->

View File

@ -0,0 +1,158 @@
/***************************************************************************
This is a library for the BME280 humidity, temperature & pressure sensor
Designed specifically to work with the Adafruit BME280 Breakout
----> http://www.adafruit.com/products/2650
These sensors use I2C or SPI to communicate, 2 or 4 pins are required
to interface. The device's I2C address is either 0x76 or 0x77.
Adafruit invests time and resources providing this open source code,
please support Adafruit andopen-source hardware by purchasing products
from Adafruit!
Written by Limor Fried & Kevin Townsend for Adafruit Industries.
BSD license, all text above must be included in any redistribution
***************************************************************************/
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#define BME_SCK 13
#define BME_MISO 12
#define BME_MOSI 11
#define BME_CS 10
#define SEALEVELPRESSURE_HPA (1013.25)
Adafruit_BME280 bme; // I2C
//Adafruit_BME280 bme(BME_CS); // hardware SPI
//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI
unsigned long delayTime;
void setup() {
Serial.begin(9600);
Serial.println(F("BME280 test"));
if (! bme.begin(&Wire)) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
while (1);
}
Serial.println("-- Default Test --");
Serial.println("normal mode, 16x oversampling for all, filter off,");
Serial.println("0.5ms standby period");
delayTime = 5000;
// For more details on the following scenarious, see chapter
// 3.5 "Recommended modes of operation" in the datasheet
/*
// weather monitoring
Serial.println("-- Weather Station Scenario --");
Serial.println("forced mode, 1x temperature / 1x humidity / 1x pressure oversampling,");
Serial.println("filter off");
bme.setSampling(Adafruit_BME280::MODE_FORCED,
Adafruit_BME280::SAMPLING_X1, // temperature
Adafruit_BME280::SAMPLING_X1, // pressure
Adafruit_BME280::SAMPLING_X1, // humidity
Adafruit_BME280::FILTER_OFF );
// suggested rate is 1/60Hz (1m)
delayTime = 60000; // in milliseconds
*/
/*
// humidity sensing
Serial.println("-- Humidity Sensing Scenario --");
Serial.println("forced mode, 1x temperature / 1x humidity / 0x pressure oversampling");
Serial.println("= pressure off, filter off");
bme.setSampling(Adafruit_BME280::MODE_FORCED,
Adafruit_BME280::SAMPLING_X1, // temperature
Adafruit_BME280::SAMPLING_NONE, // pressure
Adafruit_BME280::SAMPLING_X1, // humidity
Adafruit_BME280::FILTER_OFF );
// suggested rate is 1Hz (1s)
delayTime = 1000; // in milliseconds
*/
/*
// indoor navigation
Serial.println("-- Indoor Navigation Scenario --");
Serial.println("normal mode, 16x pressure / 2x temperature / 1x humidity oversampling,");
Serial.println("0.5ms standby period, filter 16x");
bme.setSampling(Adafruit_BME280::MODE_NORMAL,
Adafruit_BME280::SAMPLING_X2, // temperature
Adafruit_BME280::SAMPLING_X16, // pressure
Adafruit_BME280::SAMPLING_X1, // humidity
Adafruit_BME280::FILTER_X16,
Adafruit_BME280::STANDBY_MS_0_5 );
// suggested rate is 25Hz
// 1 + (2 * T_ovs) + (2 * P_ovs + 0.5) + (2 * H_ovs + 0.5)
// T_ovs = 2
// P_ovs = 16
// H_ovs = 1
// = 40ms (25Hz)
// with standby time that should really be 24.16913... Hz
delayTime = 41;
*/
/*
// gaming
Serial.println("-- Gaming Scenario --");
Serial.println("normal mode, 4x pressure / 1x temperature / 0x humidity oversampling,");
Serial.println("= humidity off, 0.5ms standby period, filter 16x");
bme.setSampling(Adafruit_BME280::MODE_NORMAL,
Adafruit_BME280::SAMPLING_X1, // temperature
Adafruit_BME280::SAMPLING_X4, // pressure
Adafruit_BME280::SAMPLING_NONE, // humidity
Adafruit_BME280::FILTER_X16,
Adafruit_BME280::STANDBY_MS_0_5 );
// Suggested rate is 83Hz
// 1 + (2 * T_ovs) + (2 * P_ovs + 0.5)
// T_ovs = 1
// P_ovs = 4
// = 11.5ms + 0.5ms standby
delayTime = 12;
*/
Serial.println();
}
void loop() {
// Only needed in forced mode! In normal mode, you can remove the next line.
bme.takeForcedMeasurement(); // has no effect in normal mode
printValues();
delay(delayTime);
}
void printValues() {
Serial.print("Temperature = ");
Serial.print(bme.readTemperature());
Serial.println(" *C");
Serial.print("Pressure = ");
Serial.print(bme.readPressure() / 100.0F);
Serial.println(" hPa");
Serial.print("Approx. Altitude = ");
Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
Serial.println(" m");
Serial.print("Humidity = ");
Serial.print(bme.readHumidity());
Serial.println(" %");
Serial.println();
}

View File

@ -0,0 +1,82 @@
/***************************************************************************
This is a library for the BME280 humidity, temperature & pressure sensor
Designed specifically to work with the Adafruit BME280 Breakout
----> http://www.adafruit.com/products/2650
These sensors use I2C or SPI to communicate, 2 or 4 pins are required
to interface. The device's I2C address is either 0x76 or 0x77.
Adafruit invests time and resources providing this open source code,
please support Adafruit andopen-source hardware by purchasing products
from Adafruit!
Written by Limor Fried & Kevin Townsend for Adafruit Industries.
BSD license, all text above must be included in any redistribution
***************************************************************************/
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#define BME_SCK 13
#define BME_MISO 12
#define BME_MOSI 11
#define BME_CS 10
#define SEALEVELPRESSURE_HPA (1013.25)
Adafruit_BME280 bme; // I2C
//Adafruit_BME280 bme(BME_CS); // hardware SPI
//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI
unsigned long delayTime;
void setup() {
Serial.begin(9600);
Serial.println(F("BME280 test"));
bool status;
// default settings
// (you can also pass in a Wire library object like &Wire2)
status = bme.begin();
if (!status) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
while (1);
}
Serial.println("-- Default Test --");
delayTime = 1000;
Serial.println();
}
void loop() {
printValues();
delay(delayTime);
}
void printValues() {
Serial.print("Temperature = ");
Serial.print(bme.readTemperature());
Serial.println(" *C");
Serial.print("Pressure = ");
Serial.print(bme.readPressure() / 100.0F);
Serial.println(" hPa");
Serial.print("Approx. Altitude = ");
Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
Serial.println(" m");
Serial.print("Humidity = ");
Serial.print(bme.readHumidity());
Serial.println(" %");
Serial.println();
}

View File

@ -0,0 +1,9 @@
name=Adafruit BME280 Library
version=1.0.8
author=Adafruit
maintainer=Adafruit <info@adafruit.com>
sentence=Arduino library for BME280 sensors.
paragraph=Arduino library for BME280 humidity and pressure sensors.
category=Sensors
url=https://github.com/adafruit/Adafruit_BME280_Library
architectures=*

View File

@ -0,0 +1,397 @@
/*!
* @file Adafruit_BMP280.cpp
*
* This is a library for the BMP280 orientation sensor
*
* Designed specifically to work with the Adafruit BMP280 Sensor.
*
* Pick one up today in the adafruit shop!
* ------> https://www.adafruit.com/product/2651
*
* These sensors use I2C to communicate, 2 pins are required to interface.
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit andopen-source hardware by purchasing products
* from Adafruit!
*
* K.Townsend (Adafruit Industries)
*
* BSD license, all text above must be included in any redistribution
*/
#include "Adafruit_BMP280.h"
#include "Arduino.h"
#include <Wire.h>
/*!
* @brief BMP280 constructor using i2c
* @param *theWire
* optional wire
*/
Adafruit_BMP280::Adafruit_BMP280(TwoWire *theWire)
: _cs(-1), _mosi(-1), _miso(-1), _sck(-1) {
_wire = theWire;
}
/*!
* @brief BMP280 constructor using hardware SPI
* @param cspin
* cs pin number
* @param theSPI
* optional SPI object
*/
Adafruit_BMP280::Adafruit_BMP280(int8_t cspin, SPIClass *theSPI)
: _cs(cspin), _mosi(-1), _miso(-1), _sck(-1) {
*_spi = *theSPI;
}
/*!
* @brief BMP280 constructor using bitbang SPI
* @param cspin
* The pin to use for CS/SSEL.
* @param mosipin
* The pin to use for MOSI.
* @param misopin
* The pin to use for MISO.
* @param sckpin
* The pin to use for SCK.
*/
Adafruit_BMP280::Adafruit_BMP280(int8_t cspin, int8_t mosipin, int8_t misopin,
int8_t sckpin)
: _cs(cspin), _mosi(mosipin), _miso(misopin), _sck(sckpin) {}
/*!
* Initialises the sensor.
* @param addr
* The I2C address to use (default = 0x77)
* @param chipid
* The expected chip ID (used to validate connection).
* @return True if the init was successful, otherwise false.
*/
bool Adafruit_BMP280::begin(uint8_t addr, uint8_t chipid) {
_i2caddr = addr;
if (_cs == -1) {
// i2c
_wire->begin();
} else {
digitalWrite(_cs, HIGH);
pinMode(_cs, OUTPUT);
if (_sck == -1) {
// hardware SPI
_spi->begin();
} else {
// software SPI
pinMode(_sck, OUTPUT);
pinMode(_mosi, OUTPUT);
pinMode(_miso, INPUT);
}
}
if (read8(BMP280_REGISTER_CHIPID) != chipid)
return false;
readCoefficients();
// write8(BMP280_REGISTER_CONTROL, 0x3F); /* needed? */
setSampling();
delay(100);
return true;
}
/*!
* Sets the sampling config for the device.
* @param mode
* The operating mode of the sensor.
* @param tempSampling
* The sampling scheme for temp readings.
* @param pressSampling
* The sampling scheme for pressure readings.
* @param filter
* The filtering mode to apply (if any).
* @param duration
* The sampling duration.
*/
void Adafruit_BMP280::setSampling(sensor_mode mode,
sensor_sampling tempSampling,
sensor_sampling pressSampling,
sensor_filter filter,
standby_duration duration) {
_measReg.mode = mode;
_measReg.osrs_t = tempSampling;
_measReg.osrs_p = pressSampling;
_configReg.filter = filter;
_configReg.t_sb = duration;
write8(BMP280_REGISTER_CONFIG, _configReg.get());
write8(BMP280_REGISTER_CONTROL, _measReg.get());
}
uint8_t Adafruit_BMP280::spixfer(uint8_t x) {
if (_sck == -1)
return SPI.transfer(x);
// software spi
// Serial.println("Software SPI");
uint8_t reply = 0;
for (int i = 7; i >= 0; i--) {
reply <<= 1;
digitalWrite(_sck, LOW);
digitalWrite(_mosi, x & (1 << i));
digitalWrite(_sck, HIGH);
if (digitalRead(_miso))
reply |= 1;
}
return reply;
}
/**************************************************************************/
/*!
@brief Writes an 8 bit value over I2C/SPI
*/
/**************************************************************************/
void Adafruit_BMP280::write8(byte reg, byte value) {
if (_cs == -1) {
_wire->beginTransmission((uint8_t)_i2caddr);
_wire->write((uint8_t)reg);
_wire->write((uint8_t)value);
_wire->endTransmission();
} else {
if (_sck == -1)
_spi->beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0));
digitalWrite(_cs, LOW);
spixfer(reg & ~0x80); // write, bit 7 low
spixfer(value);
digitalWrite(_cs, HIGH);
if (_sck == -1)
_spi->endTransaction(); // release the SPI bus
}
}
/*!
* @brief Reads an 8 bit value over I2C/SPI
* @param reg
* selected register
* @return value from selected register
*/
uint8_t Adafruit_BMP280::read8(byte reg) {
uint8_t value;
if (_cs == -1) {
_wire->beginTransmission((uint8_t)_i2caddr);
_wire->write((uint8_t)reg);
_wire->endTransmission();
_wire->requestFrom((uint8_t)_i2caddr, (byte)1);
value = _wire->read();
} else {
if (_sck == -1)
_spi->beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0));
digitalWrite(_cs, LOW);
spixfer(reg | 0x80); // read, bit 7 high
value = spixfer(0);
digitalWrite(_cs, HIGH);
if (_sck == -1)
_spi->endTransaction(); // release the SPI bus
}
return value;
}
/*!
* @brief Reads a 16 bit value over I2C/SPI
*/
uint16_t Adafruit_BMP280::read16(byte reg) {
uint16_t value;
if (_cs == -1) {
_wire->beginTransmission((uint8_t)_i2caddr);
_wire->write((uint8_t)reg);
_wire->endTransmission();
_wire->requestFrom((uint8_t)_i2caddr, (byte)2);
value = (_wire->read() << 8) | _wire->read();
} else {
if (_sck == -1)
_spi->beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0));
digitalWrite(_cs, LOW);
spixfer(reg | 0x80); // read, bit 7 high
value = (spixfer(0) << 8) | spixfer(0);
digitalWrite(_cs, HIGH);
if (_sck == -1)
_spi->endTransaction(); // release the SPI bus
}
return value;
}
uint16_t Adafruit_BMP280::read16_LE(byte reg) {
uint16_t temp = read16(reg);
return (temp >> 8) | (temp << 8);
}
/*!
* @brief Reads a signed 16 bit value over I2C/SPI
*/
int16_t Adafruit_BMP280::readS16(byte reg) { return (int16_t)read16(reg); }
int16_t Adafruit_BMP280::readS16_LE(byte reg) {
return (int16_t)read16_LE(reg);
}
/*!
* @brief Reads a 24 bit value over I2C/SPI
*/
uint32_t Adafruit_BMP280::read24(byte reg) {
uint32_t value;
if (_cs == -1) {
_wire->beginTransmission((uint8_t)_i2caddr);
_wire->write((uint8_t)reg);
_wire->endTransmission();
_wire->requestFrom((uint8_t)_i2caddr, (byte)3);
value = _wire->read();
value <<= 8;
value |= _wire->read();
value <<= 8;
value |= _wire->read();
} else {
if (_sck == -1)
_spi->beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0));
digitalWrite(_cs, LOW);
spixfer(reg | 0x80); // read, bit 7 high
value = spixfer(0);
value <<= 8;
value |= spixfer(0);
value <<= 8;
value |= spixfer(0);
digitalWrite(_cs, HIGH);
if (_sck == -1)
_spi->endTransaction(); // release the SPI bus
}
return value;
}
/*!
* @brief Reads the factory-set coefficients
*/
void Adafruit_BMP280::readCoefficients() {
_bmp280_calib.dig_T1 = read16_LE(BMP280_REGISTER_DIG_T1);
_bmp280_calib.dig_T2 = readS16_LE(BMP280_REGISTER_DIG_T2);
_bmp280_calib.dig_T3 = readS16_LE(BMP280_REGISTER_DIG_T3);
_bmp280_calib.dig_P1 = read16_LE(BMP280_REGISTER_DIG_P1);
_bmp280_calib.dig_P2 = readS16_LE(BMP280_REGISTER_DIG_P2);
_bmp280_calib.dig_P3 = readS16_LE(BMP280_REGISTER_DIG_P3);
_bmp280_calib.dig_P4 = readS16_LE(BMP280_REGISTER_DIG_P4);
_bmp280_calib.dig_P5 = readS16_LE(BMP280_REGISTER_DIG_P5);
_bmp280_calib.dig_P6 = readS16_LE(BMP280_REGISTER_DIG_P6);
_bmp280_calib.dig_P7 = readS16_LE(BMP280_REGISTER_DIG_P7);
_bmp280_calib.dig_P8 = readS16_LE(BMP280_REGISTER_DIG_P8);
_bmp280_calib.dig_P9 = readS16_LE(BMP280_REGISTER_DIG_P9);
}
/*!
* Reads the temperature from the device.
* @return The temperature in degress celcius.
*/
float Adafruit_BMP280::readTemperature() {
int32_t var1, var2;
int32_t adc_T = read24(BMP280_REGISTER_TEMPDATA);
adc_T >>= 4;
var1 = ((((adc_T >> 3) - ((int32_t)_bmp280_calib.dig_T1 << 1))) *
((int32_t)_bmp280_calib.dig_T2)) >>
11;
var2 = (((((adc_T >> 4) - ((int32_t)_bmp280_calib.dig_T1)) *
((adc_T >> 4) - ((int32_t)_bmp280_calib.dig_T1))) >>
12) *
((int32_t)_bmp280_calib.dig_T3)) >>
14;
t_fine = var1 + var2;
float T = (t_fine * 5 + 128) >> 8;
return T / 100;
}
/*!
* Reads the barometric pressure from the device.
* @return Barometric pressure in hPa.
*/
float Adafruit_BMP280::readPressure() {
int64_t var1, var2, p;
// Must be done first to get the t_fine variable set up
readTemperature();
int32_t adc_P = read24(BMP280_REGISTER_PRESSUREDATA);
adc_P >>= 4;
var1 = ((int64_t)t_fine) - 128000;
var2 = var1 * var1 * (int64_t)_bmp280_calib.dig_P6;
var2 = var2 + ((var1 * (int64_t)_bmp280_calib.dig_P5) << 17);
var2 = var2 + (((int64_t)_bmp280_calib.dig_P4) << 35);
var1 = ((var1 * var1 * (int64_t)_bmp280_calib.dig_P3) >> 8) +
((var1 * (int64_t)_bmp280_calib.dig_P2) << 12);
var1 =
(((((int64_t)1) << 47) + var1)) * ((int64_t)_bmp280_calib.dig_P1) >> 33;
if (var1 == 0) {
return 0; // avoid exception caused by division by zero
}
p = 1048576 - adc_P;
p = (((p << 31) - var2) * 3125) / var1;
var1 = (((int64_t)_bmp280_calib.dig_P9) * (p >> 13) * (p >> 13)) >> 25;
var2 = (((int64_t)_bmp280_calib.dig_P8) * p) >> 19;
p = ((p + var1 + var2) >> 8) + (((int64_t)_bmp280_calib.dig_P7) << 4);
return (float)p / 256;
}
/*!
* @brief Calculates the approximate altitude using barometric pressure and the
* supplied sea level hPa as a reference.
* @param seaLevelhPa
* The current hPa at sea level.
* @return The approximate altitude above sea level in meters.
*/
float Adafruit_BMP280::readAltitude(float seaLevelhPa) {
float altitude;
float pressure = readPressure(); // in Si units for Pascal
pressure /= 100;
altitude = 44330 * (1.0 - pow(pressure / seaLevelhPa, 0.1903));
return altitude;
}
/*!
* @brief Take a new measurement (only possible in forced mode)
* !!!todo!!!
*/
/*
void Adafruit_BMP280::takeForcedMeasurement()
{
// If we are in forced mode, the BME sensor goes back to sleep after each
// measurement and we need to set it to forced mode once at this point, so
// it will take the next measurement and then return to sleep again.
// In normal mode simply does new measurements periodically.
if (_measReg.mode == MODE_FORCED) {
// set to forced mode, i.e. "take next measurement"
write8(BMP280_REGISTER_CONTROL, _measReg.get());
// wait until measurement has been completed, otherwise we would read
// the values from the last measurement
while (read8(BMP280_REGISTER_STATUS) & 0x08)
delay(1);
}
}
*/

View File

@ -0,0 +1,226 @@
/*!
* @file Adafruit_BMP280.h
*
* This is a library for the Adafruit BMP280 Breakout.
*
* Designed specifically to work with the Adafruit BMP280 Breakout.
*
* Pick one up today in the adafruit shop!
* ------> https://www.adafruit.com/product/2651
*
* These sensors use I2C to communicate, 2 pins are required to interface.
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit andopen-source hardware by purchasing products
* from Adafruit!
*
* K.Townsend (Adafruit Industries)
*
* BSD license, all text above must be included in any redistribution
*/
#ifndef __BMP280_H__
#define __BMP280_H__
#include "Arduino.h"
#include <Wire.h>
#include <SPI.h>
/*!
* I2C ADDRESS/BITS/SETTINGS
*/
#define BMP280_ADDRESS (0x77) /**< The default I2C address for the sensor. */
#define BMP280_ADDRESS_ALT \
(0x76) /**< Alternative I2C address for the sensor. */
#define BMP280_CHIPID (0x58) /**< Default chip ID. */
/*!
* Registers available on the sensor.
*/
enum {
BMP280_REGISTER_DIG_T1 = 0x88,
BMP280_REGISTER_DIG_T2 = 0x8A,
BMP280_REGISTER_DIG_T3 = 0x8C,
BMP280_REGISTER_DIG_P1 = 0x8E,
BMP280_REGISTER_DIG_P2 = 0x90,
BMP280_REGISTER_DIG_P3 = 0x92,
BMP280_REGISTER_DIG_P4 = 0x94,
BMP280_REGISTER_DIG_P5 = 0x96,
BMP280_REGISTER_DIG_P6 = 0x98,
BMP280_REGISTER_DIG_P7 = 0x9A,
BMP280_REGISTER_DIG_P8 = 0x9C,
BMP280_REGISTER_DIG_P9 = 0x9E,
BMP280_REGISTER_CHIPID = 0xD0,
BMP280_REGISTER_VERSION = 0xD1,
BMP280_REGISTER_SOFTRESET = 0xE0,
BMP280_REGISTER_CAL26 = 0xE1, /**< R calibration = 0xE1-0xF0 */
BMP280_REGISTER_CONTROL = 0xF4,
BMP280_REGISTER_CONFIG = 0xF5,
BMP280_REGISTER_PRESSUREDATA = 0xF7,
BMP280_REGISTER_TEMPDATA = 0xFA,
};
/*!
* Struct to hold calibration data.
*/
typedef struct {
uint16_t dig_T1; /**< dig_T1 cal register. */
int16_t dig_T2; /**< dig_T2 cal register. */
int16_t dig_T3; /**< dig_T3 cal register. */
uint16_t dig_P1; /**< dig_P1 cal register. */
int16_t dig_P2; /**< dig_P2 cal register. */
int16_t dig_P3; /**< dig_P3 cal register. */
int16_t dig_P4; /**< dig_P4 cal register. */
int16_t dig_P5; /**< dig_P5 cal register. */
int16_t dig_P6; /**< dig_P6 cal register. */
int16_t dig_P7; /**< dig_P7 cal register. */
int16_t dig_P8; /**< dig_P8 cal register. */
int16_t dig_P9; /**< dig_P9 cal register. */
uint8_t dig_H1; /**< dig_H1 cal register. */
int16_t dig_H2; /**< dig_H2 cal register. */
uint8_t dig_H3; /**< dig_H3 cal register. */
int16_t dig_H4; /**< dig_H4 cal register. */
int16_t dig_H5; /**< dig_H5 cal register. */
int8_t dig_H6; /**< dig_H6 cal register. */
} bmp280_calib_data;
/**
* Driver for the Adafruit BMP280 barometric pressure sensor.
*/
class Adafruit_BMP280 {
public:
/** Oversampling rate for the sensor. */
enum sensor_sampling {
/** No over-sampling. */
SAMPLING_NONE = 0x00,
/** 1x over-sampling. */
SAMPLING_X1 = 0x01,
/** 2x over-sampling. */
SAMPLING_X2 = 0x02,
/** 4x over-sampling. */
SAMPLING_X4 = 0x03,
/** 8x over-sampling. */
SAMPLING_X8 = 0x04,
/** 16x over-sampling. */
SAMPLING_X16 = 0x05
};
/** Operating mode for the sensor. */
enum sensor_mode {
/** Sleep mode. */
MODE_SLEEP = 0x00,
/** Forced mode. */
MODE_FORCED = 0x01,
/** Normal mode. */
MODE_NORMAL = 0x03,
/** Software reset. */
MODE_SOFT_RESET_CODE = 0xB6
};
/** Filtering level for sensor data. */
enum sensor_filter {
/** No filtering. */
FILTER_OFF = 0x00,
/** 2x filtering. */
FILTER_X2 = 0x01,
/** 4x filtering. */
FILTER_X4 = 0x02,
/** 8x filtering. */
FILTER_X8 = 0x03,
/** 16x filtering. */
FILTER_X16 = 0x04
};
/** Standby duration in ms */
enum standby_duration {
/** 1 ms standby. */
STANDBY_MS_1 = 0x00,
/** 63 ms standby. */
STANDBY_MS_63 = 0x01,
/** 125 ms standby. */
STANDBY_MS_125 = 0x02,
/** 250 ms standby. */
STANDBY_MS_250 = 0x03,
/** 500 ms standby. */
STANDBY_MS_500 = 0x04,
/** 1000 ms standby. */
STANDBY_MS_1000 = 0x05,
/** 2000 ms standby. */
STANDBY_MS_2000 = 0x06,
/** 4000 ms standby. */
STANDBY_MS_4000 = 0x07
};
Adafruit_BMP280(TwoWire *theWire = &Wire);
Adafruit_BMP280(int8_t cspin, SPIClass *theSPI = &SPI);
Adafruit_BMP280(int8_t cspin, int8_t mosipin, int8_t misopin, int8_t sckpin);
bool begin(uint8_t addr = BMP280_ADDRESS, uint8_t chipid = BMP280_CHIPID);
float readTemperature();
float readPressure(void);
float readAltitude(float seaLevelhPa = 1013.25);
// void takeForcedMeasurement();
void setSampling(sensor_mode mode = MODE_NORMAL,
sensor_sampling tempSampling = SAMPLING_X16,
sensor_sampling pressSampling = SAMPLING_X16,
sensor_filter filter = FILTER_OFF,
standby_duration duration = STANDBY_MS_1);
TwoWire *_wire; /**< Wire object */
SPIClass *_spi; /**< SPI object */
private:
/** Encapsulates the config register */
struct config {
/** Inactive duration (standby time) in normal mode */
unsigned int t_sb : 3;
/** Filter settings */
unsigned int filter : 3;
/** Unused - don't set */
unsigned int none : 1;
/** Enables 3-wire SPI */
unsigned int spi3w_en : 1;
/** Used to retrieve the assembled config register's byte value. */
unsigned int get() { return (t_sb << 5) | (filter << 2) | spi3w_en; }
};
/** Encapsulates trhe ctrl_meas register */
struct ctrl_meas {
/** Temperature oversampling. */
unsigned int osrs_t : 3;
/** Pressure oversampling. */
unsigned int osrs_p : 3;
/** Device mode */
unsigned int mode : 2;
/** Used to retrieve the assembled ctrl_meas register's byte value. */
unsigned int get() { return (osrs_t << 5) | (osrs_p << 2) | mode; }
};
void readCoefficients(void);
uint8_t spixfer(uint8_t x);
void write8(byte reg, byte value);
uint8_t read8(byte reg);
uint16_t read16(byte reg);
uint32_t read24(byte reg);
int16_t readS16(byte reg);
uint16_t read16_LE(byte reg);
int16_t readS16_LE(byte reg);
uint8_t _i2caddr;
int32_t _sensorID;
int32_t t_fine;
int8_t _cs, _mosi, _miso, _sck;
bmp280_calib_data _bmp280_calib;
config _configReg;
ctrl_meas _measReg;
};
#endif

View File

@ -0,0 +1,47 @@
# Adafruit BMP280 Driver (Barometric Pressure Sensor) [![Build Status](https://travis-ci.org/adafruit/Adafruit_BMP280_Library.svg?branch=master)](https://travis-ci.org/adafruit/Adafruit_BMP280_Library)
This driver is for the [Adafruit BMP280 Breakout](http://www.adafruit.com/products/2651)
<a href="https://www.adafruit.com/product/2651"><img src="assets/board.jpg" width="500"/></a>
## About the BMP280 ##
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!
## About this Driver ##
Adafruit invests time and resources providing this open source code. Please support Adafruit and open-source hardware by purchasing products from Adafruit!
Written by Kevin (KTOWN) Townsend for Adafruit Industries.
<!-- START COMPATIBILITY TABLE -->
## Compatibility
MCU | Tested Works | Doesn't Work | Not Tested | Notes
------------------ | :----------: | :----------: | :---------: | -----
Atmega328 @ 16MHz | X | | |
Atmega328 @ 12MHz | X | | |
Atmega32u4 @ 16MHz | X | | | Use SDA/SCL on pins D2 &amp; D3
Atmega32u4 @ 8MHz | X | | | Use SDA/SCL on pins D2 &amp; D3
ESP8266 | X | | | SDA/SCL default to pins 4 &amp; 5 but any two pins can be assigned as SDA/SCL using Wire.begin(SDA,SCL)
Atmega2560 @ 16MHz | X | | | Use SDA/SCL on pins 20 &amp; 21
ATSAM3X8E | X | | | Use SDA/SCL on pins 20 &amp; 21
ATSAM21D | X | | |
ATtiny85 @ 16MHz | | X | |
ATtiny85 @ 8MHz | | X | |
Intel Curie @ 32MHz | | | X |
STM32F2 | | | X |
* ATmega328 @ 16MHz : Arduino UNO, Adafruit Pro Trinket 5V, Adafruit Metro 328, Adafruit Metro Mini
* ATmega328 @ 12MHz : Adafruit Pro Trinket 3V
* ATmega32u4 @ 16MHz : Arduino Leonardo, Arduino Micro, Arduino Yun, Teensy 2.0
* ATmega32u4 @ 8MHz : Adafruit Flora, Bluefruit Micro
* ESP8266 : Adafruit Huzzah
* ATmega2560 @ 16MHz : Arduino Mega
* ATSAM3X8E : Arduino Due
* ATSAM21D : Arduino Zero, M0 Pro
* ATtiny85 @ 16MHz : Adafruit Trinket 5V
* ATtiny85 @ 8MHz : Adafruit Gemma, Arduino Gemma, Adafruit Trinket 3V
<!-- END COMPATIBILITY TABLE -->

Binary file not shown.

After

Width:  |  Height:  |  Size: 453 KiB

View File

@ -0,0 +1,63 @@
/***************************************************************************
This is a library for the BMP280 humidity, temperature & pressure sensor
Designed specifically to work with the Adafruit BMEP280 Breakout
----> http://www.adafruit.com/products/2651
These sensors use I2C or SPI to communicate, 2 or 4 pins are required
to interface.
Adafruit invests time and resources providing this open source code,
please support Adafruit andopen-source hardware by purchasing products
from Adafruit!
Written by Limor Fried & Kevin Townsend for Adafruit Industries.
BSD license, all text above must be included in any redistribution
***************************************************************************/
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_BMP280.h>
#define BMP_SCK (13)
#define BMP_MISO (12)
#define BMP_MOSI (11)
#define BMP_CS (10)
Adafruit_BMP280 bmp; // I2C
//Adafruit_BMP280 bmp(BMP_CS); // hardware SPI
//Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO, BMP_SCK);
void setup() {
Serial.begin(9600);
Serial.println(F("BMP280 test"));
if (!bmp.begin()) {
Serial.println(F("Could not find a valid BMP280 sensor, check wiring!"));
while (1);
}
/* Default settings from datasheet. */
bmp.setSampling(Adafruit_BMP280::MODE_NORMAL, /* Operating Mode. */
Adafruit_BMP280::SAMPLING_X2, /* Temp. oversampling */
Adafruit_BMP280::SAMPLING_X16, /* Pressure oversampling */
Adafruit_BMP280::FILTER_X16, /* Filtering. */
Adafruit_BMP280::STANDBY_MS_500); /* Standby time. */
}
void loop() {
Serial.print(F("Temperature = "));
Serial.print(bmp.readTemperature());
Serial.println(" *C");
Serial.print(F("Pressure = "));
Serial.print(bmp.readPressure());
Serial.println(" Pa");
Serial.print(F("Approx altitude = "));
Serial.print(bmp.readAltitude(1013.25)); /* Adjusted to local forecast! */
Serial.println(" m");
Serial.println();
delay(2000);
}

View File

@ -0,0 +1,9 @@
name=Adafruit BMP280 Library
version=1.0.3
author=Adafruit
maintainer=Adafruit <info@adafruit.com>
sentence=Arduino library for BMP280 sensors.
paragraph=Arduino library for BMP280 pressure and altitude sensors.
category=Sensors
url=https://github.com/adafruit/Adafruit_BMP280_Library
architectures=*

View File

@ -0,0 +1,258 @@
#include <Adafruit_BusIO_Register.h>
/*!
* @brief Create a register we access over an I2C Device (which defines the bus and address)
* @param i2cdevice The I2CDevice to use for underlying I2C access
* @param reg_addr The address pointer value for the I2C/SMBus register, can be 8 or 16 bits
* @param width The width of the register data itself, defaults to 1 byte
* @param bitorder The bit order of the register (used when width is > 1), defaults to LSBFIRST
* @param address_width The width of the register address itself, defaults to 1 byte
*/
Adafruit_BusIO_Register::Adafruit_BusIO_Register(Adafruit_I2CDevice *i2cdevice, uint16_t reg_addr,
uint8_t width, uint8_t bitorder, uint8_t address_width) {
_i2cdevice = i2cdevice;
_spidevice = NULL;
_addrwidth = address_width;
_address = reg_addr;
_bitorder = bitorder;
_width = width;
}
/*!
* @brief Create a register we access over an SPI Device (which defines the bus and CS pin)
* @param spidevice The SPIDevice to use for underlying I2C access
* @param reg_addr The address pointer value for the I2C/SMBus register, can be 8 or 16 bits
* @param type The method we use to read/write data to SPI (which is not as well defined as I2C)
* @param width The width of the register data itself, defaults to 1 byte
* @param bitorder The bit order of the register (used when width is > 1), defaults to LSBFIRST
* @param address_width The width of the register address itself, defaults to 1 byte
*/
Adafruit_BusIO_Register::Adafruit_BusIO_Register(Adafruit_SPIDevice *spidevice, uint16_t reg_addr,
Adafruit_BusIO_SPIRegType type,
uint8_t width, uint8_t bitorder, uint8_t address_width) {
_spidevice = spidevice;
_spiregtype = type;
_i2cdevice = NULL;
_addrwidth = address_width;
_address = reg_addr;
_bitorder = bitorder;
_width = width;
}
/*!
* @brief Create a register we access over an I2C or SPI Device. This is a handy function because we
* can pass in NULL for the unused interface, allowing libraries to mass-define all the registers
* @param i2cdevice The I2CDevice to use for underlying I2C access, if NULL we use SPI
* @param spidevice The SPIDevice to use for underlying I2C access, if NULL we use I2C
* @param reg_addr The address pointer value for the I2C/SMBus register, can be 8 or 16 bits
* @param type The method we use to read/write data to SPI (which is not as well defined as I2C)
* @param width The width of the register data itself, defaults to 1 byte
* @param bitorder The bit order of the register (used when width is > 1), defaults to LSBFIRST
* @param address_width The width of the register address itself, defaults to 1 byte
*/
Adafruit_BusIO_Register::Adafruit_BusIO_Register(Adafruit_I2CDevice *i2cdevice, Adafruit_SPIDevice *spidevice,
Adafruit_BusIO_SPIRegType type, uint16_t reg_addr,
uint8_t width, uint8_t bitorder, uint8_t address_width) {
_spidevice = spidevice;
_i2cdevice = i2cdevice;
_spiregtype = type;
_addrwidth = address_width;
_address = reg_addr;
_bitorder = bitorder;
_width = width;
}
/*!
* @brief Write a buffer of data to the register location
* @param buffer Pointer to data to write
* @param len Number of bytes to write
* @return True on successful write (only really useful for I2C as SPI is uncheckable)
*/
bool Adafruit_BusIO_Register::write(uint8_t *buffer, uint8_t len) {
uint8_t addrbuffer[2] = {(uint8_t)(_address & 0xFF), (uint8_t)(_address>>8)};
if (_i2cdevice) {
return _i2cdevice->write(buffer, len, true, addrbuffer, _addrwidth);
}
if (_spidevice) {
if (_spiregtype == ADDRBIT8_HIGH_TOREAD) {
addrbuffer[0] &= ~0x80;
}
return _spidevice->write( buffer, len, addrbuffer, _addrwidth);
}
return false;
}
/*!
* @brief Write up to 4 bytes of data to the register location
* @param value Data to write
* @param numbytes How many bytes from 'value' to write
* @return True on successful write (only really useful for I2C as SPI is uncheckable)
*/
bool Adafruit_BusIO_Register::write(uint32_t value, uint8_t numbytes) {
if (numbytes == 0) {
numbytes = _width;
}
if (numbytes > 4) {
return false;
}
for (int i=0; i<numbytes; i++) {
if (_bitorder == LSBFIRST) {
_buffer[i] = value & 0xFF;
} else {
_buffer[numbytes-i-1] = value & 0xFF;
}
value >>= 8;
}
return write(_buffer, numbytes);
}
/*!
* @brief Read data from the register location. This does not do any error checking!
* @return Returns 0xFFFFFFFF on failure, value otherwise
*/
uint32_t Adafruit_BusIO_Register::read(void) {
if (! read(_buffer, _width)) {
return -1;
}
uint32_t value = 0;
for (int i=0; i < _width; i++) {
value <<= 8;
if (_bitorder == LSBFIRST) {
value |= _buffer[_width-i-1];
} else {
value |= _buffer[i];
}
}
return value;
}
/*!
* @brief Read a buffer of data from the register location
* @param buffer Pointer to data to read into
* @param len Number of bytes to read
* @return True on successful write (only really useful for I2C as SPI is uncheckable)
*/
bool Adafruit_BusIO_Register::read(uint8_t *buffer, uint8_t len) {
uint8_t addrbuffer[2] = {(uint8_t)(_address & 0xFF), (uint8_t)(_address>>8)};
if (_i2cdevice) {
return _i2cdevice->write_then_read(addrbuffer, _addrwidth, buffer, len);
}
if (_spidevice) {
if (_spiregtype == ADDRBIT8_HIGH_TOREAD) {
addrbuffer[0] |= 0x80;
}
return _spidevice->write_then_read(addrbuffer, _addrwidth, buffer, len);
}
return false;
}
/*!
* @brief Read 2 bytes of data from the register location
* @param value Pointer to uint16_t variable to read into
* @return True on successful write (only really useful for I2C as SPI is uncheckable)
*/
bool Adafruit_BusIO_Register::read(uint16_t *value) {
if (! read(_buffer, 2)) {
return false;
}
if (_bitorder == LSBFIRST) {
*value = _buffer[1];
*value <<= 8;
*value |= _buffer[0];
} else {
*value = _buffer[0];
*value <<= 8;
*value |= _buffer[1];
}
return true;
}
/*!
* @brief Read 1 byte of data from the register location
* @param value Pointer to uint8_t variable to read into
* @return True on successful write (only really useful for I2C as SPI is uncheckable)
*/
bool Adafruit_BusIO_Register::read(uint8_t *value) {
if (! read(_buffer, 1)) {
return false;
}
*value = _buffer[0];
return true;
}
/*!
* @brief Pretty printer for this register
* @param s The Stream to print to, defaults to &Serial
*/
void Adafruit_BusIO_Register::print(Stream *s) {
uint32_t val = read();
s->print("0x"); s->print(val, HEX);
}
/*!
* @brief Pretty printer for this register
* @param s The Stream to print to, defaults to &Serial
*/
void Adafruit_BusIO_Register::println(Stream *s) {
print(s);
s->println();
}
/*!
* @brief Create a slice of the register that we can address without touching other bits
* @param reg The Adafruit_BusIO_Register which defines the bus/register
* @param bits The number of bits wide we are slicing
* @param shift The number of bits that our bit-slice is shifted from LSB
*/
Adafruit_BusIO_RegisterBits::Adafruit_BusIO_RegisterBits(Adafruit_BusIO_Register *reg, uint8_t bits, uint8_t shift) {
_register = reg;
_bits = bits;
_shift = shift;
}
/*!
* @brief Read 4 bytes of data from the register
* @return data The 4 bytes to read
*/
uint32_t Adafruit_BusIO_RegisterBits::read(void) {
uint32_t val = _register->read();
val >>= _shift;
return val & ((1 << (_bits+1)) - 1);
}
/*!
* @brief Write 4 bytes of data to the register
* @param data The 4 bytes to write
*/
void Adafruit_BusIO_RegisterBits::write(uint32_t data) {
uint32_t val = _register->read();
// mask off the data before writing
uint32_t mask = (1 << (_bits+1)) - 1;
data &= mask;
mask <<= _shift;
val &= ~mask; // remove the current data at that spot
val |= data << _shift; // and add in the new data
_register->write(val, _register->width());
}
/*!
* @brief The width of the register data, helpful for doing calculations
* @returns The data width used when initializing the register
*/
uint8_t Adafruit_BusIO_Register::width(void) { return _width; }

View File

@ -0,0 +1,69 @@
#include <Adafruit_I2CDevice.h>
#include <Adafruit_SPIDevice.h>
#include <Arduino.h>
#ifndef Adafruit_BusIO_Register_h
#define Adafruit_BusIO_Register_h
typedef enum _Adafruit_BusIO_SPIRegType {
ADDRBIT8_HIGH_TOREAD = 0,
} Adafruit_BusIO_SPIRegType;
/*!
* @brief The class which defines a device register (a location to read/write data from)
*/
class Adafruit_BusIO_Register {
public:
Adafruit_BusIO_Register(Adafruit_I2CDevice *i2cdevice, uint16_t reg_addr,
uint8_t width=1, uint8_t bitorder=LSBFIRST,
uint8_t address_width=1);
Adafruit_BusIO_Register(Adafruit_SPIDevice *spidevice, uint16_t reg_addr,
Adafruit_BusIO_SPIRegType type,
uint8_t width=1, uint8_t bitorder=LSBFIRST,
uint8_t address_width=1);
Adafruit_BusIO_Register(Adafruit_I2CDevice *i2cdevice,
Adafruit_SPIDevice *spidevice,
Adafruit_BusIO_SPIRegType type,
uint16_t reg_addr,
uint8_t width=1, uint8_t bitorder=LSBFIRST,
uint8_t address_width=1);
bool read(uint8_t *buffer, uint8_t len);
bool read(uint8_t *value);
bool read(uint16_t *value);
uint32_t read(void);
bool write(uint8_t *buffer, uint8_t len);
bool write(uint32_t value, uint8_t numbytes=0);
uint8_t width(void);
void print(Stream *s=&Serial);
void println(Stream *s=&Serial);
private:
Adafruit_I2CDevice *_i2cdevice;
Adafruit_SPIDevice *_spidevice;
Adafruit_BusIO_SPIRegType _spiregtype;
uint16_t _address;
uint8_t _width, _addrwidth, _bitorder;
uint8_t _buffer[4]; // we wont support anything larger than uint32 for non-buffered read
};
/*!
* @brief The class which defines a slice of bits from within a device register (a location to read/write data from)
*/
class Adafruit_BusIO_RegisterBits {
public:
Adafruit_BusIO_RegisterBits(Adafruit_BusIO_Register *reg, uint8_t bits, uint8_t shift);
void write(uint32_t value);
uint32_t read(void);
private:
Adafruit_BusIO_Register *_register;
uint8_t _bits, _shift;
};
#endif //BusIO_Register_h

View File

@ -0,0 +1,184 @@
#include <Adafruit_I2CDevice.h>
#include <Arduino.h>
//#define DEBUG_SERIAL Serial
/*!
* @brief Create an I2C device at a given address
* @param addr The 7-bit I2C address for the device
* @param theWire The I2C bus to use, defaults to &Wire
*/
Adafruit_I2CDevice::Adafruit_I2CDevice(uint8_t addr, TwoWire *theWire) {
_addr = addr;
_wire = theWire;
_begun = false;
}
/*!
* @brief Initializes and does basic address detection
* @return True if I2C initialized and a device with the addr found
*/
bool Adafruit_I2CDevice::begin(void) {
_wire->begin();
_begun = true;
return detected();
}
/*!
* @brief Scans I2C for the address - note will give a false-positive
* if there's no pullups on I2C
* @return True if I2C initialized and a device with the addr found
*/
bool Adafruit_I2CDevice::detected(void) {
// Init I2C if not done yet
if (!_begun && !begin()) {
return false;
}
// A basic scanner, see if it ACK's
_wire->beginTransmission(_addr);
if (_wire->endTransmission () == 0) {
return true;
}
return false;
}
/*!
* @brief Write a buffer or two to the I2C device. Cannot be more than 32 bytes.
* @param buffer Pointer to buffer of data to write
* @param len Number of bytes from buffer to write
* @param prefix_buffer Pointer to optional array of data to write before buffer. Cannot be more than 32 bytes.
* @param prefix_len Number of bytes from prefix buffer to write
* @param stop Whether to send an I2C STOP signal on write
* @return True if write was successful, otherwise false.
*/
bool Adafruit_I2CDevice::write(uint8_t *buffer, size_t len, bool stop, uint8_t *prefix_buffer, size_t prefix_len) {
if ((len+prefix_len) > 32) {
// currently not guaranteed to work if more than 32 bytes!
// we will need to find out if some platforms have larger
// I2C buffer sizes :/
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.println(F("\tI2CDevice could not write such a large buffer"));
#endif
return false;
}
_wire->beginTransmission(_addr);
// Write the prefix data (usually an address)
if ((prefix_len != 0) && (prefix_buffer != NULL)) {
if (_wire->write(prefix_buffer, prefix_len) != prefix_len) {
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.println(F("\tI2CDevice failed to write"));
#endif
return false;
}
}
// Write the data itself
if (_wire->write(buffer, len) != len) {
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.println(F("\tI2CDevice failed to write"));
#endif
return false;
}
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.print(F("\tI2CDevice Wrote: "));
if ((prefix_len != 0) && (prefix_buffer != NULL)) {
for (uint16_t i=0; i<prefix_len; i++) {
DEBUG_SERIAL.print(F("0x"));
DEBUG_SERIAL.print(prefix_buffer[i], HEX);
DEBUG_SERIAL.print(F(", "));
}
}
for (uint16_t i=0; i<len; i++) {
DEBUG_SERIAL.print(F("0x"));
DEBUG_SERIAL.print(buffer[i], HEX);
DEBUG_SERIAL.print(F(", "));
if (len % 32 == 31) {
DEBUG_SERIAL.println();
}
}
DEBUG_SERIAL.println();
#endif
return (_wire -> endTransmission(stop) == 0);
}
/*!
* @brief Read from I2C into a buffer from the I2C device. Cannot be more than 32 bytes.
* @param buffer Pointer to buffer of data to read into
* @param len Number of bytes from buffer to read.
* @param stop Whether to send an I2C STOP signal on read
* @return True if read was successful, otherwise false.
*/
bool Adafruit_I2CDevice::read(uint8_t *buffer, size_t len, bool stop) {
if (len > 32) {
// currently not guaranteed to work if more than 32 bytes!
// we will need to find out if some platforms have larger
// I2C buffer sizes :/
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.println(F("\tI2CDevice could not read such a large buffer"));
#endif
return false;
}
if (_wire->requestFrom((uint8_t)_addr, (uint8_t)len, (uint8_t)stop) != len) {
// Not enough data available to fulfill our obligation!
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.println(F("\tI2CDevice did not receive enough data"));
#endif
return false;
}
for (uint16_t i=0; i<len; i++) {
buffer[i] = _wire->read();
}
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.print(F("\tI2CDevice Read: "));
for (uint16_t i=0; i<len; i++) {
DEBUG_SERIAL.print(F("0x"));
DEBUG_SERIAL.print(buffer[i], HEX);
DEBUG_SERIAL.print(F(", "));
if (len % 32 == 31) {
DEBUG_SERIAL.println();
}
}
DEBUG_SERIAL.println();
#endif
return true;
}
/*!
* @brief Write some data, then read some data from I2C into another buffer. Cannot be more than 32 bytes. The buffers can point to same/overlapping locations.
* @param write_buffer Pointer to buffer of data to write from
* @param write_len Number of bytes from buffer to write.
* @param read_buffer Pointer to buffer of data to read into.
* @param read_len Number of bytes from buffer to read.
* @param stop Whether to send an I2C STOP signal between the write and read
* @return True if write & read was successful, otherwise false.
*/
bool Adafruit_I2CDevice::write_then_read(uint8_t *write_buffer, size_t write_len, uint8_t *read_buffer, size_t read_len, bool stop) {
if (! write(write_buffer, write_len, stop)) {
return false;
}
return read(read_buffer, read_len);
}
/*!
* @brief Returns the 7-bit address of this device
* @return The 7-bit address of this device
*/
uint8_t Adafruit_I2CDevice::address(void) {
return _addr;
}

View File

@ -0,0 +1,26 @@
#include <Wire.h>
#ifndef Adafruit_I2CDevice_h
#define Adafruit_I2CDevice_h
///< The class which defines how we will talk to this device over I2C
class Adafruit_I2CDevice {
public:
Adafruit_I2CDevice(uint8_t addr, TwoWire *theWire=&Wire);
uint8_t address(void);
bool begin(void);
bool detected(void);
bool read(uint8_t *buffer, size_t len, bool stop=true);
bool write(uint8_t *buffer, size_t len, bool stop=true, uint8_t *prefix_buffer=NULL, size_t prefix_len=0);
bool write_then_read(uint8_t *write_buffer, size_t write_len, uint8_t *read_buffer, size_t read_len, bool stop=false);
private:
uint8_t _addr;
TwoWire *_wire;
bool _begun;
};
#endif // Adafruit_I2CDevice_h

View File

@ -0,0 +1,8 @@
#include "Adafruit_BusIO_Register.h"
#ifndef _ADAFRUIT_I2C_REGISTER_H_
#define _ADAFRUIT_I2C_REGISTER_H_
typedef Adafruit_BusIO_Register Adafruit_I2CRegister;
typedef Adafruit_BusIO_RegisterBits Adafruit_I2CRegisterBits;
#endif

View File

@ -0,0 +1,301 @@
#include <Adafruit_SPIDevice.h>
#include <Arduino.h>
//#define DEBUG_SERIAL Serial
/*!
* @brief Create an SPI device with the given CS pin and settins
* @param cspin The arduino pin number to use for chip select
* @param freq The SPI clock frequency to use, defaults to 1MHz
* @param dataOrder The SPI data order to use for bits within each byte, defaults to SPI_BITORDER_MSBFIRST
* @param dataMode The SPI mode to use, defaults to SPI_MODE0
* @param theSPI The SPI bus to use, defaults to &theSPI
*/
Adafruit_SPIDevice::Adafruit_SPIDevice(int8_t cspin, uint32_t freq, BitOrder dataOrder, uint8_t dataMode, SPIClass *theSPI) {
_cs = cspin;
_sck = _mosi = _miso = -1;
_spi = theSPI;
_begun = false;
_spiSetting = new SPISettings(freq, dataOrder, dataMode);
_freq = freq;
_dataOrder = dataOrder;
_dataMode = dataMode;
}
/*!
* @brief Create an SPI device with the given CS pin and settins
* @param cspin The arduino pin number to use for chip select
* @param sckpin The arduino pin number to use for SCK
* @param misopin The arduino pin number to use for MISO, set to -1 if not used
* @param mosipin The arduino pin number to use for MOSI, set to -1 if not used
* @param freq The SPI clock frequency to use, defaults to 1MHz
* @param dataOrder The SPI data order to use for bits within each byte, defaults to SPI_BITORDER_MSBFIRST
* @param dataMode The SPI mode to use, defaults to SPI_MODE0
*/
Adafruit_SPIDevice::Adafruit_SPIDevice(int8_t cspin, int8_t sckpin, int8_t misopin, int8_t mosipin,
uint32_t freq, BitOrder dataOrder, uint8_t dataMode) {
_cs = cspin;
_sck = sckpin;
_miso = misopin;
_mosi = mosipin;
_freq = freq;
_dataOrder = dataOrder;
_dataMode = dataMode;
_begun = false;
_spiSetting = new SPISettings(freq, dataOrder, dataMode);
_spi = NULL;
}
/*!
* @brief Initializes SPI bus and sets CS pin high
* @return Always returns true because there's no way to test success of SPI init
*/
bool Adafruit_SPIDevice::begin(void) {
pinMode(_cs, OUTPUT);
digitalWrite(_cs, HIGH);
if (_spi) { // hardware SPI
_spi->begin();
} else {
pinMode(_sck, OUTPUT);
if (_dataMode==SPI_MODE0) {
digitalWrite(_sck, HIGH);
} else {
digitalWrite(_sck, LOW);
}
if (_mosi != -1) {
pinMode(_mosi, OUTPUT);
digitalWrite(_mosi, HIGH);
}
if (_miso != -1) {
pinMode(_miso, INPUT);
}
}
_begun = true;
return true;
}
/*!
* @brief Transfer (send/receive) one byte over hard/soft SPI
* @param buffer The buffer to send and receive at the same time
* @param len The number of bytes to transfer
*/
void Adafruit_SPIDevice::transfer(uint8_t *buffer, size_t len) {
if (_spi) {
// hardware SPI is easy
_spi->transfer(buffer, len);
return;
}
// for softSPI we'll do it by hand
for (size_t i=0; i<len; i++) {
// software SPI
uint8_t reply = 0;
uint8_t send = buffer[i];
if (_dataOrder == SPI_BITORDER_LSBFIRST) {
// LSB is rare, if it happens we'll just flip the bits around for them
uint8_t temp = 0;
for (uint8_t b=0; b<8; b++) {
temp |= ((send >> b) & 0x1) << (7-b);
}
send = temp;
}
for (int b=7; b>=0; b--) {
reply <<= 1;
if (_dataMode == SPI_MODE0) {
digitalWrite(_sck, LOW);
digitalWrite(_mosi, send & (1<<b));
digitalWrite(_sck, HIGH);
if ((_miso != -1) && digitalRead(_miso)) {
reply |= 1;
}
}
if (_dataMode == SPI_MODE1) {
digitalWrite(_sck, HIGH);
digitalWrite(_mosi, send & (1<<b));
digitalWrite(_sck, LOW);
if ((_miso != -1) && digitalRead(_miso)) {
reply |= 1;
}
}
}
if (_dataOrder == SPI_BITORDER_LSBFIRST) {
// LSB is rare, if it happens we'll just flip the bits around for them
uint8_t temp = 0;
for (uint8_t b=0; b<8; b++) {
temp |= ((reply >> b) & 0x1) << (7-b);
}
reply = temp;
}
buffer[i] = reply;
}
return;
}
/*!
* @brief Transfer (send/receive) one byte over hard/soft SPI
* @param send The byte to send
* @return The byte received while transmitting
*/
uint8_t Adafruit_SPIDevice::transfer(uint8_t send) {
uint8_t data = send;
transfer(&data, 1);
return data;
}
/*!
* @brief Write a buffer or two to the SPI device.
* @param buffer Pointer to buffer of data to write
* @param len Number of bytes from buffer to write
* @param prefix_buffer Pointer to optional array of data to write before buffer.
* @param prefix_len Number of bytes from prefix buffer to write
* @return Always returns true because there's no way to test success of SPI writes
*/
bool Adafruit_SPIDevice::write(uint8_t *buffer, size_t len, uint8_t *prefix_buffer, size_t prefix_len) {
if (_spi) {
_spi->beginTransaction(*_spiSetting);
}
digitalWrite(_cs, LOW);
// do the writing
for (size_t i=0; i<prefix_len; i++) {
transfer(prefix_buffer[i]);
}
for (size_t i=0; i<len; i++) {
transfer(buffer[i]);
}
digitalWrite(_cs, HIGH);
if (_spi) {
_spi->endTransaction();
}
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.print(F("\tSPIDevice Wrote: "));
if ((prefix_len != 0) && (prefix_buffer != NULL)) {
for (uint16_t i=0; i<prefix_len; i++) {
DEBUG_SERIAL.print(F("0x"));
DEBUG_SERIAL.print(prefix_buffer[i], HEX);
DEBUG_SERIAL.print(F(", "));
}
}
for (uint16_t i=0; i<len; i++) {
DEBUG_SERIAL.print(F("0x"));
DEBUG_SERIAL.print(buffer[i], HEX);
DEBUG_SERIAL.print(F(", "));
if (len % 32 == 31) {
DEBUG_SERIAL.println();
}
}
DEBUG_SERIAL.println();
#endif
return true;
}
/*!
* @brief Read from SPI into a buffer from the SPI device.
* @param buffer Pointer to buffer of data to read into
* @param len Number of bytes from buffer to read.
* @param sendvalue The 8-bits of data to write when doing the data read, defaults to 0xFF
* @return Always returns true because there's no way to test success of SPI writes
*/
bool Adafruit_SPIDevice::read(uint8_t *buffer, size_t len, uint8_t sendvalue) {
memset(buffer, sendvalue, len); // clear out existing buffer
if (_spi) {
_spi->beginTransaction(*_spiSetting);
}
digitalWrite(_cs, LOW);
transfer(buffer, len);
digitalWrite(_cs, HIGH);
if (_spi) {
_spi->endTransaction();
}
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.print(F("\tSPIDevice Read: "));
for (uint16_t i=0; i<len; i++) {
DEBUG_SERIAL.print(F("0x"));
DEBUG_SERIAL.print(buffer[i], HEX);
DEBUG_SERIAL.print(F(", "));
if (len % 32 == 31) {
DEBUG_SERIAL.println();
}
}
DEBUG_SERIAL.println();
#endif
return true;
}
/*!
* @brief Write some data, then read some data from SPI into another buffer. The buffers can point to same/overlapping locations. This does not transmit-receive at the same time!
* @param write_buffer Pointer to buffer of data to write from
* @param write_len Number of bytes from buffer to write.
* @param read_buffer Pointer to buffer of data to read into.
* @param read_len Number of bytes from buffer to read.
* @param sendvalue The 8-bits of data to write when doing the data read, defaults to 0xFF
* @return Always returns true because there's no way to test success of SPI writes
*/
bool Adafruit_SPIDevice::write_then_read(uint8_t *write_buffer, size_t write_len, uint8_t *read_buffer, size_t read_len, uint8_t sendvalue) {
if (_spi) {
_spi->beginTransaction(*_spiSetting);
}
digitalWrite(_cs, LOW);
// do the writing
for (size_t i=0; i<write_len; i++) {
transfer(write_buffer[i]);
}
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.print(F("\tSPIDevice Wrote: "));
for (uint16_t i=0; i<write_len; i++) {
DEBUG_SERIAL.print(F("0x"));
DEBUG_SERIAL.print(write_buffer[i], HEX);
DEBUG_SERIAL.print(F(", "));
if (write_len % 32 == 31) {
DEBUG_SERIAL.println();
}
}
DEBUG_SERIAL.println();
#endif
// do the reading
for (size_t i=0; i<read_len; i++) {
read_buffer[i] = transfer(sendvalue);
}
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.print(F("\tSPIDevice Read: "));
for (uint16_t i=0; i<read_len; i++) {
DEBUG_SERIAL.print(F("0x"));
DEBUG_SERIAL.print(read_buffer[i], HEX);
DEBUG_SERIAL.print(F(", "));
if (read_len % 32 == 31) {
DEBUG_SERIAL.println();
}
}
DEBUG_SERIAL.println();
#endif
digitalWrite(_cs, HIGH);
if (_spi) {
_spi->endTransaction();
}
return true;
}

View File

@ -0,0 +1,62 @@
#include <SPI.h>
#ifndef Adafruit_SPIDevice_h
#define Adafruit_SPIDevice_h
// some modern SPI definitions don't have BitOrder enum
#if defined(__AVR__) || defined(ESP8266) || defined(TEENSYDUINO)
typedef enum _BitOrder {
SPI_BITORDER_MSBFIRST = MSBFIRST,
SPI_BITORDER_LSBFIRST = LSBFIRST,
} BitOrder;
#endif
// some modern SPI definitions don't have BitOrder enum and have different SPI mode defines
#if defined(ESP32)
typedef enum _BitOrder {
SPI_BITORDER_MSBFIRST = SPI_MSBFIRST,
SPI_BITORDER_LSBFIRST = SPI_LSBFIRST,
} BitOrder;
#endif
// Some platforms have a BitOrder enum but its named MSBFIRST/LSBFIRST
#if defined(ARDUINO_ARCH_SAMD) || defined(__SAM3X8E__) || defined(NRF52_SERIES)
#define SPI_BITORDER_MSBFIRST MSBFIRST
#define SPI_BITORDER_LSBFIRST LSBFIRST
#endif
///< The class which defines how we will talk to this device over SPI
class Adafruit_SPIDevice {
public:
Adafruit_SPIDevice(int8_t cspin,
uint32_t freq=1000000,
BitOrder dataOrder=SPI_BITORDER_MSBFIRST,
uint8_t dataMode=SPI_MODE0,
SPIClass *theSPI=&SPI);
Adafruit_SPIDevice(int8_t cspin, int8_t sck, int8_t miso, int8_t mosi,
uint32_t freq=1000000,
BitOrder dataOrder=SPI_BITORDER_MSBFIRST,
uint8_t dataMode=SPI_MODE0);
bool begin(void);
bool read(uint8_t *buffer, size_t len, uint8_t sendvalue=0xFF);
bool write(uint8_t *buffer, size_t len, uint8_t *prefix_buffer=NULL, size_t prefix_len=0);
bool write_then_read(uint8_t *write_buffer, size_t write_len, uint8_t *read_buffer, size_t read_len, uint8_t sendvalue=0xFF);
uint8_t transfer(uint8_t send);
void transfer(uint8_t *buffer, size_t len);
private:
SPIClass *_spi;
SPISettings *_spiSetting;
uint32_t _freq;
BitOrder _dataOrder;
uint8_t _dataMode;
int8_t _cs, _sck, _mosi, _miso;
bool _begun;
};
#endif // Adafruit_SPIDevice_h

View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2017 Adafruit Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,7 @@
# Adafruit Bus IO Library [![Build Status](https://travis-ci.com/adafruit/Adafruit_BusIO.svg?branch=master)](https://travis-ci.com/adafruit/Adafruit_BusIO)
This is a helper libary to abstract away I2C & SPI transactions and registers
Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit!
MIT license, all text above must be included in any redistribution

View File

@ -0,0 +1,21 @@
#include <Adafruit_I2CDevice.h>
Adafruit_I2CDevice i2c_dev = Adafruit_I2CDevice(0x10);
void setup() {
while (!Serial) { delay(10); }
Serial.begin(115200);
Serial.println("I2C address detection test");
if (!i2c_dev.begin()) {
Serial.print("Did not find device at 0x");
Serial.println(i2c_dev.address(), HEX);
while (1);
}
Serial.print("Device found on address 0x");
Serial.println(i2c_dev.address(), HEX);
}
void loop() {
}

View File

@ -0,0 +1,41 @@
#include <Adafruit_I2CDevice.h>
#define I2C_ADDRESS 0x60
Adafruit_I2CDevice i2c_dev = Adafruit_I2CDevice(I2C_ADDRESS);
void setup() {
while (!Serial) { delay(10); }
Serial.begin(115200);
Serial.println("I2C device read and write test");
if (!i2c_dev.begin()) {
Serial.print("Did not find device at 0x");
Serial.println(i2c_dev.address(), HEX);
while (1);
}
Serial.print("Device found on address 0x");
Serial.println(i2c_dev.address(), HEX);
uint8_t buffer[32];
// Try to read 32 bytes
i2c_dev.read(buffer, 32);
Serial.print("Read: ");
for (uint8_t i=0; i<32; i++) {
Serial.print("0x"); Serial.print(buffer[i], HEX); Serial.print(", ");
}
Serial.println();
// read a register by writing first, then reading
buffer[0] = 0x0C; // we'll reuse the same buffer
i2c_dev.write_then_read(buffer, 1, buffer, 2, false);
Serial.print("Write then Read: ");
for (uint8_t i=0; i<2; i++) {
Serial.print("0x"); Serial.print(buffer[i], HEX); Serial.print(", ");
}
Serial.println();
}
void loop() {
}

View File

@ -0,0 +1,38 @@
#include <Adafruit_I2CDevice.h>
#include <Adafruit_BusIO_Register.h>
#define I2C_ADDRESS 0x60
Adafruit_I2CDevice i2c_dev = Adafruit_I2CDevice(I2C_ADDRESS);
void setup() {
while (!Serial) { delay(10); }
Serial.begin(115200);
Serial.println("I2C device register test");
if (!i2c_dev.begin()) {
Serial.print("Did not find device at 0x");
Serial.println(i2c_dev.address(), HEX);
while (1);
}
Serial.print("Device found on address 0x");
Serial.println(i2c_dev.address(), HEX);
Adafruit_BusIO_Register id_reg = Adafruit_BusIO_Register(&i2c_dev, 0x0C, 2, LSBFIRST);
uint16_t id;
id_reg.read(&id);
Serial.print("ID register = 0x"); Serial.println(id, HEX);
Adafruit_BusIO_Register thresh_reg = Adafruit_BusIO_Register(&i2c_dev, 0x01, 2, LSBFIRST);
uint16_t thresh;
thresh_reg.read(&thresh);
Serial.print("Initial threshold register = 0x"); Serial.println(thresh, HEX);
thresh_reg.write(~thresh);
Serial.print("Post threshold register = 0x"); Serial.println(thresh_reg.read(), HEX);
}
void loop() {
}

View File

@ -0,0 +1,38 @@
#include <Adafruit_BusIO_Register.h>
// Define which interface to use by setting the unused interface to NULL!
#define SPIDEVICE_CS 10
Adafruit_SPIDevice *spi_dev = NULL; // new Adafruit_SPIDevice(SPIDEVICE_CS);
#define I2C_ADDRESS 0x5D
Adafruit_I2CDevice *i2c_dev = new Adafruit_I2CDevice(I2C_ADDRESS);
void setup() {
while (!Serial) { delay(10); }
Serial.begin(115200);
Serial.println("I2C or SPI device register test");
if (spi_dev && !spi_dev->begin()) {
Serial.println("Could not initialize SPI device");
}
if (i2c_dev) {
if (i2c_dev->begin()) {
Serial.print("Device found on I2C address 0x");
Serial.println(i2c_dev->address(), HEX);
} else {
Serial.print("Did not find I2C device at 0x");
Serial.println(i2c_dev->address(), HEX);
}
}
Adafruit_BusIO_Register id_reg = Adafruit_BusIO_Register(i2c_dev, spi_dev, ADDRBIT8_HIGH_TOREAD, 0x0F);
uint8_t id;
id_reg.read(&id);
Serial.print("ID register = 0x"); Serial.println(id, HEX);
}
void loop() {
}

View File

@ -0,0 +1,29 @@
#include <Adafruit_SPIDevice.h>
#define SPIDEVICE_CS 10
Adafruit_SPIDevice spi_dev = Adafruit_SPIDevice(SPIDEVICE_CS, 100000, SPI_BITORDER_MSBFIRST, SPI_MODE1);
//Adafruit_SPIDevice spi_dev = Adafruit_SPIDevice(SPIDEVICE_CS, 13, 12, 11, 100000, SPI_BITORDER_MSBFIRST, SPI_MODE1);
void setup() {
while (!Serial) { delay(10); }
Serial.begin(115200);
Serial.println("SPI device mode test");
if (!spi_dev.begin()) {
Serial.println("Could not initialize SPI device");
while (1);
}
}
void loop() {
Serial.println("\n\nTransfer test");
for (uint16_t x=0; x<=0xFF; x++) {
uint8_t i = x;
Serial.print("0x"); Serial.print(i, HEX);
spi_dev.read(&i, 1, i);
Serial.print("/"); Serial.print(i, HEX);
Serial.print(", ");
delay(25);
}
}

View File

@ -0,0 +1,39 @@
#include <Adafruit_SPIDevice.h>
#define SPIDEVICE_CS 10
Adafruit_SPIDevice spi_dev = Adafruit_SPIDevice(SPIDEVICE_CS);
void setup() {
while (!Serial) { delay(10); }
Serial.begin(115200);
Serial.println("SPI device read and write test");
if (!spi_dev.begin()) {
Serial.println("Could not initialize SPI device");
while (1);
}
uint8_t buffer[32];
// Try to read 32 bytes
spi_dev.read(buffer, 32);
Serial.print("Read: ");
for (uint8_t i=0; i<32; i++) {
Serial.print("0x"); Serial.print(buffer[i], HEX); Serial.print(", ");
}
Serial.println();
// read a register by writing first, then reading
buffer[0] = 0x8F; // we'll reuse the same buffer
spi_dev.write_then_read(buffer, 1, buffer, 2, false);
Serial.print("Write then Read: ");
for (uint8_t i=0; i<2; i++) {
Serial.print("0x"); Serial.print(buffer[i], HEX); Serial.print(", ");
}
Serial.println();
}
void loop() {
}

View File

@ -0,0 +1,34 @@
#include <Adafruit_BusIO_Register.h>
#include <Adafruit_SPIDevice.h>
#define SPIDEVICE_CS 10
Adafruit_SPIDevice spi_dev = Adafruit_SPIDevice(SPIDEVICE_CS);
void setup() {
while (!Serial) { delay(10); }
Serial.begin(115200);
Serial.println("SPI device register test");
if (!spi_dev.begin()) {
Serial.println("Could not initialize SPI device");
while (1);
}
Adafruit_BusIO_Register id_reg = Adafruit_BusIO_Register(&spi_dev, 0x0F, ADDRBIT8_HIGH_TOREAD);
uint8_t id;
id_reg.read(&id);
Serial.print("ID register = 0x"); Serial.println(id, HEX);
Adafruit_BusIO_Register thresh_reg = Adafruit_BusIO_Register(&spi_dev, 0x0C, ADDRBIT8_HIGH_TOREAD, 2, LSBFIRST);
uint16_t thresh;
thresh_reg.read(&thresh);
Serial.print("Initial threshold register = 0x"); Serial.println(thresh, HEX);
thresh_reg.write(~thresh);
Serial.print("Post threshold register = 0x"); Serial.println(thresh_reg.read(), HEX);
}
void loop() {
}

View File

@ -0,0 +1,9 @@
name=Adafruit BusIO
version=1.0.4
author=Adafruit
maintainer=Adafruit <info@adafruit.com>
sentence=This is a library for abstracting away UART, I2C and SPI interfacing
paragraph=This is a library for abstracting away UART, I2C and SPI interfacing
category=Signal Input/Output
url=https://github.com/adafruit/Adafruit_BusIO
architectures=*

View File

@ -0,0 +1,46 @@
Thank you for opening an issue on an Adafruit Arduino library repository. To
improve the speed of resolution please review the following guidelines and
common troubleshooting steps below before creating the issue:
- **Do not use GitHub issues for troubleshooting projects and issues.** Instead use
the forums at http://forums.adafruit.com to ask questions and troubleshoot why
something isn't working as expected. In many cases the problem is a common issue
that you will more quickly receive help from the forum community. GitHub issues
are meant for known defects in the code. If you don't know if there is a defect
in the code then start with troubleshooting on the forum first.
- **If following a tutorial or guide be sure you didn't miss a step.** Carefully
check all of the steps and commands to run have been followed. Consult the
forum if you're unsure or have questions about steps in a guide/tutorial.
- **For Arduino projects check these very common issues to ensure they don't apply**:
- For uploading sketches or communicating with the board make sure you're using
a **USB data cable** and **not** a **USB charge-only cable**. It is sometimes
very hard to tell the difference between a data and charge cable! Try using the
cable with other devices or swapping to another cable to confirm it is not
the problem.
- **Be sure you are supplying adequate power to the board.** Check the specs of
your board and plug in an external power supply. In many cases just
plugging a board into your computer is not enough to power it and other
peripherals.
- **Double check all soldering joints and connections.** Flakey connections
cause many mysterious problems. See the [guide to excellent soldering](https://learn.adafruit.com/adafruit-guide-excellent-soldering/tools) for examples of good solder joints.
- **Ensure you are using an official Arduino or Adafruit board.** We can't
guarantee a clone board will have the same functionality and work as expected
with this code and don't support them.
If you're sure this issue is a defect in the code and checked the steps above
please fill in the following fields to provide enough troubleshooting information.
You may delete the guideline and text above to just leave the following details:
- Arduino board: **INSERT ARDUINO BOARD NAME/TYPE HERE**
- Arduino IDE version (found in Arduino -> About Arduino menu): **INSERT ARDUINO
VERSION HERE**
- List the steps to reproduce the problem below (if possible attach a sketch or
copy the sketch code in too): **LIST REPRO STEPS BELOW**

View File

@ -0,0 +1,26 @@
Thank you for creating a pull request to contribute to Adafruit's GitHub code!
Before you open the request please review the following guidelines and tips to
help it be more easily integrated:
- **Describe the scope of your change--i.e. what the change does and what parts
of the code were modified.** This will help us understand any risks of integrating
the code.
- **Describe any known limitations with your change.** For example if the change
doesn't apply to a supported platform of the library please mention it.
- **Please run any tests or examples that can exercise your modified code.** We
strive to not break users of the code and running tests/examples helps with this
process.
Thank you again for contributing! We will try to test and integrate the change
as soon as we can, but be aware we have many GitHub repositories to manage and
can't immediately respond to every request. There is no need to bump or check in
on a pull request (it will clutter the discussion of the request).
Also don't be worried if the request is closed or not integrated--sometimes the
priorities of Adafruit's GitHub code (education, ease of use) might not match the
priorities of the pull request. Don't fret, the open source community thrives on
forks and GitHub makes it easy to keep your changes in a forked repo.
After reviewing the guidelines above you can delete this text from the pull request.

View File

@ -0,0 +1,178 @@
/***************************************************
This is a library for the Adafruit Thermocouple Sensor w/MAX31855K
Designed specifically to work with the Adafruit Thermocouple Sensor
----> https://www.adafruit.com/products/269
These displays use SPI to communicate, 3 pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
****************************************************/
#include "Adafruit_MAX31855.h"
#ifdef __AVR
#include <avr/pgmspace.h>
#elif defined(ESP8266)
#include <pgmspace.h>
#endif
#include <stdlib.h>
#include <SPI.h>
Adafruit_MAX31855::Adafruit_MAX31855(int8_t _sclk, int8_t _cs, int8_t _miso) {
sclk = _sclk;
cs = _cs;
miso = _miso;
initialized = false;
}
Adafruit_MAX31855::Adafruit_MAX31855(int8_t _cs) {
cs = _cs;
sclk = miso = -1;
initialized = false;
}
void Adafruit_MAX31855::begin(void) {
//define pin modes
pinMode(cs, OUTPUT);
digitalWrite(cs, HIGH);
if (sclk == -1) {
// hardware SPI
//start and configure hardware SPI
SPI.begin();
} else {
pinMode(sclk, OUTPUT);
pinMode(miso, INPUT);
}
initialized = true;
}
double Adafruit_MAX31855::readInternal(void) {
uint32_t v;
v = spiread32();
// ignore bottom 4 bits - they're just thermocouple data
v >>= 4;
// pull the bottom 11 bits off
float internal = v & 0x7FF;
// check sign bit!
if (v & 0x800) {
// Convert to negative value by extending sign and casting to signed type.
int16_t tmp = 0xF800 | (v & 0x7FF);
internal = tmp;
}
internal *= 0.0625; // LSB = 0.0625 degrees
//Serial.print("\tInternal Temp: "); Serial.println(internal);
return internal;
}
double Adafruit_MAX31855::readCelsius(void) {
int32_t v;
v = spiread32();
//Serial.print("0x"); Serial.println(v, HEX);
/*
float internal = (v >> 4) & 0x7FF;
internal *= 0.0625;
if ((v >> 4) & 0x800)
internal *= -1;
Serial.print("\tInternal Temp: "); Serial.println(internal);
*/
if (v & 0x7) {
// uh oh, a serious problem!
return NAN;
}
if (v & 0x80000000) {
// Negative value, drop the lower 18 bits and explicitly extend sign bits.
v = 0xFFFFC000 | ((v >> 18) & 0x00003FFFF);
}
else {
// Positive value, just drop the lower 18 bits.
v >>= 18;
}
//Serial.println(v, HEX);
double centigrade = v;
// LSB = 0.25 degrees C
centigrade *= 0.25;
return centigrade;
}
uint8_t Adafruit_MAX31855::readError() {
return spiread32() & 0x7;
}
double Adafruit_MAX31855::readFarenheit(void) {
float f = readCelsius();
f *= 9.0;
f /= 5.0;
f += 32;
return f;
}
uint32_t Adafruit_MAX31855::spiread32(void) {
int i;
uint32_t d = 0;
// backcompatibility!
if (! initialized) {
begin();
}
digitalWrite(cs, LOW);
delay(1);
if(sclk == -1) {
// hardware SPI
SPI.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE0));
d = SPI.transfer(0);
d <<= 8;
d |= SPI.transfer(0);
d <<= 8;
d |= SPI.transfer(0);
d <<= 8;
d |= SPI.transfer(0);
SPI.endTransaction();
} else {
// software SPI
digitalWrite(sclk, LOW);
delay(1);
for (i=31; i>=0; i--) {
digitalWrite(sclk, LOW);
delay(1);
d <<= 1;
if (digitalRead(miso)) {
d |= 1;
}
digitalWrite(sclk, HIGH);
delay(1);
}
}
digitalWrite(cs, HIGH);
//Serial.println(d, HEX);
return d;
}

View File

@ -0,0 +1,44 @@
/***************************************************
This is a library for the Adafruit Thermocouple Sensor w/MAX31855K
Designed specifically to work with the Adafruit Thermocouple Sensor
----> https://www.adafruit.com/products/269
These displays use SPI to communicate, 3 pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
****************************************************/
#ifndef ADAFRUIT_MAX31855_H
#define ADAFRUIT_MAX31855_H
#if (ARDUINO >= 100)
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
class Adafruit_MAX31855 {
public:
Adafruit_MAX31855(int8_t _sclk, int8_t _cs, int8_t _miso);
Adafruit_MAX31855(int8_t _cs);
void begin(void);
double readInternal(void);
double readCelsius(void);
double readFarenheit(void);
uint8_t readError();
private:
boolean initialized;
int8_t sclk, miso, cs;
uint32_t spiread32(void);
};
#endif

View File

@ -0,0 +1,32 @@
# Adafruit-MAX31855-library
<!-- START COMPATIBILITY TABLE -->
## Compatibility
MCU | Tested Works | Doesn't Work | Not Tested | Notes
------------------ | :----------: | :----------: | :---------: | -----
Atmega328 @ 16MHz | X | | |
Atmega328 @ 12MHz | X | | | For LCD example had to move pin 7.
Atmega32u4 @ 16MHz | X | | |
Atmega32u4 @ 8MHz | X | | |
ESP8266 | X | | |
Atmega2560 @ 16MHz | X | | |
ATSAM3X8E | X | | |
ATSAM21D | X | | |
ATtiny85 @ 16MHz | | X | |
ATtiny85 @ 8MHz | | X | |
Intel Curie @ 32MHz | | | X |
STM32F2 | | | X |
* ATmega328 @ 16MHz : Arduino UNO, Adafruit Pro Trinket 5V, Adafruit Metro 328, Adafruit Metro Mini
* ATmega328 @ 12MHz : Adafruit Pro Trinket 3V
* ATmega32u4 @ 16MHz : Arduino Leonardo, Arduino Micro, Arduino Yun, Teensy 2.0
* ATmega32u4 @ 8MHz : Adafruit Flora, Bluefruit Micro
* ESP8266 : Adafruit Huzzah
* ATmega2560 @ 16MHz : Arduino Mega
* ATSAM3X8E : Arduino Due
* ATSAM21D : Arduino Zero, M0 Pro
* ATtiny85 @ 16MHz : Adafruit Trinket 5V
* ATtiny85 @ 8MHz : Adafruit Gemma, Arduino Gemma, Adafruit Trinket 3V
<!-- END COMPATIBILITY TABLE -->

View File

@ -0,0 +1,19 @@
This is the Adafruit MAX31885 Arduino Library
Tested and works great with the Adafruit Thermocouple Breakout w/MAX31885K
------> http://www.adafruit.com/products/269
These modules use SPI to communicate, 3 pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, check license.txt for more information
All text above must be included in any redistribution
To download. click the DOWNLOADS button in the top right corner, rename the uncompressed folder Adafruit_MAX31885. Check that the Adafruit_MAX31885 folder contains Adafruit_MAX31885.cpp and Adafruit_MAX31885.h
Place the Adafruit_MAX31885 library folder your <arduinosketchfolder>/libraries/ folder. You may need to create the libraries subfolder if its your first library. Restart the IDE.

View File

@ -0,0 +1,77 @@
/***************************************************
This is an example for the Adafruit Thermocouple Sensor w/MAX31855K
Designed specifically to work with the Adafruit Thermocouple Sensor
----> https://www.adafruit.com/products/269
These displays use SPI to communicate, 3 pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
****************************************************/
#include <SPI.h>
#include <Wire.h>
#include "Adafruit_MAX31855.h"
#include <LiquidCrystal.h>
// Example creating a thermocouple instance with software SPI on any three
// digital IO pins.
#define MAXDO 3
#define MAXCS 4
#define MAXCLK 5
// Initialize the Thermocouple
Adafruit_MAX31855 thermocouple(MAXCLK, MAXCS, MAXDO);
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
#if defined(ARDUINO_ARCH_SAMD)
// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero!
#define Serial SerialUSB
#endif
void setup() {
#ifndef ESP8266
while (!Serial); // will pause Zero, Leonardo, etc until serial console opens
#endif
Serial.begin(9600);
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
lcd.clear();
lcd.print("MAX31855 test");
// wait for MAX chip to stabilize
delay(500);
}
void loop() {
// basic readout test, just print the current temp
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Int. Temp = ");
lcd.println(thermocouple.readInternal());
Serial.print("Int. Temp = ");
Serial.println(thermocouple.readInternal());
double c = thermocouple.readCelsius();
lcd.setCursor(0, 1);
if (isnan(c))
{
lcd.print("T/C Problem");
}
else
{
lcd.print("C = ");
lcd.print(c);
lcd.print(" ");
Serial.print("Thermocouple Temp = *");
Serial.println(c);
}
delay(1000);
}

View File

@ -0,0 +1,63 @@
/***************************************************
This is an example for the Adafruit Thermocouple Sensor w/MAX31855K
Designed specifically to work with the Adafruit Thermocouple Sensor
----> https://www.adafruit.com/products/269
These displays use SPI to communicate, 3 pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
****************************************************/
#include <SPI.h>
#include "Adafruit_MAX31855.h"
// Default connection is using software SPI, but comment and uncomment one of
// the two examples below to switch between software SPI and hardware SPI:
// Example creating a thermocouple instance with software SPI on any three
// digital IO pins.
#define MAXDO 3
#define MAXCS 4
#define MAXCLK 5
// initialize the Thermocouple
Adafruit_MAX31855 thermocouple(MAXCLK, MAXCS, MAXDO);
// Example creating a thermocouple instance with hardware SPI
// on a given CS pin.
//#define MAXCS 10
//Adafruit_MAX31855 thermocouple(MAXCS);
void setup() {
Serial.begin(9600);
while (!Serial) delay(1); // wait for Serial on Leonardo/Zero, etc
Serial.println("MAX31855 test");
// wait for MAX chip to stabilize
delay(500);
}
void loop() {
// basic readout test, just print the current temp
Serial.print("Internal Temp = ");
Serial.println(thermocouple.readInternal());
double c = thermocouple.readCelsius();
if (isnan(c)) {
Serial.println("Something wrong with thermocouple!");
} else {
Serial.print("C = ");
Serial.println(c);
}
//Serial.print("F = ");
//Serial.println(thermocouple.readFarenheit());
delay(1000);
}

View File

@ -0,0 +1,21 @@
#######################################
# Syntax Coloring Map for NewSoftSerial
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
max6675 KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
readCelsius KEYWORD2
readFarenheit KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################

View File

@ -0,0 +1,9 @@
name=Adafruit MAX31855 library
version=1.0.3
author=Adafruit
maintainer=Adafruit <info@adafruit.com>
sentence=Library for the Adafruit Thermocouple breakout with MAX31855K
paragraph=Library for the Adafruit Thermocouple breakout with MAX31855K
category=Sensors
url=https://github.com/adafruit/Adafruit-MAX31855-library
architectures=*

View File

@ -0,0 +1,26 @@
Software License Agreement (BSD License)
Copyright (c) 2012, Adafruit Industries
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,366 @@
/*!
* @file Adafruit_NeoPixel.h
*
* This is part of Adafruit's NeoPixel library for the Arduino platform,
* allowing a broad range of microcontroller boards (most AVR boards,
* many ARM devices, ESP8266 and ESP32, among others) to control Adafruit
* NeoPixels, FLORA RGB Smart Pixels and compatible devices -- WS2811,
* WS2812, WS2812B, SK6812, etc.
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit and open-source hardware by purchasing products
* from Adafruit!
*
* Written by Phil "Paint Your Dragon" Burgess for Adafruit Industries,
* with contributions by PJRC, Michael Miller and other members of the
* open source community.
*
* This file is part of the Adafruit_NeoPixel library.
*
* Adafruit_NeoPixel is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Adafruit_NeoPixel is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with NeoPixel. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#ifndef ADAFRUIT_NEOPIXEL_H
#define ADAFRUIT_NEOPIXEL_H
#ifdef ARDUINO
#if (ARDUINO >= 100)
#include <Arduino.h>
#else
#include <WProgram.h>
#include <pins_arduino.h>
#endif
#endif
#ifdef TARGET_LPC1768
#include <Arduino.h>
#endif
// The order of primary colors in the NeoPixel data stream can vary among
// device types, manufacturers and even different revisions of the same
// item. The third parameter to the Adafruit_NeoPixel constructor encodes
// the per-pixel byte offsets of the red, green and blue primaries (plus
// white, if present) in the data stream -- the following #defines provide
// an easier-to-use named version for each permutation. e.g. NEO_GRB
// indicates a NeoPixel-compatible device expecting three bytes per pixel,
// with the first byte transmitted containing the green value, second
// containing red and third containing blue. The in-memory representation
// of a chain of NeoPixels is the same as the data-stream order; no
// re-ordering of bytes is required when issuing data to the chain.
// Most of these values won't exist in real-world devices, but it's done
// this way so we're ready for it (also, if using the WS2811 driver IC,
// one might have their pixels set up in any weird permutation).
// Bits 5,4 of this value are the offset (0-3) from the first byte of a
// pixel to the location of the red color byte. Bits 3,2 are the green
// offset and 1,0 are the blue offset. If it is an RGBW-type device
// (supporting a white primary in addition to R,G,B), bits 7,6 are the
// offset to the white byte...otherwise, bits 7,6 are set to the same value
// as 5,4 (red) to indicate an RGB (not RGBW) device.
// i.e. binary representation:
// 0bWWRRGGBB for RGBW devices
// 0bRRRRGGBB for RGB
// RGB NeoPixel permutations; white and red offsets are always same
// Offset: W R G B
#define NEO_RGB ((0<<6) | (0<<4) | (1<<2) | (2)) ///< Transmit as R,G,B
#define NEO_RBG ((0<<6) | (0<<4) | (2<<2) | (1)) ///< Transmit as R,B,G
#define NEO_GRB ((1<<6) | (1<<4) | (0<<2) | (2)) ///< Transmit as G,R,B
#define NEO_GBR ((2<<6) | (2<<4) | (0<<2) | (1)) ///< Transmit as G,B,R
#define NEO_BRG ((1<<6) | (1<<4) | (2<<2) | (0)) ///< Transmit as B,R,G
#define NEO_BGR ((2<<6) | (2<<4) | (1<<2) | (0)) ///< Transmit as B,G,R
// RGBW NeoPixel permutations; all 4 offsets are distinct
// Offset: W R G B
#define NEO_WRGB ((0<<6) | (1<<4) | (2<<2) | (3)) ///< Transmit as W,R,G,B
#define NEO_WRBG ((0<<6) | (1<<4) | (3<<2) | (2)) ///< Transmit as W,R,B,G
#define NEO_WGRB ((0<<6) | (2<<4) | (1<<2) | (3)) ///< Transmit as W,G,R,B
#define NEO_WGBR ((0<<6) | (3<<4) | (1<<2) | (2)) ///< Transmit as W,G,B,R
#define NEO_WBRG ((0<<6) | (2<<4) | (3<<2) | (1)) ///< Transmit as W,B,R,G
#define NEO_WBGR ((0<<6) | (3<<4) | (2<<2) | (1)) ///< Transmit as W,B,G,R
#define NEO_RWGB ((1<<6) | (0<<4) | (2<<2) | (3)) ///< Transmit as R,W,G,B
#define NEO_RWBG ((1<<6) | (0<<4) | (3<<2) | (2)) ///< Transmit as R,W,B,G
#define NEO_RGWB ((2<<6) | (0<<4) | (1<<2) | (3)) ///< Transmit as R,G,W,B
#define NEO_RGBW ((3<<6) | (0<<4) | (1<<2) | (2)) ///< Transmit as R,G,B,W
#define NEO_RBWG ((2<<6) | (0<<4) | (3<<2) | (1)) ///< Transmit as R,B,W,G
#define NEO_RBGW ((3<<6) | (0<<4) | (2<<2) | (1)) ///< Transmit as R,B,G,W
#define NEO_GWRB ((1<<6) | (2<<4) | (0<<2) | (3)) ///< Transmit as G,W,R,B
#define NEO_GWBR ((1<<6) | (3<<4) | (0<<2) | (2)) ///< Transmit as G,W,B,R
#define NEO_GRWB ((2<<6) | (1<<4) | (0<<2) | (3)) ///< Transmit as G,R,W,B
#define NEO_GRBW ((3<<6) | (1<<4) | (0<<2) | (2)) ///< Transmit as G,R,B,W
#define NEO_GBWR ((2<<6) | (3<<4) | (0<<2) | (1)) ///< Transmit as G,B,W,R
#define NEO_GBRW ((3<<6) | (2<<4) | (0<<2) | (1)) ///< Transmit as G,B,R,W
#define NEO_BWRG ((1<<6) | (2<<4) | (3<<2) | (0)) ///< Transmit as B,W,R,G
#define NEO_BWGR ((1<<6) | (3<<4) | (2<<2) | (0)) ///< Transmit as B,W,G,R
#define NEO_BRWG ((2<<6) | (1<<4) | (3<<2) | (0)) ///< Transmit as B,R,W,G
#define NEO_BRGW ((3<<6) | (1<<4) | (2<<2) | (0)) ///< Transmit as B,R,G,W
#define NEO_BGWR ((2<<6) | (3<<4) | (1<<2) | (0)) ///< Transmit as B,G,W,R
#define NEO_BGRW ((3<<6) | (2<<4) | (1<<2) | (0)) ///< Transmit as B,G,R,W
// Add NEO_KHZ400 to the color order value to indicate a 400 KHz device.
// All but the earliest v1 NeoPixels expect an 800 KHz data stream, this is
// the default if unspecified. Because flash space is very limited on ATtiny
// devices (e.g. Trinket, Gemma), v1 NeoPixels aren't handled by default on
// those chips, though it can be enabled by removing the ifndef/endif below,
// but code will be bigger. Conversely, can disable the NEO_KHZ400 line on
// other MCUs to remove v1 support and save a little space.
#define NEO_KHZ800 0x0000 ///< 800 KHz data transmission
#ifndef __AVR_ATtiny85__
#define NEO_KHZ400 0x0100 ///< 400 KHz data transmission
#endif
// If 400 KHz support is enabled, the third parameter to the constructor
// requires a 16-bit value (in order to select 400 vs 800 KHz speed).
// If only 800 KHz is enabled (as is default on ATtiny), an 8-bit value
// is sufficient to encode pixel color order, saving some space.
#ifdef NEO_KHZ400
typedef uint16_t neoPixelType; ///< 3rd arg to Adafruit_NeoPixel constructor
#else
typedef uint8_t neoPixelType; ///< 3rd arg to Adafruit_NeoPixel constructor
#endif
// These two tables are declared outside the Adafruit_NeoPixel class
// because some boards may require oldschool compilers that don't
// handle the C++11 constexpr keyword.
/* A PROGMEM (flash mem) table containing 8-bit unsigned sine wave (0-255).
Copy & paste this snippet into a Python REPL to regenerate:
import math
for x in range(256):
print("{:3},".format(int((math.sin(x/128.0*math.pi)+1.0)*127.5+0.5))),
if x&15 == 15: print
*/
static const uint8_t PROGMEM _NeoPixelSineTable[256] = {
128,131,134,137,140,143,146,149,152,155,158,162,165,167,170,173,
176,179,182,185,188,190,193,196,198,201,203,206,208,211,213,215,
218,220,222,224,226,228,230,232,234,235,237,238,240,241,243,244,
245,246,248,249,250,250,251,252,253,253,254,254,254,255,255,255,
255,255,255,255,254,254,254,253,253,252,251,250,250,249,248,246,
245,244,243,241,240,238,237,235,234,232,230,228,226,224,222,220,
218,215,213,211,208,206,203,201,198,196,193,190,188,185,182,179,
176,173,170,167,165,162,158,155,152,149,146,143,140,137,134,131,
128,124,121,118,115,112,109,106,103,100, 97, 93, 90, 88, 85, 82,
79, 76, 73, 70, 67, 65, 62, 59, 57, 54, 52, 49, 47, 44, 42, 40,
37, 35, 33, 31, 29, 27, 25, 23, 21, 20, 18, 17, 15, 14, 12, 11,
10, 9, 7, 6, 5, 5, 4, 3, 2, 2, 1, 1, 1, 0, 0, 0,
0, 0, 0, 0, 1, 1, 1, 2, 2, 3, 4, 5, 5, 6, 7, 9,
10, 11, 12, 14, 15, 17, 18, 20, 21, 23, 25, 27, 29, 31, 33, 35,
37, 40, 42, 44, 47, 49, 52, 54, 57, 59, 62, 65, 67, 70, 73, 76,
79, 82, 85, 88, 90, 93, 97,100,103,106,109,112,115,118,121,124};
/* Similar to above, but for an 8-bit gamma-correction table.
Copy & paste this snippet into a Python REPL to regenerate:
import math
gamma=2.6
for x in range(256):
print("{:3},".format(int(math.pow((x)/255.0,gamma)*255.0+0.5))),
if x&15 == 15: print
*/
static const uint8_t PROGMEM _NeoPixelGammaTable[256] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3,
3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 7,
7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12,
13, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20,
20, 21, 21, 22, 22, 23, 24, 24, 25, 25, 26, 27, 27, 28, 29, 29,
30, 31, 31, 32, 33, 34, 34, 35, 36, 37, 38, 38, 39, 40, 41, 42,
42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
58, 59, 60, 61, 62, 63, 64, 65, 66, 68, 69, 70, 71, 72, 73, 75,
76, 77, 78, 80, 81, 82, 84, 85, 86, 88, 89, 90, 92, 93, 94, 96,
97, 99,100,102,103,105,106,108,109,111,112,114,115,117,119,120,
122,124,125,127,129,130,132,134,136,137,139,141,143,145,146,148,
150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,
182,184,186,188,191,193,195,197,199,202,204,206,209,211,213,215,
218,220,223,225,227,230,232,235,237,240,242,245,247,250,252,255};
/*!
@brief Class that stores state and functions for interacting with
Adafruit NeoPixels and compatible devices.
*/
class Adafruit_NeoPixel {
public:
// Constructor: number of LEDs, pin number, LED type
Adafruit_NeoPixel(uint16_t n, uint16_t pin=6,
neoPixelType type=NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel(void);
~Adafruit_NeoPixel();
void begin(void);
void show(void);
void setPin(uint16_t p);
void setPixelColor(uint16_t n, uint8_t r, uint8_t g, uint8_t b);
void setPixelColor(uint16_t n, uint8_t r, uint8_t g, uint8_t b,
uint8_t w);
void setPixelColor(uint16_t n, uint32_t c);
void fill(uint32_t c=0, uint16_t first=0, uint16_t count=0);
void setBrightness(uint8_t);
void clear(void);
void updateLength(uint16_t n);
void updateType(neoPixelType t);
/*!
@brief Check whether a call to show() will start sending data
immediately or will 'block' for a required interval. NeoPixels
require a short quiet time (about 300 microseconds) after the
last bit is received before the data 'latches' and new data can
start being received. Usually one's sketch is implicitly using
this time to generate a new frame of animation...but if it
finishes very quickly, this function could be used to see if
there's some idle time available for some low-priority
concurrent task.
@return 1 or true if show() will start sending immediately, 0 or false
if show() would block (meaning some idle time is available).
*/
bool canShow(void) {
if (endTime > micros()) {
endTime = micros();
}
return (micros() - endTime) >= 300L;
}
/*!
@brief Get a pointer directly to the NeoPixel data buffer in RAM.
Pixel data is stored in a device-native format (a la the NEO_*
constants) and is not translated here. Applications that access
this buffer will need to be aware of the specific data format
and handle colors appropriately.
@return Pointer to NeoPixel buffer (uint8_t* array).
@note This is for high-performance applications where calling
setPixelColor() on every single pixel would be too slow (e.g.
POV or light-painting projects). There is no bounds checking
on the array, creating tremendous potential for mayhem if one
writes past the ends of the buffer. Great power, great
responsibility and all that.
*/
uint8_t *getPixels(void) const { return pixels; };
uint8_t getBrightness(void) const;
/*!
@brief Retrieve the pin number used for NeoPixel data output.
@return Arduino pin number (-1 if not set).
*/
int16_t getPin(void) const { return pin; };
/*!
@brief Return the number of pixels in an Adafruit_NeoPixel strip object.
@return Pixel count (0 if not set).
*/
uint16_t numPixels(void) const { return numLEDs; }
uint32_t getPixelColor(uint16_t n) const;
/*!
@brief An 8-bit integer sine wave function, not directly compatible
with standard trigonometric units like radians or degrees.
@param x Input angle, 0-255; 256 would loop back to zero, completing
the circle (equivalent to 360 degrees or 2 pi radians).
One can therefore use an unsigned 8-bit variable and simply
add or subtract, allowing it to overflow/underflow and it
still does the expected contiguous thing.
@return Sine result, 0 to 255, or -128 to +127 if type-converted to
a signed int8_t, but you'll most likely want unsigned as this
output is often used for pixel brightness in animation effects.
*/
static uint8_t sine8(uint8_t x) {
return pgm_read_byte(&_NeoPixelSineTable[x]); // 0-255 in, 0-255 out
}
/*!
@brief An 8-bit gamma-correction function for basic pixel brightness
adjustment. Makes color transitions appear more perceptially
correct.
@param x Input brightness, 0 (minimum or off/black) to 255 (maximum).
@return Gamma-adjusted brightness, can then be passed to one of the
setPixelColor() functions. This uses a fixed gamma correction
exponent of 2.6, which seems reasonably okay for average
NeoPixels in average tasks. If you need finer control you'll
need to provide your own gamma-correction function instead.
*/
static uint8_t gamma8(uint8_t x) {
return pgm_read_byte(&_NeoPixelGammaTable[x]); // 0-255 in, 0-255 out
}
/*!
@brief Convert separate red, green and blue values into a single
"packed" 32-bit RGB color.
@param r Red brightness, 0 to 255.
@param g Green brightness, 0 to 255.
@param b Blue brightness, 0 to 255.
@return 32-bit packed RGB value, which can then be assigned to a
variable for later use or passed to the setPixelColor()
function. Packed RGB format is predictable, regardless of
LED strand color order.
*/
static uint32_t Color(uint8_t r, uint8_t g, uint8_t b) {
return ((uint32_t)r << 16) | ((uint32_t)g << 8) | b;
}
/*!
@brief Convert separate red, green, blue and white values into a
single "packed" 32-bit WRGB color.
@param r Red brightness, 0 to 255.
@param g Green brightness, 0 to 255.
@param b Blue brightness, 0 to 255.
@param w White brightness, 0 to 255.
@return 32-bit packed WRGB value, which can then be assigned to a
variable for later use or passed to the setPixelColor()
function. Packed WRGB format is predictable, regardless of
LED strand color order.
*/
static uint32_t Color(uint8_t r, uint8_t g, uint8_t b, uint8_t w) {
return ((uint32_t)w << 24) | ((uint32_t)r << 16) | ((uint32_t)g << 8) | b;
}
static uint32_t ColorHSV(uint16_t hue, uint8_t sat=255, uint8_t val=255);
/*!
@brief A gamma-correction function for 32-bit packed RGB or WRGB
colors. Makes color transitions appear more perceptially
correct.
@param x 32-bit packed RGB or WRGB color.
@return Gamma-adjusted packed color, can then be passed in one of the
setPixelColor() functions. Like gamma8(), this uses a fixed
gamma correction exponent of 2.6, which seems reasonably okay
for average NeoPixels in average tasks. If you need finer
control you'll need to provide your own gamma-correction
function instead.
*/
static uint32_t gamma32(uint32_t x);
protected:
#ifdef NEO_KHZ400 // If 400 KHz NeoPixel support enabled...
bool is800KHz; ///< true if 800 KHz pixels
#endif
bool begun; ///< true if begin() previously called
uint16_t numLEDs; ///< Number of RGB LEDs in strip
uint16_t numBytes; ///< Size of 'pixels' buffer below
int16_t pin; ///< Output pin number (-1 if not yet set)
uint8_t brightness; ///< Strip brightness 0-255 (stored as +1)
uint8_t *pixels; ///< Holds LED color values (3 or 4 bytes each)
uint8_t rOffset; ///< Red index within each 3- or 4-byte pixel
uint8_t gOffset; ///< Index of green byte
uint8_t bOffset; ///< Index of blue byte
uint8_t wOffset; ///< Index of white (==rOffset if no white)
uint32_t endTime; ///< Latch timing reference
#ifdef __AVR__
volatile uint8_t *port; ///< Output PORT register
uint8_t pinMask; ///< Output PORT bitmask
#endif
#if defined(ARDUINO_ARCH_STM32) || defined(ARDUINO_ARCH_ARDUINO_CORE_STM32)
GPIO_TypeDef *gpioPort; ///< Output GPIO PORT
uint32_t gpioPin; ///< Output GPIO PIN
#endif
};
#endif // ADAFRUIT_NEOPIXEL_H

View File

@ -0,0 +1,13 @@
# Contribution Guidelines
This library is the culmination of the expertise of many members of the open source community who have dedicated their time and hard work. The best way to ask for help or propose a new idea is to [create a new issue](https://github.com/adafruit/Adafruit_NeoPixel/issues/new) while creating a Pull Request with your code changes allows you to share your own innovations with the rest of the community.
The following are some guidelines to observe when creating issues or PRs:
- Be friendly; it is important that we can all enjoy a safe space as we are all working on the same project and it is okay for people to have different ideas
- [Use code blocks](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#code); it helps us help you when we can read your code! On that note also refrain from pasting more than 30 lines of code in a post, instead [create a gist](https://gist.github.com/) if you need to share large snippets
- Use reasonable titles; refrain from using overly long or capitalized titles as they are usually annoying and do little to encourage others to help :smile:
- Be detailed; refrain from mentioning code problems without sharing your source code and always give information regarding your board and version of the library

View File

@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

View File

@ -0,0 +1,153 @@
# Adafruit NeoPixel Library [![Build Status](https://github.com/adafruit/Adafruit_NeoPixel/workflows/Arduino%20Library%20CI/badge.svg)](https://github.com/adafruit/Adafruit_NeoPixel/actions)[![Documentation](https://github.com/adafruit/ci-arduino/blob/master/assets/doxygen_badge.svg)](http://adafruit.github.io/Adafruit_NeoPixel/html/index.html)
Arduino library for controlling single-wire-based LED pixels and strip such as the [Adafruit 60 LED/meter Digital LED strip][strip], the [Adafruit FLORA RGB Smart Pixel][flora], the [Adafruit Breadboard-friendly RGB Smart Pixel][pixel], the [Adafruit NeoPixel Stick][stick], and the [Adafruit NeoPixel Shield][shield].
After downloading, rename folder to 'Adafruit_NeoPixel' and install in Arduino Libraries folder. Restart Arduino IDE, then open File->Sketchbook->Library->Adafruit_NeoPixel->strandtest sketch.
Compatibility notes: Port A is not supported on any AVR processors at this time
[flora]: http://adafruit.com/products/1060
[strip]: http://adafruit.com/products/1138
[pixel]: http://adafruit.com/products/1312
[stick]: http://adafruit.com/products/1426
[shield]: http://adafruit.com/products/1430
---
## Installation
### First Method
![image](https://user-images.githubusercontent.com/36513474/68967967-3e37f480-0803-11ea-91d9-601848c306ee.png)
1. In the Arduino IDE, navigate to Sketch > Include Library > Manage Libraries
1. Then the Library Manager will open and you will find a list of libraries that are already installed or ready for installation.
1. Then search for Neopixel strip using the search bar.
1. Click on the text area and then select the specific version and install it.
### Second Method
1. Navigate to the [Releases page](https://github.com/adafruit/Adafruit_NeoPixel/releases).
1. Download the latest release.
1. Extract the zip file
1. In the Arduino IDE, navigate to Sketch > Include Library > Add .ZIP Library
## Features
- ### Simple to use
Controlling NeoPixels “from scratch” is quite a challenge, so we provide a library letting you focus on the fun and interesting bits.
- ### Give back
The library is free; you dont have to pay for anything. Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit!
- ### Supported Chipsets
We have included code for the following chips - sometimes these break for exciting reasons that we can't control in which case please open an issue!
- AVR ATmega and ATtiny (any 8-bit) - 8 MHz, 12 MHz and 16 MHz
- Teensy 3.x and LC
- Arduino Due
- Arduino 101
- ATSAMD21 (Arduino Zero/M0 and other SAMD21 boards) @ 48 MHz
- ATSAMD51 @ 120 MHz
- Adafruit STM32 Feather @ 120 MHz
- ESP8266 any speed
- ESP32 any speed
- Nordic nRF52 (Adafruit Feather nRF52), nRF51 (micro:bit)
Check forks for other architectures not listed here!
- ### GNU Lesser General Public License
Adafruit_NeoPixel is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
## Functions
- begin()
- updateLength()
- updateType()
- show()
- delay_ns()
- setPin()
- setPixelColor()
- fill()
- ColorHSV()
- getPixelColor()
- setBrightness()
- getBrightness()
- clear()
- gamma32()
## Examples
There are many examples implemented in this library. One of the examples is below. You can find other examples [here](https://github.com/adafruit/Adafruit_NeoPixel/tree/master/examples)
### Simple
```Cpp
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
#define PIN 6
#define NUMPIXELS 16
Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
#define DELAYVAL 500
void setup() {
#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
clock_prescale_set(clock_div_1);
#endif
pixels.begin();
}
void loop() {
pixels.clear();
for(int i=0; i<NUMPIXELS; i++) {
pixels.setPixelColor(i, pixels.Color(0, 150, 0));
pixels.show();
delay(DELAYVAL);
}
}
```
## Contributing
If you want to contribute to this project:
- Report bugs and errors
- Ask for enhancements
- Create issues and pull requests
- Tell others about this library
- Contribute new protocols
Please read [CONTRIBUTING.md](https://github.com/adafruit/Adafruit_NeoPixel/blob/master/CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us.
### Roadmap
The PRIME DIRECTIVE is to maintain backward compatibility with existing Arduino sketches -- many are hosted elsewhere and don't track changes here, some are in print and can never be changed!
Please don't reformat code for the sake of reformatting code. The resulting large "visual diff" makes it impossible to untangle actual bug fixes from merely rearranged lines. (Exception for first item in wishlist below.)
Things I'd Like To Do But There's No Official Timeline So Please Don't Count On Any Of This Ever Being Canonical:
- For the show() function (with all the delicate pixel timing stuff), break out each architecture into separate source files rather than the current unmaintainable tangle of #ifdef statements!
- Please don't use updateLength() or updateType() in new code. They should not have been implemented this way (use the C++ 'new' operator with the regular constructor instead) and are only sticking around because of the Prime Directive. setPin() is OK for now though, it's a trick we can use to 'recycle' pixel memory across multiple strips.
- In the M0 and M4 code, use the hardware systick counter for bit timing rather than hand-tweaked NOPs (a temporary kludge at the time because I wasn't reading systick correctly). (As of 1.4.2, systick is used on M4 devices and it appears to be overclock-compatible. Not for M0 yet, which is why this item is still here.)
- As currently written, brightness scaling is still a "destructive" operation -- pixel values are altered in RAM and the original value as set can't be accurately read back, only approximated, which has been confusing and frustrating to users. It was done this way at the time because NeoPixel timing is strict, AVR microcontrollers (all we had at the time) are limited, and assembly language is hard. All the 32-bit architectures should have no problem handling nondestructive brightness scaling -- calculating each byte immediately before it's sent out the wire, maintaining the original set value in RAM -- the work just hasn't been done. There's a fair chance even the AVR code could manage it with some intense focus. (The DotStar library achieves nondestructive brightness scaling because it doesn't have to manage data timing so carefully...every architecture, even ATtiny, just takes whatever cycles it needs for the multiply/shift operations.)
## Credits
This library is written by Phil "Paint Your Dragon" Burgess for Adafruit Industries, with contributions by PJRC, Michael Miller and other members of the open source community.
## License
Adafruit_NeoPixel is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
Adafruit_NeoPixel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the [GNU Lesser General Public License](https://www.gnu.org/licenses/lgpl-3.0.en.html) for more details.
You should have received a copy of the GNU Lesser General Public License along with NeoPixel. If not, see [this](https://www.gnu.org/licenses/)

View File

@ -0,0 +1,86 @@
// This is a mash-up of the Due show() code + insights from Michael Miller's
// ESP8266 work for the NeoPixelBus library: github.com/Makuna/NeoPixelBus
// Needs to be a separate .c file to enforce ICACHE_RAM_ATTR execution.
#if defined(ESP8266) || defined(ESP32)
#include <Arduino.h>
#ifdef ESP8266
#include <eagle_soc.h>
#endif
static uint32_t _getCycleCount(void) __attribute__((always_inline));
static inline uint32_t _getCycleCount(void) {
uint32_t ccount;
__asm__ __volatile__("rsr %0,ccount":"=a" (ccount));
return ccount;
}
#ifdef ESP8266
void ICACHE_RAM_ATTR espShow(
uint8_t pin, uint8_t *pixels, uint32_t numBytes, boolean is800KHz) {
#else
void espShow(
uint8_t pin, uint8_t *pixels, uint32_t numBytes, boolean is800KHz) {
#endif
#define CYCLES_800_T0H (F_CPU / 2500000) // 0.4us
#define CYCLES_800_T1H (F_CPU / 1250000) // 0.8us
#define CYCLES_800 (F_CPU / 800000) // 1.25us per bit
#define CYCLES_400_T0H (F_CPU / 2000000) // 0.5uS
#define CYCLES_400_T1H (F_CPU / 833333) // 1.2us
#define CYCLES_400 (F_CPU / 400000) // 2.5us per bit
uint8_t *p, *end, pix, mask;
uint32_t t, time0, time1, period, c, startTime;
#ifdef ESP8266
uint32_t pinMask;
pinMask = _BV(pin);
#endif
p = pixels;
end = p + numBytes;
pix = *p++;
mask = 0x80;
startTime = 0;
#ifdef NEO_KHZ400
if(is800KHz) {
#endif
time0 = CYCLES_800_T0H;
time1 = CYCLES_800_T1H;
period = CYCLES_800;
#ifdef NEO_KHZ400
} else { // 400 KHz bitstream
time0 = CYCLES_400_T0H;
time1 = CYCLES_400_T1H;
period = CYCLES_400;
}
#endif
for(t = time0;; t = time0) {
if(pix & mask) t = time1; // Bit high duration
while(((c = _getCycleCount()) - startTime) < period); // Wait for bit start
#ifdef ESP8266
GPIO_REG_WRITE(GPIO_OUT_W1TS_ADDRESS, pinMask); // Set high
#else
gpio_set_level(pin, HIGH);
#endif
startTime = c; // Save start time
while(((c = _getCycleCount()) - startTime) < t); // Wait high duration
#ifdef ESP8266
GPIO_REG_WRITE(GPIO_OUT_W1TC_ADDRESS, pinMask); // Set low
#else
gpio_set_level(pin, LOW);
#endif
if(!(mask >>= 1)) { // Next bit/byte
if(p >= end) break;
pix = *p++;
mask = 0x80;
}
}
while((_getCycleCount() - startTime) < period); // Wait for last bit
}
#endif // ESP8266

View File

@ -0,0 +1,177 @@
// NeoPixel test program showing use of the WHITE channel for RGBW
// pixels only (won't look correct on regular RGB NeoPixel strips).
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h> // Required for 16 MHz Adafruit Trinket
#endif
// Which pin on the Arduino is connected to the NeoPixels?
// On a Trinket or Gemma we suggest changing this to 1:
#define LED_PIN 6
// How many NeoPixels are attached to the Arduino?
#define LED_COUNT 60
// NeoPixel brightness, 0 (min) to 255 (max)
#define BRIGHTNESS 50
// Declare our NeoPixel strip object:
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRBW + NEO_KHZ800);
// Argument 1 = Number of pixels in NeoPixel strip
// Argument 2 = Arduino pin number (most are valid)
// Argument 3 = Pixel type flags, add together as needed:
// NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
// NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
// NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products)
// NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
// NEO_RGBW Pixels are wired for RGBW bitstream (NeoPixel RGBW products)
void setup() {
// These lines are specifically to support the Adafruit Trinket 5V 16 MHz.
// Any other board, you can remove this part (but no harm leaving it):
#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
clock_prescale_set(clock_div_1);
#endif
// END of Trinket-specific code.
strip.begin(); // INITIALIZE NeoPixel strip object (REQUIRED)
strip.show(); // Turn OFF all pixels ASAP
strip.setBrightness(50); // Set BRIGHTNESS to about 1/5 (max = 255)
}
void loop() {
// Fill along the length of the strip in various colors...
colorWipe(strip.Color(255, 0, 0) , 50); // Red
colorWipe(strip.Color( 0, 255, 0) , 50); // Green
colorWipe(strip.Color( 0, 0, 255) , 50); // Blue
colorWipe(strip.Color( 0, 0, 0, 255), 50); // True white (not RGB white)
whiteOverRainbow(75, 5);
pulseWhite(5);
rainbowFade2White(3, 3, 1);
}
// Fill strip pixels one after another with a color. Strip is NOT cleared
// first; anything there will be covered pixel by pixel. Pass in color
// (as a single 'packed' 32-bit value, which you can get by calling
// strip.Color(red, green, blue) as shown in the loop() function above),
// and a delay time (in milliseconds) between pixels.
void colorWipe(uint32_t color, int wait) {
for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
strip.setPixelColor(i, color); // Set pixel's color (in RAM)
strip.show(); // Update strip to match
delay(wait); // Pause for a moment
}
}
void whiteOverRainbow(int whiteSpeed, int whiteLength) {
if(whiteLength >= strip.numPixels()) whiteLength = strip.numPixels() - 1;
int head = whiteLength - 1;
int tail = 0;
int loops = 3;
int loopNum = 0;
uint32_t lastTime = millis();
uint32_t firstPixelHue = 0;
for(;;) { // Repeat forever (or until a 'break' or 'return')
for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
if(((i >= tail) && (i <= head)) || // If between head & tail...
((tail > head) && ((i >= tail) || (i <= head)))) {
strip.setPixelColor(i, strip.Color(0, 0, 0, 255)); // Set white
} else { // else set rainbow
int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());
strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue)));
}
}
strip.show(); // Update strip with new contents
// There's no delay here, it just runs full-tilt until the timer and
// counter combination below runs out.
firstPixelHue += 40; // Advance just a little along the color wheel
if((millis() - lastTime) > whiteSpeed) { // Time to update head/tail?
if(++head >= strip.numPixels()) { // Advance head, wrap around
head = 0;
if(++loopNum >= loops) return;
}
if(++tail >= strip.numPixels()) { // Advance tail, wrap around
tail = 0;
}
lastTime = millis(); // Save time of last movement
}
}
}
void pulseWhite(uint8_t wait) {
for(int j=0; j<256; j++) { // Ramp up from 0 to 255
// Fill entire strip with white at gamma-corrected brightness level 'j':
strip.fill(strip.Color(0, 0, 0, strip.gamma8(j)));
strip.show();
delay(wait);
}
for(int j=255; j>=0; j--) { // Ramp down from 255 to 0
strip.fill(strip.Color(0, 0, 0, strip.gamma8(j)));
strip.show();
delay(wait);
}
}
void rainbowFade2White(int wait, int rainbowLoops, int whiteLoops) {
int fadeVal=0, fadeMax=100;
// Hue of first pixel runs 'rainbowLoops' complete loops through the color
// wheel. Color wheel has a range of 65536 but it's OK if we roll over, so
// just count from 0 to rainbowLoops*65536, using steps of 256 so we
// advance around the wheel at a decent clip.
for(uint32_t firstPixelHue = 0; firstPixelHue < rainbowLoops*65536;
firstPixelHue += 256) {
for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
// Offset pixel hue by an amount to make one full revolution of the
// color wheel (range of 65536) along the length of the strip
// (strip.numPixels() steps):
uint32_t pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());
// strip.ColorHSV() can take 1 or 3 arguments: a hue (0 to 65535) or
// optionally add saturation and value (brightness) (each 0 to 255).
// Here we're using just the three-argument variant, though the
// second value (saturation) is a constant 255.
strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue, 255,
255 * fadeVal / fadeMax)));
}
strip.show();
delay(wait);
if(firstPixelHue < 65536) { // First loop,
if(fadeVal < fadeMax) fadeVal++; // fade in
} else if(firstPixelHue >= ((rainbowLoops-1) * 65536)) { // Last loop,
if(fadeVal > 0) fadeVal--; // fade out
} else {
fadeVal = fadeMax; // Interim loop, make sure fade is at max
}
}
for(int k=0; k<whiteLoops; k++) {
for(int j=0; j<256; j++) { // Ramp up 0 to 255
// Fill entire strip with white at gamma-corrected brightness level 'j':
strip.fill(strip.Color(0, 0, 0, strip.gamma8(j)));
strip.show();
}
delay(1000); // Pause 1 second
for(int j=255; j>=0; j--) { // Ramp down 255 to 0
strip.fill(strip.Color(0, 0, 0, strip.gamma8(j)));
strip.show();
}
}
delay(500); // Pause 1/2 second
}

View File

@ -0,0 +1,231 @@
/****************************************************************************
* This example is based on StrandtestBLE example and adapts it to use
* the new ArduinoBLE library.
*
* https://github.com/arduino-libraries/ArduinoBLE
*
* Supported boards:
* Arduino MKR WiFi 1010, Arduino Uno WiFi Rev2 board, Arduino Nano 33 IoT,
Arduino Nano 33 BLE, or Arduino Nano 33 BLE Sense board.
*
* You can use a generic BLE central app, like LightBlue (iOS and Android) or
* nRF Connect (Android), to interact with the services and characteristics
* created in this sketch.
*
* This example code is in the public domain.
*
*/
#include <Adafruit_NeoPixel.h>
#define PIN 15 // Pin where NeoPixels are connected
// Declare our NeoPixel strip object:
Adafruit_NeoPixel strip(64, PIN, NEO_GRB + NEO_KHZ800);
// Argument 1 = Number of pixels in NeoPixel strip
// Argument 2 = Arduino pin number (most are valid)
// Argument 3 = Pixel type flags, add together as needed:
// NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
// NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
// NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products)
// NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
// NEO_RGBW Pixels are wired for RGBW bitstream (NeoPixel RGBW products)
// NEOPIXEL BEST PRACTICES for most reliable operation:
// - Add 1000 uF CAPACITOR between NeoPixel strip's + and - connections.
// - MINIMIZE WIRING LENGTH between microcontroller board and first pixel.
// - NeoPixel strip's DATA-IN should pass through a 300-500 OHM RESISTOR.
// - AVOID connecting NeoPixels on a LIVE CIRCUIT. If you must, ALWAYS
// connect GROUND (-) first, then +, then data.
// - When using a 3.3V microcontroller with a 5V-powered NeoPixel strip,
// a LOGIC-LEVEL CONVERTER on the data line is STRONGLY RECOMMENDED.
// (Skipping these may work OK on your workbench but can fail in the field)
uint8_t rgb_values[3];
#include <ArduinoBLE.h>
BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // BLE LED Service
// BLE LED Switch Characteristic - custom 128-bit UUID, read and writable by central
BLEByteCharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
void setup()
{
Serial.begin(115200);
Serial.println("Hello World!");
// custom services and characteristics can be added as well
// begin initialization
if (!BLE.begin())
{
Serial.println("starting BLE failed!");
while (1)
;
}
Serial.print("Peripheral address: ");
Serial.println(BLE.address());
// set advertised local name and service UUID:
BLE.setLocalName("LED");
BLE.setAdvertisedService(ledService);
// add the characteristic to the service
ledService.addCharacteristic(switchCharacteristic);
// add service
BLE.addService(ledService);
// set the initial value for the characeristic:
switchCharacteristic.writeValue(0);
// start advertising
BLE.advertise();
strip.begin(); // INITIALIZE NeoPixel strip object (REQUIRED)
strip.show(); // Turn OFF all pixels ASAP
pinMode(PIN, OUTPUT);
digitalWrite(PIN, LOW);
}
void loop()
{
BLEDevice central = BLE.central();
// if a central is connected to peripheral:
if (central)
{
Serial.print("Connected to central: ");
// print the central's MAC address:
Serial.println(central.address());
// while the central is still connected to peripheral:
while (central.connected())
{
// if the remote device wrote to the characteristic,
// use the value to control the LED:
if (switchCharacteristic.written())
{
switch (switchCharacteristic.value())
{
case 'a':
colorWipe(strip.Color(255, 0, 0), 20); // Red
break;
case 'b':
colorWipe(strip.Color(0, 255, 0), 20); // Green
break;
case 'c':
colorWipe(strip.Color(0, 0, 255), 20); // Blue
break;
case 'd':
theaterChase(strip.Color(255, 0, 0), 20); // Red
break;
case 'e':
theaterChase(strip.Color(0, 255, 0), 20); // Green
break;
case 'f':
theaterChase(strip.Color(255, 0, 255), 20); // Cyan
break;
case 'g':
rainbow(10);
break;
case 'h':
theaterChaseRainbow(20);
break;
}
}
}
}
}
// Fill strip pixels one after another with a color. Strip is NOT cleared
// first; anything there will be covered pixel by pixel. Pass in color
// (as a single 'packed' 32-bit value, which you can get by calling
// strip.Color(red, green, blue) as shown in the loop() function above),
// and a delay time (in milliseconds) between pixels.
void colorWipe(uint32_t color, int wait)
{
for (int i = 0; i < strip.numPixels(); i++)
{ // For each pixel in strip...
strip.setPixelColor(i, color); // Set pixel's color (in RAM)
strip.show(); // Update strip to match
delay(wait); // Pause for a moment
}
}
// Theater-marquee-style chasing lights. Pass in a color (32-bit value,
// a la strip.Color(r,g,b) as mentioned above), and a delay time (in ms)
// between frames.
void theaterChase(uint32_t color, int wait)
{
for (int a = 0; a < 10; a++)
{ // Repeat 10 times...
for (int b = 0; b < 3; b++)
{ // 'b' counts from 0 to 2...
strip.clear(); // Set all pixels in RAM to 0 (off)
// 'c' counts up from 'b' to end of strip in steps of 3...
for (int c = b; c < strip.numPixels(); c += 3)
{
strip.setPixelColor(c, color); // Set pixel 'c' to value 'color'
}
strip.show(); // Update strip with new contents
delay(wait); // Pause for a moment
}
}
}
// Rainbow cycle along whole strip. Pass delay time (in ms) between frames.
void rainbow(int wait)
{
// Hue of first pixel runs 5 complete loops through the color wheel.
// Color wheel has a range of 65536 but it's OK if we roll over, so
// just count from 0 to 5*65536. Adding 256 to firstPixelHue each time
// means we'll make 5*65536/256 = 1280 passes through this outer loop:
for (long firstPixelHue = 0; firstPixelHue < 5 * 65536; firstPixelHue += 256)
{
for (int i = 0; i < strip.numPixels(); i++)
{ // For each pixel in strip...
// Offset pixel hue by an amount to make one full revolution of the
// color wheel (range of 65536) along the length of the strip
// (strip.numPixels() steps):
int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());
// strip.ColorHSV() can take 1 or 3 arguments: a hue (0 to 65535) or
// optionally add saturation and value (brightness) (each 0 to 255).
// Here we're using just the single-argument hue variant. The result
// is passed through strip.gamma32() to provide 'truer' colors
// before assigning to each pixel:
strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue)));
}
strip.show(); // Update strip with new contents
delay(wait); // Pause for a moment
}
}
// Rainbow-enhanced theater marquee. Pass delay time (in ms) between frames.
void theaterChaseRainbow(int wait)
{
int firstPixelHue = 0; // First pixel starts at red (hue 0)
for (int a = 0; a < 30; a++)
{ // Repeat 30 times...
for (int b = 0; b < 3; b++)
{ // 'b' counts from 0 to 2...
strip.clear(); // Set all pixels in RAM to 0 (off)
// 'c' counts up from 'b' to end of strip in increments of 3...
for (int c = b; c < strip.numPixels(); c += 3)
{
// hue of pixel 'c' is offset by an amount to make one full
// revolution of the color wheel (range 65536) along the length
// of the strip (strip.numPixels() steps):
int hue = firstPixelHue + c * 65536L / strip.numPixels();
uint32_t color = strip.gamma32(strip.ColorHSV(hue)); // hue -> RGB
strip.setPixelColor(c, color); // Set pixel 'c' to value 'color'
}
strip.show(); // Update strip with new contents
delay(wait); // Pause for a moment
firstPixelHue += 65536 / 90; // One cycle of color wheel over 90 frames
}
}
}

View File

@ -0,0 +1,239 @@
/****************************************************************************
* This example is based on StrandtestArduinoBLE example to make use of
* callbacks features of the ArduinoBLE library.
*
* https://github.com/arduino-libraries/ArduinoBLE
*
* Supported boards:
* Arduino MKR WiFi 1010, Arduino Uno WiFi Rev2 board, Arduino Nano 33 IoT,
Arduino Nano 33 BLE, or Arduino Nano 33 BLE Sense board.
*
* You can use a generic BLE central app, like LightBlue (iOS and Android) or
* nRF Connect (Android), to interact with the services and characteristics
* created in this sketch.
*
* This example code is in the public domain.
*
*/
#include <Adafruit_NeoPixel.h>
#define PIN 15 // Pin where NeoPixels are connected
// Declare our NeoPixel strip object:
Adafruit_NeoPixel strip(64, PIN, NEO_GRB + NEO_KHZ800);
// Argument 1 = Number of pixels in NeoPixel strip
// Argument 2 = Arduino pin number (most are valid)
// Argument 3 = Pixel type flags, add together as needed:
// NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
// NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
// NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products)
// NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
// NEO_RGBW Pixels are wired for RGBW bitstream (NeoPixel RGBW products)
// NEOPIXEL BEST PRACTICES for most reliable operation:
// - Add 1000 uF CAPACITOR between NeoPixel strip's + and - connections.
// - MINIMIZE WIRING LENGTH between microcontroller board and first pixel.
// - NeoPixel strip's DATA-IN should pass through a 300-500 OHM RESISTOR.
// - AVOID connecting NeoPixels on a LIVE CIRCUIT. If you must, ALWAYS
// connect GROUND (-) first, then +, then data.
// - When using a 3.3V microcontroller with a 5V-powered NeoPixel strip,
// a LOGIC-LEVEL CONVERTER on the data line is STRONGLY RECOMMENDED.
// (Skipping these may work OK on your workbench but can fail in the field)
uint8_t rgb_values[3];
#include <ArduinoBLE.h>
BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // BLE LED Service
// BLE LED Switch Characteristic - custom 128-bit UUID, read and writable by central
BLEByteCharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
void setup()
{
Serial.begin(115200);
Serial.println("Hello World!");
// custom services and characteristics can be added as well
// begin initialization
if (!BLE.begin())
{
Serial.println("starting BLE failed!");
while (1)
;
}
Serial.print("Peripheral address: ");
Serial.println(BLE.address());
// set advertised local name and service UUID:
BLE.setLocalName("LEDCallback");
BLE.setAdvertisedService(ledService);
// add the characteristic to the service
ledService.addCharacteristic(switchCharacteristic);
// add service
BLE.addService(ledService);
// assign event handlers for connected, disconnected to peripheral
BLE.setEventHandler(BLEConnected, blePeripheralConnectHandler);
BLE.setEventHandler(BLEDisconnected, blePeripheralDisconnectHandler);
// assign event handlers for characteristic
switchCharacteristic.setEventHandler(BLEWritten, switchCharacteristicWritten);
// set the initial value for the characeristic:
switchCharacteristic.writeValue(0);
// start advertising
BLE.advertise();
strip.begin(); // INITIALIZE NeoPixel strip object (REQUIRED)
strip.show(); // Turn OFF all pixels ASAP
pinMode(PIN, OUTPUT);
digitalWrite(PIN, LOW);
}
void loop()
{
// poll for BLE events
BLE.poll();
}
void blePeripheralConnectHandler(BLEDevice central)
{
// central connected event handler
Serial.print("Connected event, central: ");
Serial.println(central.address());
}
void blePeripheralDisconnectHandler(BLEDevice central)
{
// central disconnected event handler
Serial.print("Disconnected event, central: ");
Serial.println(central.address());
}
void switchCharacteristicWritten(BLEDevice central, BLECharacteristic characteristic)
{
// central wrote new value to characteristic, update LED
Serial.print("Characteristic event, written: ");
switch (switchCharacteristic.value())
{
case 'a':
colorWipe(strip.Color(255, 0, 0), 20); // Red
break;
case 'b':
colorWipe(strip.Color(0, 255, 0), 20); // Green
break;
case 'c':
colorWipe(strip.Color(0, 0, 255), 20); // Blue
break;
case 'd':
theaterChase(strip.Color(255, 0, 0), 20); // Red
break;
case 'e':
theaterChase(strip.Color(0, 255, 0), 20); // Green
break;
case 'f':
theaterChase(strip.Color(255, 0, 255), 20); // Cyan
break;
case 'g':
rainbow(10);
break;
case 'h':
theaterChaseRainbow(20);
break;
}
}
// Fill strip pixels one after another with a color. Strip is NOT cleared
// first; anything there will be covered pixel by pixel. Pass in color
// (as a single 'packed' 32-bit value, which you can get by calling
// strip.Color(red, green, blue) as shown in the loop() function above),
// and a delay time (in milliseconds) between pixels.
void colorWipe(uint32_t color, int wait)
{
for (int i = 0; i < strip.numPixels(); i++)
{ // For each pixel in strip...
strip.setPixelColor(i, color); // Set pixel's color (in RAM)
strip.show(); // Update strip to match
delay(wait); // Pause for a moment
}
}
// Theater-marquee-style chasing lights. Pass in a color (32-bit value,
// a la strip.Color(r,g,b) as mentioned above), and a delay time (in ms)
// between frames.
void theaterChase(uint32_t color, int wait)
{
for (int a = 0; a < 10; a++)
{ // Repeat 10 times...
for (int b = 0; b < 3; b++)
{ // 'b' counts from 0 to 2...
strip.clear(); // Set all pixels in RAM to 0 (off)
// 'c' counts up from 'b' to end of strip in steps of 3...
for (int c = b; c < strip.numPixels(); c += 3)
{
strip.setPixelColor(c, color); // Set pixel 'c' to value 'color'
}
strip.show(); // Update strip with new contents
delay(wait); // Pause for a moment
}
}
}
// Rainbow cycle along whole strip. Pass delay time (in ms) between frames.
void rainbow(int wait)
{
// Hue of first pixel runs 5 complete loops through the color wheel.
// Color wheel has a range of 65536 but it's OK if we roll over, so
// just count from 0 to 5*65536. Adding 256 to firstPixelHue each time
// means we'll make 5*65536/256 = 1280 passes through this outer loop:
for (long firstPixelHue = 0; firstPixelHue < 5 * 65536; firstPixelHue += 256)
{
for (int i = 0; i < strip.numPixels(); i++)
{ // For each pixel in strip...
// Offset pixel hue by an amount to make one full revolution of the
// color wheel (range of 65536) along the length of the strip
// (strip.numPixels() steps):
int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());
// strip.ColorHSV() can take 1 or 3 arguments: a hue (0 to 65535) or
// optionally add saturation and value (brightness) (each 0 to 255).
// Here we're using just the single-argument hue variant. The result
// is passed through strip.gamma32() to provide 'truer' colors
// before assigning to each pixel:
strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue)));
}
strip.show(); // Update strip with new contents
delay(wait); // Pause for a moment
}
}
// Rainbow-enhanced theater marquee. Pass delay time (in ms) between frames.
void theaterChaseRainbow(int wait)
{
int firstPixelHue = 0; // First pixel starts at red (hue 0)
for (int a = 0; a < 30; a++)
{ // Repeat 30 times...
for (int b = 0; b < 3; b++)
{ // 'b' counts from 0 to 2...
strip.clear(); // Set all pixels in RAM to 0 (off)
// 'c' counts up from 'b' to end of strip in increments of 3...
for (int c = b; c < strip.numPixels(); c += 3)
{
// hue of pixel 'c' is offset by an amount to make one full
// revolution of the color wheel (range 65536) along the length
// of the strip (strip.numPixels() steps):
int hue = firstPixelHue + c * 65536L / strip.numPixels();
uint32_t color = strip.gamma32(strip.ColorHSV(hue)); // hue -> RGB
strip.setPixelColor(c, color); // Set pixel 'c' to value 'color'
}
strip.show(); // Update strip with new contents
delay(wait); // Pause for a moment
firstPixelHue += 65536 / 90; // One cycle of color wheel over 90 frames
}
}
}

View File

@ -0,0 +1,133 @@
#include "BLESerial.h"
// #define BLE_SERIAL_DEBUG
BLESerial* BLESerial::_instance = NULL;
BLESerial::BLESerial(unsigned char req, unsigned char rdy, unsigned char rst) :
BLEPeripheral(req, rdy, rst)
{
this->_txCount = 0;
this->_rxHead = this->_rxTail = 0;
this->_flushed = 0;
BLESerial::_instance = this;
addAttribute(this->_uartService);
addAttribute(this->_uartNameDescriptor);
setAdvertisedServiceUuid(this->_uartService.uuid());
addAttribute(this->_rxCharacteristic);
addAttribute(this->_rxNameDescriptor);
this->_rxCharacteristic.setEventHandler(BLEWritten, BLESerial::_received);
addAttribute(this->_txCharacteristic);
addAttribute(this->_txNameDescriptor);
}
void BLESerial::begin(...) {
BLEPeripheral::begin();
#ifdef BLE_SERIAL_DEBUG
Serial.println(F("BLESerial::begin()"));
#endif
}
void BLESerial::poll() {
if (millis() < this->_flushed + 100) {
BLEPeripheral::poll();
} else {
flush();
}
}
void BLESerial::end() {
this->_rxCharacteristic.setEventHandler(BLEWritten, NULL);
this->_rxHead = this->_rxTail = 0;
flush();
BLEPeripheral::disconnect();
}
int BLESerial::available(void) {
BLEPeripheral::poll();
int retval = (this->_rxHead - this->_rxTail + sizeof(this->_rxBuffer)) % sizeof(this->_rxBuffer);
#ifdef BLE_SERIAL_DEBUG
Serial.print(F("BLESerial::available() = "));
Serial.println(retval);
#endif
return retval;
}
int BLESerial::peek(void) {
BLEPeripheral::poll();
if (this->_rxTail == this->_rxHead) return -1;
uint8_t byte = this->_rxBuffer[this->_rxTail];
#ifdef BLE_SERIAL_DEBUG
Serial.print(F("BLESerial::peek() = "));
Serial.print((char) byte);
Serial.print(F(" 0x"));
Serial.println(byte, HEX);
#endif
return byte;
}
int BLESerial::read(void) {
BLEPeripheral::poll();
if (this->_rxTail == this->_rxHead) return -1;
this->_rxTail = (this->_rxTail + 1) % sizeof(this->_rxBuffer);
uint8_t byte = this->_rxBuffer[this->_rxTail];
#ifdef BLE_SERIAL_DEBUG
Serial.print(F("BLESerial::read() = "));
Serial.print((char) byte);
Serial.print(F(" 0x"));
Serial.println(byte, HEX);
#endif
return byte;
}
void BLESerial::flush(void) {
if (this->_txCount == 0) return;
this->_txCharacteristic.setValue(this->_txBuffer, this->_txCount);
this->_flushed = millis();
this->_txCount = 0;
BLEPeripheral::poll();
#ifdef BLE_SERIAL_DEBUG
Serial.println(F("BLESerial::flush()"));
#endif
}
size_t BLESerial::write(uint8_t byte) {
BLEPeripheral::poll();
if (this->_txCharacteristic.subscribed() == false) return 0;
this->_txBuffer[this->_txCount++] = byte;
if (this->_txCount == sizeof(this->_txBuffer)) flush();
#ifdef BLE_SERIAL_DEBUG
Serial.print(F("BLESerial::write("));
Serial.print((char) byte);
Serial.print(F(" 0x"));
Serial.print(byte, HEX);
Serial.println(F(") = 1"));
#endif
return 1;
}
BLESerial::operator bool() {
bool retval = BLEPeripheral::connected();
#ifdef BLE_SERIAL_DEBUG
Serial.print(F("BLESerial::operator bool() = "));
Serial.println(retval);
#endif
return retval;
}
void BLESerial::_received(const uint8_t* data, size_t size) {
for (int i = 0; i < size; i++) {
this->_rxHead = (this->_rxHead + 1) % sizeof(this->_rxBuffer);
this->_rxBuffer[this->_rxHead] = data[i];
}
#ifdef BLE_SERIAL_DEBUG
Serial.print(F("BLESerial::received("));
for (int i = 0; i < size; i++) Serial.print((char) data[i]);
Serial.println(F(")"));
#endif
}
void BLESerial::_received(BLECentral& /*central*/, BLECharacteristic& rxCharacteristic) {
BLESerial::_instance->_received(rxCharacteristic.value(), rxCharacteristic.valueLength());
}

View File

@ -0,0 +1,46 @@
#ifndef _BLE_SERIAL_H_
#define _BLE_SERIAL_H_
#include <Arduino.h>
#include <BLEPeripheral.h>
class BLESerial : public BLEPeripheral, public Stream
{
public:
BLESerial(unsigned char req, unsigned char rdy, unsigned char rst);
void begin(...);
void poll();
void end();
virtual int available(void);
virtual int peek(void);
virtual int read(void);
virtual void flush(void);
virtual size_t write(uint8_t byte);
using Print::write;
virtual operator bool();
private:
unsigned long _flushed;
static BLESerial* _instance;
size_t _rxHead;
size_t _rxTail;
size_t _rxCount() const;
uint8_t _rxBuffer[BLE_ATTRIBUTE_MAX_VALUE_LENGTH];
size_t _txCount;
uint8_t _txBuffer[BLE_ATTRIBUTE_MAX_VALUE_LENGTH];
BLEService _uartService = BLEService("6E400001-B5A3-F393-E0A9-E50E24DCCA9E");
BLEDescriptor _uartNameDescriptor = BLEDescriptor("2901", "UART");
BLECharacteristic _rxCharacteristic = BLECharacteristic("6E400002-B5A3-F393-E0A9-E50E24DCCA9E", BLEWriteWithoutResponse, BLE_ATTRIBUTE_MAX_VALUE_LENGTH);
BLEDescriptor _rxNameDescriptor = BLEDescriptor("2901", "RX - Receive Data (Write)");
BLECharacteristic _txCharacteristic = BLECharacteristic("6E400003-B5A3-F393-E0A9-E50E24DCCA9E", BLENotify, BLE_ATTRIBUTE_MAX_VALUE_LENGTH);
BLEDescriptor _txNameDescriptor = BLEDescriptor("2901", "TX - Transfer Data (Notify)");
void _received(const uint8_t* data, size_t size);
static void _received(BLECentral& /*central*/, BLECharacteristic& rxCharacteristic);
};
#endif

View File

@ -0,0 +1,192 @@
/****************************************************************************
* This example was developed by the Hackerspace San Salvador to demonstrate
* the simultaneous use of the NeoPixel library and the Bluetooth SoftDevice.
* To compile this example you'll need to add support for the NRF52 based
* following the instructions at:
* https://github.com/sandeepmistry/arduino-nRF5
* Or adding the following URL to the board manager URLs on Arduino preferences:
* https://sandeepmistry.github.io/arduino-nRF5/package_nRF5_boards_index.json
* Then you can install the BLEPeripheral library avaiable at:
* https://github.com/sandeepmistry/arduino-BLEPeripheral
* To test it, compile this example and use the UART module from the nRF
* Toolbox App for Android. Edit the interface and send the characters
* 'a' to 'i' to switch the animation.
* There is a delay because this example blocks the thread of execution but
* the change will be shown after the current animation ends. (This might
* take a couple of seconds)
* For more info write us at: info _at- teubi.co
*/
#include <SPI.h>
#include <BLEPeripheral.h>
#include "BLESerial.h"
#include <Adafruit_NeoPixel.h>
#define PIN 15 // Pin where NeoPixels are connected
// Declare our NeoPixel strip object:
Adafruit_NeoPixel strip(64, PIN, NEO_GRB + NEO_KHZ800);
// Argument 1 = Number of pixels in NeoPixel strip
// Argument 2 = Arduino pin number (most are valid)
// Argument 3 = Pixel type flags, add together as needed:
// NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
// NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
// NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products)
// NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
// NEO_RGBW Pixels are wired for RGBW bitstream (NeoPixel RGBW products)
// NEOPIXEL BEST PRACTICES for most reliable operation:
// - Add 1000 uF CAPACITOR between NeoPixel strip's + and - connections.
// - MINIMIZE WIRING LENGTH between microcontroller board and first pixel.
// - NeoPixel strip's DATA-IN should pass through a 300-500 OHM RESISTOR.
// - AVOID connecting NeoPixels on a LIVE CIRCUIT. If you must, ALWAYS
// connect GROUND (-) first, then +, then data.
// - When using a 3.3V microcontroller with a 5V-powered NeoPixel strip,
// a LOGIC-LEVEL CONVERTER on the data line is STRONGLY RECOMMENDED.
// (Skipping these may work OK on your workbench but can fail in the field)
// define pins (varies per shield/board)
#define BLE_REQ 10
#define BLE_RDY 2
#define BLE_RST 9
// create ble serial instance, see pinouts above
BLESerial BLESerial(BLE_REQ, BLE_RDY, BLE_RST);
uint8_t current_state = 0;
uint8_t rgb_values[3];
void setup() {
Serial.begin(115200);
Serial.println("Hello World!");
// custom services and characteristics can be added as well
BLESerial.setLocalName("UART_HS");
BLESerial.begin();
strip.begin(); // INITIALIZE NeoPixel strip object (REQUIRED)
strip.show(); // Turn OFF all pixels ASAP
//pinMode(PIN, OUTPUT);
//digitalWrite(PIN, LOW);
current_state = 'a';
}
void loop() {
while(BLESerial.available()) {
uint8_t character = BLESerial.read();
switch(character) {
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
current_state = character;
break;
};
}
switch(current_state) {
case 'a':
colorWipe(strip.Color(255, 0, 0), 20); // Red
break;
case 'b':
colorWipe(strip.Color( 0, 255, 0), 20); // Green
break;
case 'c':
colorWipe(strip.Color( 0, 0, 255), 20); // Blue
break;
case 'd':
theaterChase(strip.Color(255, 0, 0), 20); // Red
break;
case 'e':
theaterChase(strip.Color( 0, 255, 0), 20); // Green
break;
case 'f':
theaterChase(strip.Color(255, 0, 255), 20); // Cyan
break;
case 'g':
rainbow(10);
break;
case 'h':
theaterChaseRainbow(20);
break;
}
}
// Fill strip pixels one after another with a color. Strip is NOT cleared
// first; anything there will be covered pixel by pixel. Pass in color
// (as a single 'packed' 32-bit value, which you can get by calling
// strip.Color(red, green, blue) as shown in the loop() function above),
// and a delay time (in milliseconds) between pixels.
void colorWipe(uint32_t color, int wait) {
for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
strip.setPixelColor(i, color); // Set pixel's color (in RAM)
strip.show(); // Update strip to match
delay(wait); // Pause for a moment
}
}
// Theater-marquee-style chasing lights. Pass in a color (32-bit value,
// a la strip.Color(r,g,b) as mentioned above), and a delay time (in ms)
// between frames.
void theaterChase(uint32_t color, int wait) {
for(int a=0; a<10; a++) { // Repeat 10 times...
for(int b=0; b<3; b++) { // 'b' counts from 0 to 2...
strip.clear(); // Set all pixels in RAM to 0 (off)
// 'c' counts up from 'b' to end of strip in steps of 3...
for(int c=b; c<strip.numPixels(); c += 3) {
strip.setPixelColor(c, color); // Set pixel 'c' to value 'color'
}
strip.show(); // Update strip with new contents
delay(wait); // Pause for a moment
}
}
}
// Rainbow cycle along whole strip. Pass delay time (in ms) between frames.
void rainbow(int wait) {
// Hue of first pixel runs 5 complete loops through the color wheel.
// Color wheel has a range of 65536 but it's OK if we roll over, so
// just count from 0 to 5*65536. Adding 256 to firstPixelHue each time
// means we'll make 5*65536/256 = 1280 passes through this outer loop:
for(long firstPixelHue = 0; firstPixelHue < 5*65536; firstPixelHue += 256) {
for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
// Offset pixel hue by an amount to make one full revolution of the
// color wheel (range of 65536) along the length of the strip
// (strip.numPixels() steps):
int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());
// strip.ColorHSV() can take 1 or 3 arguments: a hue (0 to 65535) or
// optionally add saturation and value (brightness) (each 0 to 255).
// Here we're using just the single-argument hue variant. The result
// is passed through strip.gamma32() to provide 'truer' colors
// before assigning to each pixel:
strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue)));
}
strip.show(); // Update strip with new contents
delay(wait); // Pause for a moment
}
}
// Rainbow-enhanced theater marquee. Pass delay time (in ms) between frames.
void theaterChaseRainbow(int wait) {
int firstPixelHue = 0; // First pixel starts at red (hue 0)
for(int a=0; a<30; a++) { // Repeat 30 times...
for(int b=0; b<3; b++) { // 'b' counts from 0 to 2...
strip.clear(); // Set all pixels in RAM to 0 (off)
// 'c' counts up from 'b' to end of strip in increments of 3...
for(int c=b; c<strip.numPixels(); c += 3) {
// hue of pixel 'c' is offset by an amount to make one full
// revolution of the color wheel (range 65536) along the length
// of the strip (strip.numPixels() steps):
int hue = firstPixelHue + c * 65536L / strip.numPixels();
uint32_t color = strip.gamma32(strip.ColorHSV(hue)); // hue -> RGB
strip.setPixelColor(c, color); // Set pixel 'c' to value 'color'
}
strip.show(); // Update strip with new contents
delay(wait); // Pause for a moment
firstPixelHue += 65536 / 90; // One cycle of color wheel over 90 frames
}
}
}

View File

@ -0,0 +1,164 @@
// Simple demonstration on using an input device to trigger changes on your
// NeoPixels. Wire a momentary push button to connect from ground to a
// digital IO pin. When the button is pressed it will change to a new pixel
// animation. Initial state has all pixels off -- press the button once to
// start the first animation. As written, the button does not interrupt an
// animation in-progress, it works only when idle.
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h> // Required for 16 MHz Adafruit Trinket
#endif
// Digital IO pin connected to the button. This will be driven with a
// pull-up resistor so the switch pulls the pin to ground momentarily.
// On a high -> low transition the button press logic will execute.
#define BUTTON_PIN 2
#define PIXEL_PIN 6 // Digital IO pin connected to the NeoPixels.
#define PIXEL_COUNT 16 // Number of NeoPixels
// Declare our NeoPixel strip object:
Adafruit_NeoPixel strip(PIXEL_COUNT, PIXEL_PIN, NEO_GRB + NEO_KHZ800);
// Argument 1 = Number of pixels in NeoPixel strip
// Argument 2 = Arduino pin number (most are valid)
// Argument 3 = Pixel type flags, add together as needed:
// NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
// NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
// NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products)
// NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
// NEO_RGBW Pixels are wired for RGBW bitstream (NeoPixel RGBW products)
boolean oldState = HIGH;
int mode = 0; // Currently-active animation mode, 0-9
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP);
strip.begin(); // Initialize NeoPixel strip object (REQUIRED)
strip.show(); // Initialize all pixels to 'off'
}
void loop() {
// Get current button state.
boolean newState = digitalRead(BUTTON_PIN);
// Check if state changed from high to low (button press).
if((newState == LOW) && (oldState == HIGH)) {
// Short delay to debounce button.
delay(20);
// Check if button is still low after debounce.
newState = digitalRead(BUTTON_PIN);
if(newState == LOW) { // Yes, still low
if(++mode > 8) mode = 0; // Advance to next mode, wrap around after #8
switch(mode) { // Start the new animation...
case 0:
colorWipe(strip.Color( 0, 0, 0), 50); // Black/off
break;
case 1:
colorWipe(strip.Color(255, 0, 0), 50); // Red
break;
case 2:
colorWipe(strip.Color( 0, 255, 0), 50); // Green
break;
case 3:
colorWipe(strip.Color( 0, 0, 255), 50); // Blue
break;
case 4:
theaterChase(strip.Color(127, 127, 127), 50); // White
break;
case 5:
theaterChase(strip.Color(127, 0, 0), 50); // Red
break;
case 6:
theaterChase(strip.Color( 0, 0, 127), 50); // Blue
break;
case 7:
rainbow(10);
break;
case 8:
theaterChaseRainbow(50);
break;
}
}
}
// Set the last-read button state to the old state.
oldState = newState;
}
// Fill strip pixels one after another with a color. Strip is NOT cleared
// first; anything there will be covered pixel by pixel. Pass in color
// (as a single 'packed' 32-bit value, which you can get by calling
// strip.Color(red, green, blue) as shown in the loop() function above),
// and a delay time (in milliseconds) between pixels.
void colorWipe(uint32_t color, int wait) {
for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
strip.setPixelColor(i, color); // Set pixel's color (in RAM)
strip.show(); // Update strip to match
delay(wait); // Pause for a moment
}
}
// Theater-marquee-style chasing lights. Pass in a color (32-bit value,
// a la strip.Color(r,g,b) as mentioned above), and a delay time (in ms)
// between frames.
void theaterChase(uint32_t color, int wait) {
for(int a=0; a<10; a++) { // Repeat 10 times...
for(int b=0; b<3; b++) { // 'b' counts from 0 to 2...
strip.clear(); // Set all pixels in RAM to 0 (off)
// 'c' counts up from 'b' to end of strip in steps of 3...
for(int c=b; c<strip.numPixels(); c += 3) {
strip.setPixelColor(c, color); // Set pixel 'c' to value 'color'
}
strip.show(); // Update strip with new contents
delay(wait); // Pause for a moment
}
}
}
// Rainbow cycle along whole strip. Pass delay time (in ms) between frames.
void rainbow(int wait) {
// Hue of first pixel runs 3 complete loops through the color wheel.
// Color wheel has a range of 65536 but it's OK if we roll over, so
// just count from 0 to 3*65536. Adding 256 to firstPixelHue each time
// means we'll make 3*65536/256 = 768 passes through this outer loop:
for(long firstPixelHue = 0; firstPixelHue < 3*65536; firstPixelHue += 256) {
for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
// Offset pixel hue by an amount to make one full revolution of the
// color wheel (range of 65536) along the length of the strip
// (strip.numPixels() steps):
int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());
// strip.ColorHSV() can take 1 or 3 arguments: a hue (0 to 65535) or
// optionally add saturation and value (brightness) (each 0 to 255).
// Here we're using just the single-argument hue variant. The result
// is passed through strip.gamma32() to provide 'truer' colors
// before assigning to each pixel:
strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue)));
}
strip.show(); // Update strip with new contents
delay(wait); // Pause for a moment
}
}
// Rainbow-enhanced theater marquee. Pass delay time (in ms) between frames.
void theaterChaseRainbow(int wait) {
int firstPixelHue = 0; // First pixel starts at red (hue 0)
for(int a=0; a<30; a++) { // Repeat 30 times...
for(int b=0; b<3; b++) { // 'b' counts from 0 to 2...
strip.clear(); // Set all pixels in RAM to 0 (off)
// 'c' counts up from 'b' to end of strip in increments of 3...
for(int c=b; c<strip.numPixels(); c += 3) {
// hue of pixel 'c' is offset by an amount to make one full
// revolution of the color wheel (range 65536) along the length
// of the strip (strip.numPixels() steps):
int hue = firstPixelHue + c * 65536L / strip.numPixels();
uint32_t color = strip.gamma32(strip.ColorHSV(hue)); // hue -> RGB
strip.setPixelColor(c, color); // Set pixel 'c' to value 'color'
}
strip.show(); // Update strip with new contents
delay(wait); // Pause for a moment
firstPixelHue += 65536 / 90; // One cycle of color wheel over 90 frames
}
}
}

View File

@ -0,0 +1,50 @@
// NeoPixel Ring simple sketch (c) 2013 Shae Erisson
// Released under the GPLv3 license to match the rest of the
// Adafruit NeoPixel library
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h> // Required for 16 MHz Adafruit Trinket
#endif
// Which pin on the Arduino is connected to the NeoPixels?
#define PIN 6 // On Trinket or Gemma, suggest changing this to 1
// How many NeoPixels are attached to the Arduino?
#define NUMPIXELS 16 // Popular NeoPixel ring size
// When setting up the NeoPixel library, we tell it how many pixels,
// and which pin to use to send signals. Note that for older NeoPixel
// strips you might need to change the third parameter -- see the
// strandtest example for more information on possible values.
Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
#define DELAYVAL 500 // Time (in milliseconds) to pause between pixels
void setup() {
// These lines are specifically to support the Adafruit Trinket 5V 16 MHz.
// Any other board, you can remove this part (but no harm leaving it):
#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
clock_prescale_set(clock_div_1);
#endif
// END of Trinket-specific code.
pixels.begin(); // INITIALIZE NeoPixel strip object (REQUIRED)
}
void loop() {
pixels.clear(); // Set all pixel colors to 'off'
// The first NeoPixel in a strand is #0, second is 1, all the way up
// to the count of pixels minus one.
for(int i=0; i<NUMPIXELS; i++) { // For each pixel...
// pixels.Color() takes RGB values, from 0,0,0 up to 255,255,255
// Here we're using a moderately bright green color:
pixels.setPixelColor(i, pixels.Color(0, 150, 0));
pixels.show(); // Send the updated pixel colors to the hardware.
delay(DELAYVAL); // Pause before next pass through loop
}
}

View File

@ -0,0 +1,67 @@
// NeoPixel Ring simple sketch (c) 2013 Shae Erisson
// Released under the GPLv3 license to match the rest of the
// Adafruit NeoPixel library
// This sketch shows use of the "new" operator with Adafruit_NeoPixel.
// It's helpful if you don't know NeoPixel settings at compile time or
// just want to store this settings in EEPROM or a file on an SD card.
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h> // Required for 16 MHz Adafruit Trinket
#endif
// Which pin on the Arduino is connected to the NeoPixels?
int pin = 6; // On Trinket or Gemma, suggest changing this to 1
// How many NeoPixels are attached to the Arduino?
int numPixels = 16; // Popular NeoPixel ring size
// NeoPixel color format & data rate. See the strandtest example for
// information on possible values.
int pixelFormat = NEO_GRB + NEO_KHZ800;
// Rather than declaring the whole NeoPixel object here, we just create
// a pointer for one, which we'll then allocate later...
Adafruit_NeoPixel *pixels;
#define DELAYVAL 500 // Time (in milliseconds) to pause between pixels
void setup() {
// These lines are specifically to support the Adafruit Trinket 5V 16 MHz.
// Any other board, you can remove this part (but no harm leaving it):
#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
clock_prescale_set(clock_div_1);
#endif
// END of Trinket-specific code.
// Right about here is where we could read 'pin', 'numPixels' and/or
// 'pixelFormat' from EEPROM or a file on SD or whatever. This is a simple
// example and doesn't do that -- those variables are just set to fixed
// values at the top of this code -- but this is where it would happen.
// Then create a new NeoPixel object dynamically with these values:
pixels = new Adafruit_NeoPixel(numPixels, pin, pixelFormat);
// Going forward from here, code works almost identically to any other
// NeoPixel example, but instead of the dot operator on function calls
// (e.g. pixels.begin()), we instead use pointer indirection (->) like so:
pixels->begin(); // INITIALIZE NeoPixel strip object (REQUIRED)
// You'll see more of this in the loop() function below.
}
void loop() {
pixels->clear(); // Set all pixel colors to 'off'
// The first NeoPixel in a strand is #0, second is 1, all the way up
// to the count of pixels minus one.
for(int i=0; i<numPixels; i++) { // For each pixel...
// pixels->Color() takes RGB values, from 0,0,0 up to 255,255,255
// Here we're using a moderately bright green color:
pixels->setPixelColor(i, pixels->Color(0, 150, 0));
pixels->show(); // Send the updated pixel colors to the hardware.
delay(DELAYVAL); // Pause before next pass through loop
}
}

View File

@ -0,0 +1,147 @@
// A basic everyday NeoPixel strip test program.
// NEOPIXEL BEST PRACTICES for most reliable operation:
// - Add 1000 uF CAPACITOR between NeoPixel strip's + and - connections.
// - MINIMIZE WIRING LENGTH between microcontroller board and first pixel.
// - NeoPixel strip's DATA-IN should pass through a 300-500 OHM RESISTOR.
// - AVOID connecting NeoPixels on a LIVE CIRCUIT. If you must, ALWAYS
// connect GROUND (-) first, then +, then data.
// - When using a 3.3V microcontroller with a 5V-powered NeoPixel strip,
// a LOGIC-LEVEL CONVERTER on the data line is STRONGLY RECOMMENDED.
// (Skipping these may work OK on your workbench but can fail in the field)
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h> // Required for 16 MHz Adafruit Trinket
#endif
// Which pin on the Arduino is connected to the NeoPixels?
// On a Trinket or Gemma we suggest changing this to 1:
#define LED_PIN 6
// How many NeoPixels are attached to the Arduino?
#define LED_COUNT 60
// Declare our NeoPixel strip object:
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);
// Argument 1 = Number of pixels in NeoPixel strip
// Argument 2 = Arduino pin number (most are valid)
// Argument 3 = Pixel type flags, add together as needed:
// NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
// NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
// NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products)
// NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
// NEO_RGBW Pixels are wired for RGBW bitstream (NeoPixel RGBW products)
// setup() function -- runs once at startup --------------------------------
void setup() {
// These lines are specifically to support the Adafruit Trinket 5V 16 MHz.
// Any other board, you can remove this part (but no harm leaving it):
#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
clock_prescale_set(clock_div_1);
#endif
// END of Trinket-specific code.
strip.begin(); // INITIALIZE NeoPixel strip object (REQUIRED)
strip.show(); // Turn OFF all pixels ASAP
strip.setBrightness(50); // Set BRIGHTNESS to about 1/5 (max = 255)
}
// loop() function -- runs repeatedly as long as board is on ---------------
void loop() {
// Fill along the length of the strip in various colors...
colorWipe(strip.Color(255, 0, 0), 50); // Red
colorWipe(strip.Color( 0, 255, 0), 50); // Green
colorWipe(strip.Color( 0, 0, 255), 50); // Blue
// Do a theater marquee effect in various colors...
theaterChase(strip.Color(127, 127, 127), 50); // White, half brightness
theaterChase(strip.Color(127, 0, 0), 50); // Red, half brightness
theaterChase(strip.Color( 0, 0, 127), 50); // Blue, half brightness
rainbow(10); // Flowing rainbow cycle along the whole strip
theaterChaseRainbow(50); // Rainbow-enhanced theaterChase variant
}
// Some functions of our own for creating animated effects -----------------
// Fill strip pixels one after another with a color. Strip is NOT cleared
// first; anything there will be covered pixel by pixel. Pass in color
// (as a single 'packed' 32-bit value, which you can get by calling
// strip.Color(red, green, blue) as shown in the loop() function above),
// and a delay time (in milliseconds) between pixels.
void colorWipe(uint32_t color, int wait) {
for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
strip.setPixelColor(i, color); // Set pixel's color (in RAM)
strip.show(); // Update strip to match
delay(wait); // Pause for a moment
}
}
// Theater-marquee-style chasing lights. Pass in a color (32-bit value,
// a la strip.Color(r,g,b) as mentioned above), and a delay time (in ms)
// between frames.
void theaterChase(uint32_t color, int wait) {
for(int a=0; a<10; a++) { // Repeat 10 times...
for(int b=0; b<3; b++) { // 'b' counts from 0 to 2...
strip.clear(); // Set all pixels in RAM to 0 (off)
// 'c' counts up from 'b' to end of strip in steps of 3...
for(int c=b; c<strip.numPixels(); c += 3) {
strip.setPixelColor(c, color); // Set pixel 'c' to value 'color'
}
strip.show(); // Update strip with new contents
delay(wait); // Pause for a moment
}
}
}
// Rainbow cycle along whole strip. Pass delay time (in ms) between frames.
void rainbow(int wait) {
// Hue of first pixel runs 5 complete loops through the color wheel.
// Color wheel has a range of 65536 but it's OK if we roll over, so
// just count from 0 to 5*65536. Adding 256 to firstPixelHue each time
// means we'll make 5*65536/256 = 1280 passes through this outer loop:
for(long firstPixelHue = 0; firstPixelHue < 5*65536; firstPixelHue += 256) {
for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
// Offset pixel hue by an amount to make one full revolution of the
// color wheel (range of 65536) along the length of the strip
// (strip.numPixels() steps):
int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());
// strip.ColorHSV() can take 1 or 3 arguments: a hue (0 to 65535) or
// optionally add saturation and value (brightness) (each 0 to 255).
// Here we're using just the single-argument hue variant. The result
// is passed through strip.gamma32() to provide 'truer' colors
// before assigning to each pixel:
strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue)));
}
strip.show(); // Update strip with new contents
delay(wait); // Pause for a moment
}
}
// Rainbow-enhanced theater marquee. Pass delay time (in ms) between frames.
void theaterChaseRainbow(int wait) {
int firstPixelHue = 0; // First pixel starts at red (hue 0)
for(int a=0; a<30; a++) { // Repeat 30 times...
for(int b=0; b<3; b++) { // 'b' counts from 0 to 2...
strip.clear(); // Set all pixels in RAM to 0 (off)
// 'c' counts up from 'b' to end of strip in increments of 3...
for(int c=b; c<strip.numPixels(); c += 3) {
// hue of pixel 'c' is offset by an amount to make one full
// revolution of the color wheel (range 65536) along the length
// of the strip (strip.numPixels() steps):
int hue = firstPixelHue + c * 65536L / strip.numPixels();
uint32_t color = strip.gamma32(strip.ColorHSV(hue)); // hue -> RGB
strip.setPixelColor(c, color); // Set pixel 'c' to value 'color'
}
strip.show(); // Update strip with new contents
delay(wait); // Pause for a moment
firstPixelHue += 65536 / 90; // One cycle of color wheel over 90 frames
}
}
}

View File

@ -0,0 +1,134 @@
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
#define PIN 6
// Parameter 1 = number of pixels in strip
// Parameter 2 = Arduino pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
// NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
// NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
// NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products)
// NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
// NEO_RGBW Pixels are wired for RGBW bitstream (NeoPixel RGBW products)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, PIN, NEO_GRB + NEO_KHZ800);
// IMPORTANT: To reduce NeoPixel burnout risk, add 1000 uF capacitor across
// pixel power leads, add 300 - 500 Ohm resistor on first pixel's data input
// and minimize distance between Arduino and first pixel. Avoid connecting
// on a live circuit...if you must, connect GND first.
void setup() {
// This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
#if defined (__AVR_ATtiny85__)
if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
#endif
// End of trinket special code
strip.begin();
strip.setBrightness(50);
strip.show(); // Initialize all pixels to 'off'
}
void loop() {
// Some example procedures showing how to display to the pixels:
colorWipe(strip.Color(255, 0, 0), 50); // Red
colorWipe(strip.Color(0, 255, 0), 50); // Green
colorWipe(strip.Color(0, 0, 255), 50); // Blue
//colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW
// Send a theater pixel chase in...
theaterChase(strip.Color(127, 127, 127), 50); // White
theaterChase(strip.Color(127, 0, 0), 50); // Red
theaterChase(strip.Color(0, 0, 127), 50); // Blue
rainbow(20);
rainbowCycle(20);
theaterChaseRainbow(50);
}
// Fill the dots one after the other with a color
void colorWipe(uint32_t c, uint8_t wait) {
for(uint16_t i=0; i<strip.numPixels(); i++) {
strip.setPixelColor(i, c);
strip.show();
delay(wait);
}
}
void rainbow(uint8_t wait) {
uint16_t i, j;
for(j=0; j<256; j++) {
for(i=0; i<strip.numPixels(); i++) {
strip.setPixelColor(i, Wheel((i+j) & 255));
}
strip.show();
delay(wait);
}
}
// Slightly different, this makes the rainbow equally distributed throughout
void rainbowCycle(uint8_t wait) {
uint16_t i, j;
for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
for(i=0; i< strip.numPixels(); i++) {
strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
}
strip.show();
delay(wait);
}
}
//Theatre-style crawling lights.
void theaterChase(uint32_t c, uint8_t wait) {
for (int j=0; j<10; j++) { //do 10 cycles of chasing
for (int q=0; q < 3; q++) {
for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
strip.setPixelColor(i+q, c); //turn every third pixel on
}
strip.show();
delay(wait);
for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
strip.setPixelColor(i+q, 0); //turn every third pixel off
}
}
}
}
//Theatre-style crawling lights with rainbow effect
void theaterChaseRainbow(uint8_t wait) {
for (int j=0; j < 256; j++) { // cycle all 256 colors in the wheel
for (int q=0; q < 3; q++) {
for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
strip.setPixelColor(i+q, Wheel( (i+j) % 255)); //turn every third pixel on
}
strip.show();
delay(wait);
for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
strip.setPixelColor(i+q, 0); //turn every third pixel off
}
}
}
}
// Input a value 0 to 255 to get a color value.
// The colours are a transition r - g - b - back to r.
uint32_t Wheel(byte WheelPos) {
WheelPos = 255 - WheelPos;
if(WheelPos < 85) {
return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
}
if(WheelPos < 170) {
WheelPos -= 85;
return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
}
WheelPos -= 170;
return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}

View File

@ -0,0 +1,72 @@
#######################################
# Syntax Coloring Map For Adafruit_NeoPixel
#######################################
# Class
#######################################
Adafruit_NeoPixel KEYWORD1
#######################################
# Methods and Functions
#######################################
begin KEYWORD2
show KEYWORD2
setPin KEYWORD2
setPixelColor KEYWORD2
fill KEYWORD2
setBrightness KEYWORD2
clear KEYWORD2
updateLength KEYWORD2
updateType KEYWORD2
canShow KEYWORD2
getPixels KEYWORD2
getBrightness KEYWORD2
getPin KEYWORD2
numPixels KEYWORD2
getPixelColor KEYWORD2
sine8 KEYWORD2
gamma8 KEYWORD2
Color KEYWORD2
ColorHSV KEYWORD2
gamma32 KEYWORD2
#######################################
# Constants
#######################################
NEO_COLMASK LITERAL1
NEO_SPDMASK LITERAL1
NEO_KHZ800 LITERAL1
NEO_KHZ400 LITERAL1
NEO_RGB LITERAL1
NEO_RBG LITERAL1
NEO_GRB LITERAL1
NEO_GBR LITERAL1
NEO_BRG LITERAL1
NEO_BGR LITERAL1
NEO_WRGB LITERAL1
NEO_WRBG LITERAL1
NEO_WGRB LITERAL1
NEO_WGBR LITERAL1
NEO_WBRG LITERAL1
NEO_WBGR LITERAL1
NEO_RWGB LITERAL1
NEO_RWBG LITERAL1
NEO_RGWB LITERAL1
NEO_RGBW LITERAL1
NEO_RBWG LITERAL1
NEO_RBGW LITERAL1
NEO_GWRB LITERAL1
NEO_GWBR LITERAL1
NEO_GRWB LITERAL1
NEO_GRBW LITERAL1
NEO_GBWR LITERAL1
NEO_GBRW LITERAL1
NEO_BWRG LITERAL1
NEO_BWGR LITERAL1
NEO_BRWG LITERAL1
NEO_BRGW LITERAL1
NEO_BGWR LITERAL1
NEO_BGRW LITERAL1

View File

@ -0,0 +1,9 @@
name=Adafruit NeoPixel
version=1.5.0
author=Adafruit
maintainer=Adafruit <info@adafruit.com>
sentence=Arduino library for controlling single-wire-based LED pixels and strip.
paragraph=Arduino library for controlling single-wire-based LED pixels and strip.
category=Display
url=https://github.com/adafruit/Adafruit_NeoPixel
architectures=*

View File

@ -0,0 +1,46 @@
Thank you for opening an issue on an Adafruit Arduino library repository. To
improve the speed of resolution please review the following guidelines and
common troubleshooting steps below before creating the issue:
- **Do not use GitHub issues for troubleshooting projects and issues.** Instead use
the forums at http://forums.adafruit.com to ask questions and troubleshoot why
something isn't working as expected. In many cases the problem is a common issue
that you will more quickly receive help from the forum community. GitHub issues
are meant for known defects in the code. If you don't know if there is a defect
in the code then start with troubleshooting on the forum first.
- **If following a tutorial or guide be sure you didn't miss a step.** Carefully
check all of the steps and commands to run have been followed. Consult the
forum if you're unsure or have questions about steps in a guide/tutorial.
- **For Arduino projects check these very common issues to ensure they don't apply**:
- For uploading sketches or communicating with the board make sure you're using
a **USB data cable** and **not** a **USB charge-only cable**. It is sometimes
very hard to tell the difference between a data and charge cable! Try using the
cable with other devices or swapping to another cable to confirm it is not
the problem.
- **Be sure you are supplying adequate power to the board.** Check the specs of
your board and plug in an external power supply. In many cases just
plugging a board into your computer is not enough to power it and other
peripherals.
- **Double check all soldering joints and connections.** Flakey connections
cause many mysterious problems. See the [guide to excellent soldering](https://learn.adafruit.com/adafruit-guide-excellent-soldering/tools) for examples of good solder joints.
- **Ensure you are using an official Arduino or Adafruit board.** We can't
guarantee a clone board will have the same functionality and work as expected
with this code and don't support them.
If you're sure this issue is a defect in the code and checked the steps above
please fill in the following fields to provide enough troubleshooting information.
You may delete the guideline and text above to just leave the following details:
- Arduino board: **INSERT ARDUINO BOARD NAME/TYPE HERE**
- Arduino IDE version (found in Arduino -> About Arduino menu): **INSERT ARDUINO
VERSION HERE**
- List the steps to reproduce the problem below (if possible attach a sketch or
copy the sketch code in too): **LIST REPRO STEPS BELOW**

View File

@ -0,0 +1,26 @@
Thank you for creating a pull request to contribute to Adafruit's GitHub code!
Before you open the request please review the following guidelines and tips to
help it be more easily integrated:
- **Describe the scope of your change--i.e. what the change does and what parts
of the code were modified.** This will help us understand any risks of integrating
the code.
- **Describe any known limitations with your change.** For example if the change
doesn't apply to a supported platform of the library please mention it.
- **Please run any tests or examples that can exercise your modified code.** We
strive to not break users of the code and running tests/examples helps with this
process.
Thank you again for contributing! We will try to test and integrate the change
as soon as we can, but be aware we have many GitHub repositories to manage and
can't immediately respond to every request. There is no need to bump or check in
on a pull request (it will clutter the discussion of the request).
Also don't be worried if the request is closed or not integrated--sometimes the
priorities of Adafruit's GitHub code (education, ease of use) might not match the
priorities of the pull request. Don't fret, the open source community thrives on
forks and GitHub makes it easy to keep your changes in a forked repo.
After reviewing the guidelines above you can delete this text from the pull request.

View File

@ -0,0 +1,29 @@
language: c
sudo: false
cache:
directories:
- ~/arduino_ide
- ~/.arduino15/packages/
git:
depth: false
quiet: true
env:
global:
- ARDUINO_IDE_VERSION="1.8.7"
- PRETTYNAME="Adafruit SHT31-D Library"
# Optional, will default to "$TRAVIS_BUILD_DIR/Doxyfile"
# - DOXYFILE: $TRAVIS_BUILD_DIR/Doxyfile
before_install:
- source <(curl -SLs https://raw.githubusercontent.com/adafruit/travis-ci-arduino/master/install.sh)
install:
- true
script:
- build_main_platforms
# Generate and deploy documentation
after_success:
- source <(curl -SLs https://raw.githubusercontent.com/adafruit/travis-ci-arduino/master/library_check.sh)
- source <(curl -SLs https://raw.githubusercontent.com/adafruit/travis-ci-arduino/master/doxy_gen_and_deploy.sh)

View File

@ -0,0 +1,144 @@
/***************************************************
This is a library for the SHT31 Digital Humidity & Temp Sensor
Designed specifically to work with the SHT31 Digital sensor from Adafruit
----> https://www.adafruit.com/products/2857
These sensors use I2C to communicate, 2 pins are required to interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
****************************************************/
#include "Adafruit_SHT31.h"
Adafruit_SHT31::Adafruit_SHT31() {
_i2caddr = NULL;
humidity = 0.0f;
temp = 0.0f;
}
boolean Adafruit_SHT31::begin(uint8_t i2caddr) {
Wire.begin();
_i2caddr = i2caddr;
reset();
// return (readStatus() == 0x40);
return true;
}
uint16_t Adafruit_SHT31::readStatus(void) {
writeCommand(SHT31_READSTATUS);
Wire.requestFrom(_i2caddr, (uint8_t)3);
uint16_t stat = Wire.read();
stat <<= 8;
stat |= Wire.read();
// Serial.println(stat, HEX);
return stat;
}
void Adafruit_SHT31::reset(void) {
writeCommand(SHT31_SOFTRESET);
delay(10);
}
void Adafruit_SHT31::heater(boolean h) {
if (h)
writeCommand(SHT31_HEATEREN);
else
writeCommand(SHT31_HEATERDIS);
}
float Adafruit_SHT31::readTemperature(void) {
if (!readTempHum())
return NAN;
return temp;
}
float Adafruit_SHT31::readHumidity(void) {
if (!readTempHum())
return NAN;
return humidity;
}
boolean Adafruit_SHT31::readTempHum(void) {
uint8_t readbuffer[6];
writeCommand(SHT31_MEAS_HIGHREP);
delay(20);
Wire.requestFrom(_i2caddr, (uint8_t)6);
if (Wire.available() != 6)
return false;
for (uint8_t i = 0; i < 6; i++) {
readbuffer[i] = Wire.read();
// Serial.print("0x"); Serial.println(readbuffer[i], HEX);
}
uint16_t ST, SRH;
ST = readbuffer[0];
ST <<= 8;
ST |= readbuffer[1];
if (readbuffer[2] != crc8(readbuffer, 2))
return false;
SRH = readbuffer[3];
SRH <<= 8;
SRH |= readbuffer[4];
if (readbuffer[5] != crc8(readbuffer + 3, 2))
return false;
// Serial.print("ST = "); Serial.println(ST);
double stemp = ST;
stemp *= 175;
stemp /= 0xffff;
stemp = -45 + stemp;
temp = stemp;
// Serial.print("SRH = "); Serial.println(SRH);
double shum = SRH;
shum *= 100;
shum /= 0xFFFF;
humidity = shum;
return true;
}
void Adafruit_SHT31::writeCommand(uint16_t cmd) {
Wire.beginTransmission(_i2caddr);
Wire.write(cmd >> 8);
Wire.write(cmd & 0xFF);
Wire.endTransmission();
}
uint8_t Adafruit_SHT31::crc8(const uint8_t *data, int len) {
/*
*
* CRC-8 formula from page 14 of SHT spec pdf
*
* Test data 0xBE, 0xEF should yield 0x92
*
* Initialization data 0xFF
* Polynomial 0x31 (x8 + x5 +x4 +1)
* Final XOR 0x00
*/
const uint8_t POLYNOMIAL(0x31);
uint8_t crc(0xFF);
for (int j = len; j; --j) {
crc ^= *data++;
for (int i = 8; i; --i) {
crc = (crc & 0x80) ? (crc << 1) ^ POLYNOMIAL : (crc << 1);
}
}
return crc;
}

View File

@ -0,0 +1,135 @@
/***************************************************
This is a library for the SHT31 Digital Humidity & Temp Sensor
Designed specifically to work with the SHT31 Digital sensor from Adafruit
----> https://www.adafruit.com/products/2857
These sensors use I2C to communicate, 2 pins are required to interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
****************************************************/
#ifndef ADAFRUIT_SHT31_H
#define ADAFRUIT_SHT31_H
#include "Arduino.h"
#include "Wire.h"
#define SHT31_DEFAULT_ADDR 0x44
#define SHT31_MEAS_HIGHREP_STRETCH 0x2C06
#define SHT31_MEAS_MEDREP_STRETCH 0x2C0D
#define SHT31_MEAS_LOWREP_STRETCH 0x2C10
#define SHT31_MEAS_HIGHREP 0x2400
#define SHT31_MEAS_MEDREP 0x240B
#define SHT31_MEAS_LOWREP 0x2416
#define SHT31_READSTATUS 0xF32D
#define SHT31_CLEARSTATUS 0x3041
#define SHT31_SOFTRESET 0x30A2
#define SHT31_HEATEREN 0x306D
#define SHT31_HEATERDIS 0x3066
/**
* Driver for the Adafruit SHT31-D Temperature and Humidity breakout board.
*/
class Adafruit_SHT31 {
public:
/**
* Constructor.
*/
Adafruit_SHT31();
/**
* Initialises the I2C bus, and assigns the I2C address to us.
*
* @param i2caddr The I2C address to use for the sensor.
*
* @return True if initialisation was successful, otherwise False.
*/
boolean begin(uint8_t i2caddr = SHT31_DEFAULT_ADDR);
/**
* Gets a single temperature reading from the sensor.
*
* @return A float value indicating the temperature.
*/
float readTemperature(void);
/**
* Gets a single relative humidity reading from the sensor.
*
* @return A float value representing relative humidity.
*/
float readHumidity(void);
/**
* Gets the current status register contents.
*
* @return The 16-bit status register.
*/
uint16_t readStatus(void);
/**
* Performs a reset of the sensor to put it into a known state.
*/
void reset(void);
/**
* Enables or disabled the heating element.
*
* @param h True to enable the heater, False to disable it.
*/
void heater(boolean h);
/**
* Performs a CRC8 calculation on the supplied values.
*
* @param data Pointer to the data to use when calculating the CRC8.
* @param len The number of bytes in 'data'.
*
* @return The computed CRC8 value.
*/
uint8_t crc8(const uint8_t *data, int len);
private:
/**
* Placeholder to track the I2C address.
*/
uint8_t _i2caddr;
/**
* Placeholder to track humidity internally.
*/
float humidity;
/**
* Placeholder to track temperature internally.
*/
float temp;
/**
* Internal function to perform a temp + humidity read.
*
* @return True if successful, otherwise false.
*/
boolean readTempHum(void);
/**
* Internal function to perform and I2C write.
*
* @param cmd The 16-bit command ID to send.
*/
void writeCommand(uint16_t cmd);
/**
* Internal function to read data over the I2C bus.
*
* @return True if successful, otherwise False.
*/
boolean readData(void);
};
#endif

View File

@ -0,0 +1,58 @@
# Adafruit SHT31-D Temperature and Humidity Sensor Breakout [![Build Status](https://travis-ci.org/adafruit/Adafruit_SHT31.svg?branch=master)](https://travis-ci.org/adafruit/Adafruit_SHT31)
![Adafruit SHT31](https://cdn-learn.adafruit.com/assets/assets/000/028/970/small360/adafruit_products_2857_iso_ORIG.jpg?1449606376)
This is a library for the SHT31 Digital Humidity + Temp sensor.
It is designed specifically to work with the SHT31 Digital in the Adafruit shop:
- https://www.adafruit.com/products/2857
These sensors use **I2C** to communicate, 2 pins are required to interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
Check out the links above for our tutorials and wiring diagrams
## Installation
Use the Arduino Library Manager to install this library. If you're unfamiliar
with how this works, we have a great tutorial on Arduino library installation
at: http://learn.adafruit.com/adafruit-all-about-arduino-libraries-install-use
<!-- START COMPATIBILITY TABLE -->
## Compatibility
MCU | Tested Works | Doesn't Work | Not Tested | Notes
------------------ | :----------: | :----------: | :---------: | -----
Atmega328 @ 16MHz | X | | |
Atmega328 @ 12MHz | X | | |
Atmega32u4 @ 16MHz | X | | |
Atmega32u4 @ 8MHz | X | | |
ESP8266 | X | | |
Atmega2560 @ 16MHz | X | | |
ATSAM3X8E | X | | |
ATSAM21D | X | | |
ATtiny85 @ 16MHz | X | | |
ATtiny85 @ 8MHz | X | | |
Intel Curie @ 32MHz | | | X |
STM32F2 | | | X |
* ATmega328 @ 16MHz : Arduino UNO, Adafruit Pro Trinket 5V, Adafruit Metro 328, Adafruit Metro Mini
* ATmega328 @ 12MHz : Adafruit Pro Trinket 3V
* ATmega32u4 @ 16MHz : Arduino Leonardo, Arduino Micro, Arduino Yun, Teensy 2.0
* ATmega32u4 @ 8MHz : Adafruit Flora, Bluefruit Micro
* ESP8266 : Adafruit Huzzah
* ATmega2560 @ 16MHz : Arduino Mega
* ATSAM3X8E : Arduino Due
* ATSAM21D : Arduino Zero, M0 Pro
* ATtiny85 @ 16MHz : Adafruit Trinket 5V
* ATtiny85 @ 8MHz : Adafruit Gemma, Arduino Gemma, Adafruit Trinket 3V
<!-- END COMPATIBILITY TABLE -->

View File

@ -0,0 +1,48 @@
/***************************************************
This is an example for the SHT31-D Humidity & Temp Sensor
Designed specifically to work with the SHT31-D sensor from Adafruit
----> https://www.adafruit.com/products/2857
These sensors use I2C to communicate, 2 pins are required to
interface
****************************************************/
#include <Arduino.h>
#include <Wire.h>
#include "Adafruit_SHT31.h"
Adafruit_SHT31 sht31 = Adafruit_SHT31();
void setup() {
Serial.begin(9600);
while (!Serial)
delay(10); // will pause Zero, Leonardo, etc until serial console opens
Serial.println("SHT31 test");
if (! sht31.begin(0x44)) { // Set to 0x45 for alternate i2c addr
Serial.println("Couldn't find SHT31");
while (1) delay(1);
}
}
void loop() {
float t = sht31.readTemperature();
float h = sht31.readHumidity();
if (! isnan(t)) { // check if 'is not a number'
Serial.print("Temp *C = "); Serial.println(t);
} else {
Serial.println("Failed to read temperature");
}
if (! isnan(h)) { // check if 'is not a number'
Serial.print("Hum. % = "); Serial.println(h);
} else {
Serial.println("Failed to read humidity");
}
Serial.println();
delay(1000);
}

View File

@ -0,0 +1,9 @@
name=Adafruit SHT31 Library
version=1.1.0
author=Adafruit
maintainer=Adafruit <info@adafruit.com>
sentence=Arduino library for SHT31 temperature & humidity sensor.
paragraph=Arduino library for SHT31 temperature & humidity sensor.
category=Sensors
url=https://github.com/adafruit/Adafruit_SHT31
architectures=*

View File

@ -0,0 +1,173 @@
/**************************************************************************/
/*!
@file Adafruit_Si7021.cpp
@author Limor Fried (Adafruit Industries)
@license BSD (see license.txt)
This is a library for the Adafruit Si7021 breakout board
----> https://www.adafruit.com/products/3251
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
@section HISTORY
v1.0 - First release
*/
/**************************************************************************/
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include <Wire.h>
#include <Adafruit_Si7021.h>
/**************************************************************************/
Adafruit_Si7021::Adafruit_Si7021(void) {
_i2caddr = SI7021_DEFAULT_ADDRESS;
sernum_a = sernum_b = 0;
}
bool Adafruit_Si7021::begin(void) {
Wire.begin();
reset();
if (readRegister8(SI7021_READRHT_REG_CMD) != 0x3A) return false;
readSerialNumber();
//Serial.println(sernum_a, HEX);
//Serial.println(sernum_b, HEX);
return true;
}
float Adafruit_Si7021::readHumidity(void) {
Wire.beginTransmission(_i2caddr);
Wire.write((uint8_t)SI7021_MEASRH_NOHOLD_CMD);
Wire.endTransmission(false);
delay(25);
Wire.requestFrom(_i2caddr, 3);
uint16_t hum = Wire.read();
hum <<= 8;
hum |= Wire.read();
uint8_t chxsum = Wire.read();
float humidity = hum;
humidity *= 125;
humidity /= 65536;
humidity -= 6;
return humidity;
}
float Adafruit_Si7021::readTemperature(void) {
Wire.beginTransmission(_i2caddr);
Wire.write((uint8_t)SI7021_MEASTEMP_NOHOLD_CMD);
Wire.endTransmission(false);
delay(25);
Wire.requestFrom(_i2caddr, 3);
uint16_t temp = Wire.read();
temp <<= 8;
temp |= Wire.read();
uint8_t chxsum = Wire.read();
float temperature = temp;
temperature *= 175.72;
temperature /= 65536;
temperature -= 46.85;
return temperature;
}
void Adafruit_Si7021::reset(void) {
Wire.beginTransmission(_i2caddr);
Wire.write((uint8_t)SI7021_RESET_CMD);
Wire.endTransmission();
delay(50);
}
void Adafruit_Si7021::readSerialNumber(void) {
Wire.beginTransmission(_i2caddr);
Wire.write((uint8_t)(SI7021_ID1_CMD>>8));
Wire.write((uint8_t)(SI7021_ID1_CMD&0xFF));
Wire.endTransmission();
Wire.requestFrom(_i2caddr, 8);
sernum_a = Wire.read();
Wire.read();
sernum_a <<= 8;
sernum_a |= Wire.read();
Wire.read();
sernum_a <<= 8;
sernum_a |= Wire.read();
Wire.read();
sernum_a <<= 8;
sernum_a |= Wire.read();
Wire.read();
Wire.beginTransmission(_i2caddr);
Wire.write((uint8_t)(SI7021_ID2_CMD>>8));
Wire.write((uint8_t)(SI7021_ID2_CMD&0xFF));
Wire.endTransmission();
Wire.requestFrom(_i2caddr, 8);
sernum_b = Wire.read();
Wire.read();
sernum_b <<= 8;
sernum_b |= Wire.read();
Wire.read();
sernum_b <<= 8;
sernum_b |= Wire.read();
Wire.read();
sernum_b <<= 8;
sernum_b |= Wire.read();
Wire.read();
}
/*******************************************************************/
void Adafruit_Si7021::writeRegister8(uint8_t reg, uint8_t value) {
Wire.beginTransmission(_i2caddr);
Wire.write((uint8_t)reg);
Wire.write((uint8_t)value);
Wire.endTransmission();
//Serial.print("Wrote $"); Serial.print(reg, HEX); Serial.print(": 0x"); Serial.println(value, HEX);
}
uint8_t Adafruit_Si7021::readRegister8(uint8_t reg) {
uint8_t value;
Wire.beginTransmission(_i2caddr);
Wire.write((uint8_t)reg);
Wire.endTransmission(false);
Wire.requestFrom(_i2caddr, 1);
value = Wire.read();
//Serial.print("Read $"); Serial.print(reg, HEX); Serial.print(": 0x"); Serial.println(value, HEX);
return value;
}
uint16_t Adafruit_Si7021::readRegister16(uint8_t reg) {
uint16_t value;
Wire.beginTransmission(_i2caddr);
Wire.write((uint8_t)reg);
Wire.endTransmission();
Wire.requestFrom(_i2caddr, 2);
value = Wire.read();
value <<= 8;
value |= Wire.read();
//Serial.print("Read $"); Serial.print(reg, HEX); Serial.print(": 0x"); Serial.println(value, HEX);
return value;
}

View File

@ -0,0 +1,74 @@
/**************************************************************************/
/*!
@file Adafruit_Si7021.h
@author Limor Fried (Adafruit Industries)
@license BSD (see license.txt)
This is a library for the Adafruit Si7021 breakout board
----> https://www.adafruit.com/products/3251
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
@section HISTORY
v1.0 - First release
*/
/**************************************************************************/
#ifndef __Si7021_H__
#define __Si7021_H__
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
/*=========================================================================
I2C ADDRESS/BITS
-----------------------------------------------------------------------*/
#define SI7021_DEFAULT_ADDRESS (0x40)
#define SI7021_MEASRH_HOLD_CMD 0xE5
#define SI7021_MEASRH_NOHOLD_CMD 0xF5
#define SI7021_MEASTEMP_HOLD_CMD 0xE3
#define SI7021_MEASTEMP_NOHOLD_CMD 0xF3
#define SI7021_READPREVTEMP_CMD 0xE0
#define SI7021_RESET_CMD 0xFE
#define SI7021_WRITERHT_REG_CMD 0xE6
#define SI7021_READRHT_REG_CMD 0xE7
#define SI7021_WRITEHEATER_REG_CMD 0x51
#define SI7021_READHEATER_REG_CMD 0x11
#define SI7021_ID1_CMD 0xFA0F
#define SI7021_ID2_CMD 0xFCC9
#define SI7021_FIRMVERS_CMD 0x84B8
/*=========================================================================*/
class Adafruit_Si7021 {
public:
Adafruit_Si7021(void);
bool begin(void);
float readTemperature(void);
void reset(void);
void readSerialNumber(void);
float readHumidity(void);
uint32_t sernum_a, sernum_b;
private:
uint8_t readRegister8(uint8_t reg);
uint16_t readRegister16(uint8_t reg);
void writeRegister8(uint8_t reg, uint8_t value);
int8_t _i2caddr;
};
/**************************************************************************/
#endif // __Si7021_H__

View File

@ -0,0 +1,23 @@
Adafruit Si7021
===============
Driver for Adafruit's Si7021 humidity / temp sensor breakout
Designed specifically to work with the Si7021 breakout in the adafruit shop
* https://www.adafruit.com/products/3251
This chip uses I2C to communicate, 2 pins are required to interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Check out the links above for our tutorials and wiring diagrams
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
To download. click the ZIP button on the right, rename the uncompressed folder Adafruit_Si7021. Check that the Adafruit_Si7021 folder contains Adafruit_Si7021.cpp and Adafruit_Si7021.h
Place the Adafruit_Si7021 library folder your arduinosketchfolder/libraries/ folder. You may need to create the libraries subfolder if its your first library. Restart the IDE.

View File

@ -0,0 +1,25 @@
#include "Adafruit_Si7021.h"
Adafruit_Si7021 sensor = Adafruit_Si7021();
void setup() {
Serial.begin(115200);
// wait for serial port to open
while (!Serial) {
delay(10);
}
Serial.println("Si7021 test!");
if (!sensor.begin()) {
Serial.println("Did not find Si7021 sensor!");
while (true);
}
}
void loop() {
Serial.print("Humidity: "); Serial.print(sensor.readHumidity(), 2);
Serial.print("\tTemperature: "); Serial.println(sensor.readTemperature(), 2);
delay(1000);
}

View File

@ -0,0 +1,9 @@
name=Adafruit Si7021 Library
version=1.0.1
author=Adafruit
maintainer=Adafruit <info@adafruit.com>
sentence=Arduino library for Si7021 sensors.
paragraph=Arduino library for Si7021 temperature + humidity sensors.
category=Sensors
url=https://github.com/adafruit/Adafruit_Si7021
architectures=*

View File

@ -0,0 +1,601 @@
/*!
* @file Adafruit_TCS34725.cpp
*
* @mainpage Driver for the TCS34725 digital color sensors.
*
* @section intro_sec Introduction
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit and open-source hardware by purchasing
* products from Adafruit!
*
* @section author Author
*
* KTOWN (Adafruit Industries)
*
* @section license License
*
* BSD (see license.txt)
*
* @section HISTORY
*
* v1.0 - First release
*/
#ifdef __AVR
#include <avr/pgmspace.h>
#elif defined(ESP8266)
#include <pgmspace.h>
#endif
#include <math.h>
#include <stdlib.h>
#include "Adafruit_TCS34725.h"
/*!
* @brief Implements missing powf function
* @param x
* Base number
* @param y
* Exponent
* @return x raised to the power of y
*/
float powf(const float x, const float y) {
return (float)(pow((double)x, (double)y));
}
/*!
* @brief Writes a register and an 8 bit value over I2C
* @param reg
* @param value
*/
void Adafruit_TCS34725::write8(uint8_t reg, uint32_t value) {
_wire->beginTransmission(_i2caddr);
#if ARDUINO >= 100
_wire->write(TCS34725_COMMAND_BIT | reg);
_wire->write(value & 0xFF);
#else
_wire->send(TCS34725_COMMAND_BIT | reg);
_wire->send(value & 0xFF);
#endif
_wire->endTransmission();
}
/*!
* @brief Reads an 8 bit value over I2C
* @param reg
* @return value
*/
uint8_t Adafruit_TCS34725::read8(uint8_t reg) {
_wire->beginTransmission(_i2caddr);
#if ARDUINO >= 100
_wire->write(TCS34725_COMMAND_BIT | reg);
#else
_wire->send(TCS34725_COMMAND_BIT | reg);
#endif
_wire->endTransmission();
_wire->requestFrom(_i2caddr, 1);
#if ARDUINO >= 100
return _wire->read();
#else
return _wire->receive();
#endif
}
/*!
* @brief Reads a 16 bit values over I2C
* @param reg
* @return value
*/
uint16_t Adafruit_TCS34725::read16(uint8_t reg) {
uint16_t x;
uint16_t t;
_wire->beginTransmission(_i2caddr);
#if ARDUINO >= 100
_wire->write(TCS34725_COMMAND_BIT | reg);
#else
_wire->send(TCS34725_COMMAND_BIT | reg);
#endif
_wire->endTransmission();
_wire->requestFrom(_i2caddr, 2);
#if ARDUINO >= 100
t = _wire->read();
x = _wire->read();
#else
t = _wire->receive();
x = _wire->receive();
#endif
x <<= 8;
x |= t;
return x;
}
/*!
* @brief Enables the device
*/
void Adafruit_TCS34725::enable() {
write8(TCS34725_ENABLE, TCS34725_ENABLE_PON);
delay(3);
write8(TCS34725_ENABLE, TCS34725_ENABLE_PON | TCS34725_ENABLE_AEN);
/* Set a delay for the integration time.
This is only necessary in the case where enabling and then
immediately trying to read values back. This is because setting
AEN triggers an automatic integration, so if a read RGBC is
performed too quickly, the data is not yet valid and all 0's are
returned */
switch (_tcs34725IntegrationTime) {
case TCS34725_INTEGRATIONTIME_2_4MS:
delay(3);
break;
case TCS34725_INTEGRATIONTIME_24MS:
delay(24);
break;
case TCS34725_INTEGRATIONTIME_50MS:
delay(50);
break;
case TCS34725_INTEGRATIONTIME_101MS:
delay(101);
break;
case TCS34725_INTEGRATIONTIME_154MS:
delay(154);
break;
case TCS34725_INTEGRATIONTIME_700MS:
delay(700);
break;
}
}
/*!
* @brief Disables the device (putting it in lower power sleep mode)
*/
void Adafruit_TCS34725::disable() {
/* Turn the device off to save power */
uint8_t reg = 0;
reg = read8(TCS34725_ENABLE);
write8(TCS34725_ENABLE, reg & ~(TCS34725_ENABLE_PON | TCS34725_ENABLE_AEN));
}
/*!
* @brief Constructor
* @param it
* Integration Time
* @param gain
* Gain
*/
Adafruit_TCS34725::Adafruit_TCS34725(tcs34725IntegrationTime_t it,
tcs34725Gain_t gain) {
_tcs34725Initialised = false;
_tcs34725IntegrationTime = it;
_tcs34725Gain = gain;
}
/*!
* @brief Initializes I2C and configures the sensor
* @param addr
* i2c address
* @return True if initialization was successful, otherwise false.
*/
boolean Adafruit_TCS34725::begin(uint8_t addr) {
_i2caddr = addr;
_wire = &Wire;
return init();
}
/*!
* @brief Initializes I2C and configures the sensor
* @param addr
* i2c address
* @param *theWire
* The Wire object
* @return True if initialization was successful, otherwise false.
*/
boolean Adafruit_TCS34725::begin(uint8_t addr, TwoWire *theWire) {
_i2caddr = addr;
_wire = theWire;
return init();
}
/*!
* @brief Initializes I2C and configures the sensor
* @return True if initialization was successful, otherwise false.
*/
boolean Adafruit_TCS34725::begin() {
_i2caddr = TCS34725_ADDRESS;
_wire = &Wire;
return init();
}
/*!
* @brief Part of begin
* @return True if initialization was successful, otherwise false.
*/
boolean Adafruit_TCS34725::init() {
_wire->begin();
/* Make sure we're actually connected */
uint8_t x = read8(TCS34725_ID);
if ((x != 0x44) && (x != 0x10)) {
return false;
}
_tcs34725Initialised = true;
/* Set default integration time and gain */
setIntegrationTime(_tcs34725IntegrationTime);
setGain(_tcs34725Gain);
/* Note: by default, the device is in power down mode on bootup */
enable();
return true;
}
/*!
* @brief Sets the integration time for the TC34725
* @param it
* Integration Time
*/
void Adafruit_TCS34725::setIntegrationTime(tcs34725IntegrationTime_t it) {
if (!_tcs34725Initialised)
begin();
/* Update the timing register */
write8(TCS34725_ATIME, it);
/* Update value placeholders */
_tcs34725IntegrationTime = it;
}
/*!
* @brief Adjusts the gain on the TCS34725
* @param gain
* Gain (sensitivity to light)
*/
void Adafruit_TCS34725::setGain(tcs34725Gain_t gain) {
if (!_tcs34725Initialised)
begin();
/* Update the timing register */
write8(TCS34725_CONTROL, gain);
/* Update value placeholders */
_tcs34725Gain = gain;
}
/*!
* @brief Reads the raw red, green, blue and clear channel values
* @param *r
* Red value
* @param *g
* Green value
* @param *b
* Blue value
* @param *c
* Clear channel value
*/
void Adafruit_TCS34725::getRawData(uint16_t *r, uint16_t *g, uint16_t *b,
uint16_t *c) {
if (!_tcs34725Initialised)
begin();
*c = read16(TCS34725_CDATAL);
*r = read16(TCS34725_RDATAL);
*g = read16(TCS34725_GDATAL);
*b = read16(TCS34725_BDATAL);
/* Set a delay for the integration time */
switch (_tcs34725IntegrationTime) {
case TCS34725_INTEGRATIONTIME_2_4MS:
delay(3);
break;
case TCS34725_INTEGRATIONTIME_24MS:
delay(24);
break;
case TCS34725_INTEGRATIONTIME_50MS:
delay(50);
break;
case TCS34725_INTEGRATIONTIME_101MS:
delay(101);
break;
case TCS34725_INTEGRATIONTIME_154MS:
delay(154);
break;
case TCS34725_INTEGRATIONTIME_700MS:
delay(700);
break;
}
}
/*!
* @brief Reads the raw red, green, blue and clear channel values in
* one-shot mode (e.g., wakes from sleep, takes measurement, enters
* sleep)
* @param *r
* Red value
* @param *g
* Green value
* @param *b
* Blue value
* @param *c
* Clear channel value
*/
void Adafruit_TCS34725::getRawDataOneShot(uint16_t *r, uint16_t *g, uint16_t *b,
uint16_t *c) {
if (!_tcs34725Initialised)
begin();
enable();
getRawData(r, g, b, c);
disable();
}
/*!
* @brief Read the RGB color detected by the sensor.
* @param *r
* Red value normalized to 0-255
* @param *g
* Green value normalized to 0-255
* @param *b
* Blue value normalized to 0-255
*/
void Adafruit_TCS34725::getRGB(float *r, float *g, float *b) {
uint16_t red, green, blue, clear;
getRawData(&red, &green, &blue, &clear);
uint32_t sum = clear;
// Avoid divide by zero errors ... if clear = 0 return black
if (clear == 0) {
*r = *g = *b = 0;
return;
}
*r = (float)red / sum * 255.0;
*g = (float)green / sum * 255.0;
*b = (float)blue / sum * 255.0;
}
/*!
* @brief Converts the raw R/G/B values to color temperature in degrees Kelvin
* @param r
* Red value
* @param g
* Green value
* @param b
* Blue value
* @return Color temperature in degrees Kelvin
*/
uint16_t Adafruit_TCS34725::calculateColorTemperature(uint16_t r, uint16_t g,
uint16_t b) {
float X, Y, Z; /* RGB to XYZ correlation */
float xc, yc; /* Chromaticity co-ordinates */
float n; /* McCamy's formula */
float cct;
/* 1. Map RGB values to their XYZ counterparts. */
/* Based on 6500K fluorescent, 3000K fluorescent */
/* and 60W incandescent values for a wide range. */
/* Note: Y = Illuminance or lux */
X = (-0.14282F * r) + (1.54924F * g) + (-0.95641F * b);
Y = (-0.32466F * r) + (1.57837F * g) + (-0.73191F * b);
Z = (-0.68202F * r) + (0.77073F * g) + (0.56332F * b);
/* 2. Calculate the chromaticity co-ordinates */
xc = (X) / (X + Y + Z);
yc = (Y) / (X + Y + Z);
/* 3. Use McCamy's formula to determine the CCT */
n = (xc - 0.3320F) / (0.1858F - yc);
/* Calculate the final CCT */
cct =
(449.0F * powf(n, 3)) + (3525.0F * powf(n, 2)) + (6823.3F * n) + 5520.33F;
/* Return the results in degrees Kelvin */
return (uint16_t)cct;
}
/*!
* @brief Converts the raw R/G/B values to color temperature in degrees
* Kelvin using the algorithm described in DN40 from Taos (now AMS).
* @param r
* Red value
* @param g
* Green value
* @param b
* Blue value
* @param c
* Clear channel value
* @return Color temperature in degrees Kelvin
*/
uint16_t Adafruit_TCS34725::calculateColorTemperature_dn40(uint16_t r,
uint16_t g,
uint16_t b,
uint16_t c) {
int rc; /* Error return code */
uint16_t r2, g2, b2; /* RGB values minus IR component */
int gl; /* Results of the initial lux conversion */
uint8_t gain_int; /* Gain multiplier as a normal integer */
uint16_t sat; /* Digital saturation level */
uint16_t ir; /* Inferred IR content */
/* Analog/Digital saturation:
*
* (a) As light becomes brighter, the clear channel will tend to
* saturate first since R+G+B is approximately equal to C.
* (b) The TCS34725 accumulates 1024 counts per 2.4ms of integration
* time, up to a maximum values of 65535. This means analog
* saturation can occur up to an integration time of 153.6ms
* (64*2.4ms=153.6ms).
* (c) If the integration time is > 153.6ms, digital saturation will
* occur before analog saturation. Digital saturation occurs when
* the count reaches 65535.
*/
if ((256 - _tcs34725IntegrationTime) > 63) {
/* Track digital saturation */
sat = 65535;
} else {
/* Track analog saturation */
sat = 1024 * (256 - _tcs34725IntegrationTime);
}
/* Ripple rejection:
*
* (a) An integration time of 50ms or multiples of 50ms are required to
* reject both 50Hz and 60Hz ripple.
* (b) If an integration time faster than 50ms is required, you may need
* to average a number of samples over a 50ms period to reject ripple
* from fluorescent and incandescent light sources.
*
* Ripple saturation notes:
*
* (a) If there is ripple in the received signal, the value read from C
* will be less than the max, but still have some effects of being
* saturated. This means that you can be below the 'sat' value, but
* still be saturating. At integration times >150ms this can be
* ignored, but <= 150ms you should calculate the 75% saturation
* level to avoid this problem.
*/
if ((256 - _tcs34725IntegrationTime) <= 63) {
/* Adjust sat to 75% to avoid analog saturation if atime < 153.6ms */
sat -= sat / 4;
}
/* Check for saturation and mark the sample as invalid if true */
if (c >= sat) {
return 0;
}
/* AMS RGB sensors have no IR channel, so the IR content must be */
/* calculated indirectly. */
ir = (r + g + b > c) ? (r + g + b - c) / 2 : 0;
/* Remove the IR component from the raw RGB values */
r2 = r - ir;
g2 = g - ir;
b2 = b - ir;
/* Convert gain to a usable integer value */
switch (_tcs34725Gain) {
case TCS34725_GAIN_4X: /* GAIN 4X */
gain_int = 4;
break;
case TCS34725_GAIN_16X: /* GAIN 16X */
gain_int = 16;
break;
case TCS34725_GAIN_60X: /* GAIN 60X */
gain_int = 60;
break;
case TCS34725_GAIN_1X: /* GAIN 1X */
default:
gain_int = 1;
break;
}
/* Calculate the counts per lux (CPL), taking into account the optional
* arguments for Glass Attenuation (GA) and Device Factor (DF).
*
* GA = 1/T where T is glass transmissivity, meaning if glass is 50%
* transmissive, the GA is 2 (1/0.5=2), and if the glass attenuates light
* 95% the GA is 20 (1/0.05). A GA of 1.0 assumes perfect transmission.
*
* NOTE: It is recommended to have a CPL > 5 to have a lux accuracy
* < +/- 0.5 lux, where the digitization error can be calculated via:
* 'DER = (+/-2) / CPL'.
*/
float cpl =
(((256 - _tcs34725IntegrationTime) * 2.4f) * gain_int) / (1.0f * 310.0f);
/* Determine lux accuracy (+/- lux) */
float der = 2.0f / cpl;
/* Determine the maximum lux value */
float max_lux = 65535.0 / (cpl * 3);
/* Lux is a function of the IR-compensated RGB channels and the associated
* color coefficients, with G having a particularly heavy influence to
* match the nature of the human eye.
*
* NOTE: The green value should be > 10 to ensure the accuracy of the lux
* conversions. If it is below 10, the gain should be increased, but
* the clear<100 check earlier should cover this edge case.
*/
gl = 0.136f * (float)r2 + /** Red coefficient. */
1.000f * (float)g2 + /** Green coefficient. */
-0.444f * (float)b2; /** Blue coefficient. */
float lux = gl / cpl;
/* A simple method of measuring color temp is to use the ratio of blue */
/* to red light, taking IR cancellation into account. */
uint16_t cct = (3810 * (uint32_t)b2) / /** Color temp coefficient. */
(uint32_t)r2 +
1391; /** Color temp offset. */
return cct;
}
/*!
* @brief Converts the raw R/G/B values to lux
* @param r
* Red value
* @param g
* Green value
* @param b
* Blue value
* @return Lux value
*/
uint16_t Adafruit_TCS34725::calculateLux(uint16_t r, uint16_t g, uint16_t b) {
float illuminance;
/* This only uses RGB ... how can we integrate clear or calculate lux */
/* based exclusively on clear since this might be more reliable? */
illuminance = (-0.32466F * r) + (1.57837F * g) + (-0.73191F * b);
return (uint16_t)illuminance;
}
/*!
* @brief Sets inerrupt for TCS34725
* @param i
* Interrupt (True/False)
*/
void Adafruit_TCS34725::setInterrupt(boolean i) {
uint8_t r = read8(TCS34725_ENABLE);
if (i) {
r |= TCS34725_ENABLE_AIEN;
} else {
r &= ~TCS34725_ENABLE_AIEN;
}
write8(TCS34725_ENABLE, r);
}
/*!
* @brief Clears inerrupt for TCS34725
*/
void Adafruit_TCS34725::clearInterrupt() {
_wire->beginTransmission(_i2caddr);
#if ARDUINO >= 100
_wire->write(TCS34725_COMMAND_BIT | 0x66);
#else
_wire->send(TCS34725_COMMAND_BIT | 0x66);
#endif
_wire->endTransmission();
}
/*!
* @brief Sets inerrupt limits
* @param low
* Low limit
* @param high
* High limit
*/
void Adafruit_TCS34725::setIntLimits(uint16_t low, uint16_t high) {
write8(0x04, low & 0xFF);
write8(0x05, low >> 8);
write8(0x06, high & 0xFF);
write8(0x07, high >> 8);
}

View File

@ -0,0 +1,204 @@
/*!
* @file Adafruit_TCS34725.h
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2013, Adafruit Industries
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
#ifndef _TCS34725_H_
#define _TCS34725_H_
#if ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#endif
#include <Wire.h>
#define TCS34725_ADDRESS (0x29) /**< I2C address **/
#define TCS34725_COMMAND_BIT (0x80) /**< Command bit **/
#define TCS34725_ENABLE (0x00) /**< Interrupt Enable register */
#define TCS34725_ENABLE_AIEN (0x10) /**< RGBC Interrupt Enable */
#define TCS34725_ENABLE_WEN \
(0x08) /**< Wait Enable - Writing 1 activates the wait timer */
#define TCS34725_ENABLE_AEN \
(0x02) /**< RGBC Enable - Writing 1 actives the ADC, 0 disables it */
#define TCS34725_ENABLE_PON \
(0x01) /**< Power on - Writing 1 activates the internal oscillator, 0 \
disables it */
#define TCS34725_ATIME (0x01) /**< Integration time */
#define TCS34725_WTIME \
(0x03) /**< Wait time (if TCS34725_ENABLE_WEN is asserted) */
#define TCS34725_WTIME_2_4MS (0xFF) /**< WLONG0 = 2.4ms WLONG1 = 0.029s */
#define TCS34725_WTIME_204MS (0xAB) /**< WLONG0 = 204ms WLONG1 = 2.45s */
#define TCS34725_WTIME_614MS (0x00) /**< WLONG0 = 614ms WLONG1 = 7.4s */
#define TCS34725_AILTL \
(0x04) /**< Clear channel lower interrupt threshold (lower byte) */
#define TCS34725_AILTH \
(0x05) /**< Clear channel lower interrupt threshold (higher byte) */
#define TCS34725_AIHTL \
(0x06) /**< Clear channel upper interrupt threshold (lower byte) */
#define TCS34725_AIHTH \
(0x07) /**< Clear channel upper interrupt threshold (higher byte) */
#define TCS34725_PERS \
(0x0C) /**< Persistence register - basic SW filtering mechanism for \
interrupts */
#define TCS34725_PERS_NONE \
(0b0000) /**< Every RGBC cycle generates an interrupt */
#define TCS34725_PERS_1_CYCLE \
(0b0001) /**< 1 clean channel value outside threshold range generates an \
interrupt */
#define TCS34725_PERS_2_CYCLE \
(0b0010) /**< 2 clean channel values outside threshold range generates an \
interrupt */
#define TCS34725_PERS_3_CYCLE \
(0b0011) /**< 3 clean channel values outside threshold range generates an \
interrupt */
#define TCS34725_PERS_5_CYCLE \
(0b0100) /**< 5 clean channel values outside threshold range generates an \
interrupt */
#define TCS34725_PERS_10_CYCLE \
(0b0101) /**< 10 clean channel values outside threshold range generates an \
interrupt*/
#define TCS34725_PERS_15_CYCLE \
(0b0110) /**< 15 clean channel values outside threshold range generates an \
interrupt*/
#define TCS34725_PERS_20_CYCLE \
(0b0111) /**< 20 clean channel values outside threshold range generates an \
interrupt*/
#define TCS34725_PERS_25_CYCLE \
(0b1000) /**< 25 clean channel values outside threshold range generates an \
interrupt*/
#define TCS34725_PERS_30_CYCLE \
(0b1001) /**< 30 clean channel values outside threshold range generates an \
interrupt*/
#define TCS34725_PERS_35_CYCLE \
(0b1010) /**< 35 clean channel values outside threshold range generates an \
interrupt*/
#define TCS34725_PERS_40_CYCLE \
(0b1011) /**< 40 clean channel values outside threshold range generates an \
interrupt*/
#define TCS34725_PERS_45_CYCLE \
(0b1100) /**< 45 clean channel values outside threshold range generates an \
interrupt*/
#define TCS34725_PERS_50_CYCLE \
(0b1101) /**< 50 clean channel values outside threshold range generates an \
interrupt*/
#define TCS34725_PERS_55_CYCLE \
(0b1110) /**< 55 clean channel values outside threshold range generates an \
interrupt*/
#define TCS34725_PERS_60_CYCLE \
(0b1111) /**< 60 clean channel values outside threshold range generates an \
interrupt*/
#define TCS34725_CONFIG (0x0D) /**< Configuration **/
#define TCS34725_CONFIG_WLONG \
(0x02) /**< Choose between short and long (12x) wait times via \
TCS34725_WTIME */
#define TCS34725_CONTROL (0x0F) /**< Set the gain level for the sensor */
#define TCS34725_ID \
(0x12) /**< 0x44 = TCS34721/TCS34725, 0x4D = TCS34723/TCS34727 */
#define TCS34725_STATUS (0x13) /**< Device status **/
#define TCS34725_STATUS_AINT (0x10) /**< RGBC Clean channel interrupt */
#define TCS34725_STATUS_AVALID \
(0x01) /**< Indicates that the RGBC channels have completed an integration \
cycle */
#define TCS34725_CDATAL (0x14) /**< Clear channel data low byte */
#define TCS34725_CDATAH (0x15) /**< Clear channel data high byte */
#define TCS34725_RDATAL (0x16) /**< Red channel data low byte */
#define TCS34725_RDATAH (0x17) /**< Red channel data high byte */
#define TCS34725_GDATAL (0x18) /**< Green channel data low byte */
#define TCS34725_GDATAH (0x19) /**< Green channel data high byte */
#define TCS34725_BDATAL (0x1A) /**< Blue channel data low byte */
#define TCS34725_BDATAH (0x1B) /**< Blue channel data high byte */
/** Integration time settings for TCS34725 */
typedef enum {
TCS34725_INTEGRATIONTIME_2_4MS =
0xFF, /**< 2.4ms - 1 cycle - Max Count: 1024 */
TCS34725_INTEGRATIONTIME_24MS =
0xF6, /**< 24ms - 10 cycles - Max Count: 10240 */
TCS34725_INTEGRATIONTIME_50MS =
0xEB, /**< 50ms - 20 cycles - Max Count: 20480 */
TCS34725_INTEGRATIONTIME_101MS =
0xD5, /**< 101ms - 42 cycles - Max Count: 43008 */
TCS34725_INTEGRATIONTIME_154MS =
0xC0, /**< 154ms - 64 cycles - Max Count: 65535 */
TCS34725_INTEGRATIONTIME_700MS =
0x00 /**< 700ms - 256 cycles - Max Count: 65535 */
} tcs34725IntegrationTime_t;
/** Gain settings for TCS34725 */
typedef enum {
TCS34725_GAIN_1X = 0x00, /**< No gain */
TCS34725_GAIN_4X = 0x01, /**< 4x gain */
TCS34725_GAIN_16X = 0x02, /**< 16x gain */
TCS34725_GAIN_60X = 0x03 /**< 60x gain */
} tcs34725Gain_t;
/*!
* @brief Class that stores state and functions for interacting with
* TCS34725 Color Sensor
*/
class Adafruit_TCS34725 {
public:
Adafruit_TCS34725(tcs34725IntegrationTime_t = TCS34725_INTEGRATIONTIME_2_4MS,
tcs34725Gain_t = TCS34725_GAIN_1X);
boolean begin(uint8_t addr, TwoWire *theWire);
boolean begin(uint8_t addr);
boolean begin();
boolean init();
void setIntegrationTime(tcs34725IntegrationTime_t it);
void setGain(tcs34725Gain_t gain);
void getRawData(uint16_t *r, uint16_t *g, uint16_t *b, uint16_t *c);
void getRGB(float *r, float *g, float *b);
void getRawDataOneShot(uint16_t *r, uint16_t *g, uint16_t *b, uint16_t *c);
uint16_t calculateColorTemperature(uint16_t r, uint16_t g, uint16_t b);
uint16_t calculateColorTemperature_dn40(uint16_t r, uint16_t g, uint16_t b,
uint16_t c);
uint16_t calculateLux(uint16_t r, uint16_t g, uint16_t b);
void write8(uint8_t reg, uint32_t value);
uint8_t read8(uint8_t reg);
uint16_t read16(uint8_t reg);
void setInterrupt(boolean flag);
void clearInterrupt();
void setIntLimits(uint16_t l, uint16_t h);
void enable();
void disable();
private:
TwoWire *_wire;
uint8_t _i2caddr;
boolean _tcs34725Initialised;
tcs34725Gain_t _tcs34725Gain;
tcs34725IntegrationTime_t _tcs34725IntegrationTime;
};
#endif

View File

@ -0,0 +1,21 @@
# Adafruit TCS34725 Color Sensor Driver [![Build Status](https://travis-ci.com/adafruit/Adafruit_TCS34725.svg?branch=master)](https://travis-ci.com/adafruit/Adafruit_TCS34725)
<a href="https://www.adafruit.com/product/1334"><img src="assets/board.jpg?raw=true" width="500px"></a>
This driver is for the Adafruit TCS34725 Breakout.
Tested and works great with the Adafruit MCP9808 Breakout Board
* http://www.adafruit.com/products/1334
These modules use I2C to communicate, 2 pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Kevin (KTOWN) Townsend for Adafruit Industries.
BSD license, check license.txt for more information
All text above must be included in any redistribution
To install, use the Arduino Library Manager and search for 'Adafruit TCS34725' and install the library

Binary file not shown.

After

Width:  |  Height:  |  Size: 772 KiB

View File

@ -0,0 +1,127 @@
# Adafruit Community Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and leaders pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level or type of
experience, education, socio-economic status, nationality, personal appearance,
race, religion, or sexual identity and orientation.
## Our Standards
We are committed to providing a friendly, safe and welcoming environment for
all.
Examples of behavior that contributes to creating a positive environment
include:
* Be kind and courteous to others
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Collaborating with other community members
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and sexual attention or advances
* The use of inappropriate images, including in a community member's avatar
* The use of inappropriate language, including in a community member's nickname
* Any spamming, flaming, baiting or other attention-stealing behavior
* Excessive or unwelcome helping; answering outside the scope of the question
asked
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate
The goal of the standards and moderation guidelines outlined here is to build
and maintain a respectful community. We ask that you dont just aim to be
"technically unimpeachable", but rather try to be your best self.
We value many things beyond technical expertise, including collaboration and
supporting others within our community. Providing a positive experience for
other community members can have a much more significant impact than simply
providing the correct answer.
## Our Responsibilities
Project leaders are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project leaders have the right and responsibility to remove, edit, or
reject messages, comments, commits, code, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any community member for other behaviors that they deem
inappropriate, threatening, offensive, or harmful.
## Moderation
Instances of behaviors that violate the Adafruit Community Code of Conduct
may be reported by any member of the community. Community members are
encouraged to report these situations, including situations they witness
involving other community members.
You may report in the following ways:
In any situation, you may send an email to <support@adafruit.com>.
On the Adafruit Discord, you may send an open message from any channel
to all Community Helpers by tagging @community helpers. You may also send an
open message from any channel, or a direct message to @kattni#1507,
@tannewt#4653, @Dan Halbert#1614, @cater#2442, @sommersoft#0222, or
@Andon#8175.
Email and direct message reports will be kept confidential.
In situations on Discord where the issue is particularly egregious, possibly
illegal, requires immediate action, or violates the Discord terms of service,
you should also report the message directly to Discord.
These are the steps for upholding our communitys standards of conduct.
1. Any member of the community may report any situation that violates the
Adafruit Community Code of Conduct. All reports will be reviewed and
investigated.
2. If the behavior is an egregious violation, the community member who
committed the violation may be banned immediately, without warning.
3. Otherwise, moderators will first respond to such behavior with a warning.
4. Moderators follow a soft "three strikes" policy - the community member may
be given another chance, if they are receptive to the warning and change their
behavior.
5. If the community member is unreceptive or unreasonable when warned by a
moderator, or the warning goes unheeded, they may be banned for a first or
second offense. Repeated offenses will result in the community member being
banned.
## Scope
This Code of Conduct and the enforcement policies listed above apply to all
Adafruit Community venues. This includes but is not limited to any community
spaces (both public and private), the entire Adafruit Discord server, and
Adafruit GitHub repositories. Examples of Adafruit Community spaces include
but are not limited to meet-ups, audio chats on the Adafruit Discord, or
interaction at a conference.
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. As a community
member, you are representing our community, and are expected to behave
accordingly.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 1.4, available at
<https://www.contributor-covenant.org/version/1/4/code-of-conduct.html>,
and the [Rust Code of Conduct](https://www.rust-lang.org/en-US/conduct.html).
For other projects adopting the Adafruit Community Code of
Conduct, please contact the maintainers of those projects for enforcement.
If you wish to use this code of conduct for your own project, consider
explicitly mentioning your moderation policy or making a copy with your
own moderation policy so as to avoid confusion.

View File

@ -0,0 +1,111 @@
#include <Wire.h>
#include "Adafruit_TCS34725.h"
// Pick analog outputs, for the UNO these three work well
// use ~560 ohm resistor between Red & Blue, ~1K for green (its brighter)
#define redpin 3
#define greenpin 5
#define bluepin 6
// for a common anode LED, connect the common pin to +5V
// for common cathode, connect the common to ground
// set to false if using a common cathode LED
#define commonAnode true
// our RGB -> eye-recognized gamma color
byte gammatable[256];
Adafruit_TCS34725 tcs = Adafruit_TCS34725(TCS34725_INTEGRATIONTIME_50MS, TCS34725_GAIN_4X);
void setup() {
Serial.begin(9600);
//Serial.println("Color View Test!");
if (tcs.begin()) {
//Serial.println("Found sensor");
} else {
Serial.println("No TCS34725 found ... check your connections");
while (1); // halt!
}
// use these three pins to drive an LED
#if defined(ARDUINO_ARCH_ESP32)
ledcAttachPin(redpin, 1);
ledcSetup(1, 12000, 8);
ledcAttachPin(greenpin, 2);
ledcSetup(2, 12000, 8);
ledcAttachPin(bluepin, 3);
ledcSetup(3, 12000, 8);
#else
pinMode(redpin, OUTPUT);
pinMode(greenpin, OUTPUT);
pinMode(bluepin, OUTPUT);
#endif
// thanks PhilB for this gamma table!
// it helps convert RGB colors to what humans see
for (int i=0; i<256; i++) {
float x = i;
x /= 255;
x = pow(x, 2.5);
x *= 255;
if (commonAnode) {
gammatable[i] = 255 - x;
} else {
gammatable[i] = x;
}
//Serial.println(gammatable[i]);
}
}
// The commented out code in loop is example of getRawData with clear value.
// Processing example colorview.pde can work with this kind of data too, but It requires manual conversion to
// [0-255] RGB value. You can still uncomments parts of colorview.pde and play with clear value.
void loop() {
float red, green, blue;
tcs.setInterrupt(false); // turn on LED
delay(60); // takes 50ms to read
tcs.getRGB(&red, &green, &blue);
tcs.setInterrupt(true); // turn off LED
Serial.print("R:\t"); Serial.print(int(red));
Serial.print("\tG:\t"); Serial.print(int(green));
Serial.print("\tB:\t"); Serial.print(int(blue));
// Serial.print("\t");
// Serial.print((int)red, HEX); Serial.print((int)green, HEX); Serial.print((int)blue, HEX);
Serial.print("\n");
// uint16_t red, green, blue, clear;
//
// tcs.setInterrupt(false); // turn on LED
//
// delay(60); // takes 50ms to read
//
// tcs.getRawData(&red, &green, &blue, &clear);
//
// tcs.setInterrupt(true); // turn off LED
//
// Serial.print("C:\t"); Serial.print(int(clear));
// Serial.print("R:\t"); Serial.print(int(red));
// Serial.print("\tG:\t"); Serial.print(int(green));
// Serial.print("\tB:\t"); Serial.print(int(blue));
// Serial.println();
#if defined(ARDUINO_ARCH_ESP32)
ledcWrite(1, gammatable[(int)red]);
ledcWrite(2, gammatable[(int)green]);
ledcWrite(3, gammatable[(int)blue]);
#else
analogWrite(redpin, gammatable[(int)red]);
analogWrite(greenpin, gammatable[(int)green]);
analogWrite(bluepin, gammatable[(int)blue]);
#endif
}

Some files were not shown because too many files have changed in this diff Show More