Removed all library files because the compilation works using the arduino library manager.

This commit is contained in:
Kai Lauterbach 2023-02-28 15:22:10 +01:00
parent f740973b01
commit 58ea2c1822
720 changed files with 0 additions and 320356 deletions

View File

@ -1,22 +0,0 @@
# Auto detect text files and perform LF normalization
* text=auto
# Custom for Visual Studio
*.cs diff=csharp
*.sln merge=union
*.csproj merge=union
*.vbproj merge=union
*.fsproj merge=union
*.dbproj merge=union
# Standard to msysgit
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain

View File

@ -1,192 +0,0 @@
#################
## SparkFun Useful stuff
#################
## AVR Development
*.eep
*.elf
*.lst
*.lss
*.sym
*.d
*.o
*.srec
*.map
## Notepad++ backup files
*.bak
## BOM files
*bom*
#################
## Eclipse
#################
*.pydevproject
.project
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.classpath
.settings/
.loadpath
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# CDT-specific
.cproject
# PDT-specific
.buildpath
#############
## Eagle
#############
# Ignore the board and schematic backup files
*.b#?
*.s#?
#################
## Visual Studio
#################
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.sln.docstates
# Build results
[Dd]ebug/
[Rr]elease/
*_i.c
*_p.c
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.vspscc
.builds
*.dotCover
## TODO: If you have NuGet Package Restore enabled, uncomment this
#packages/
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
# Visual Studio profiler
*.psess
*.vsp
# ReSharper is a .NET coding add-in
_ReSharper*
# Installshield output folder
[Ee]xpress
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish
# Others
[Bb]in
[Oo]bj
sql
TestResults
*.Cache
ClientBin
stylecop.*
~$*
*.dbmdl
Generated_Code #added for RIA/Silverlight projects
# Backup & report files from converting an old project file to a newer
# Visual Studio version. Backup files are not needed, because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
############
## Windows
############
# Windows image file caches
Thumbs.db
# Folder config file
Desktop.ini
#############
## Python
#############
*.py[co]
# Packages
*.egg
*.egg-info
dist
build
eggs
parts
bin
var
sdist
develop-eggs
.installed.cfg
# Installer logs
pip-log.txt
# Unit test / coverage reports
.coverage
.tox
#Translations
*.mo
#Mr Developer
.mr.developer.cfg
# Mac crap
.DS_Store

View File

@ -1,22 +0,0 @@
The MIT License (MIT)
Copyright (c) 2015 Davide Depau
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

@ -1,92 +0,0 @@
APDS9930 Ambient Light and Proximity sensor
===========================================
This is a fork of the [library from Sparkfun for the APDS-9960 sensor](https://github.com/sparkfun/APDS-9960_RGB_and_Gesture_Sensor). It has been adapted to read values from this other model.
[**Quick-start guide available here**](https://web.archive.org/web/20151224052223/http://davideddu.org/blog/posts/apds-9930-arduino-quickstart/)
[**Purchase an Avago APDS-9930 Breakout Board here**](http://www.dx.com/p/384037?Utm_rid=14976370&Utm_source=affiliate)
# DO NOT EMAIL ME IF YOU HAVE AN ISSUE
It will be deleted without reading. If you have an issue, [create an issue](https://github.com/Depau/APDS9930/issues) here on GitHub.
# Unmaintained
I'm not going to maintain this library any more. I will merge pull requests, though. Contributions are welcome. Just don't expect anything from me.
![Avago APDS-9930 Breakout Board](http://img.dxcdn.com/productimages/sku_384037_1.jpg)
**Note:** even though it says APDS-9960, it's an APDS-9930. That's how I ended up getting one of those. I wanted the RGB sensor. I found this crap in my mailbox. But I decided to write a library for it anyways ;)
Getting Started
---------------
* Download the Git repository as a ZIP ("Download ZIP" button)
* Unzip
* Copy the entire library directory (APDS-9930) to
\<Arduino installation directory\>/libraries
* Open the Arduino program
* Select File -> Examples -> APDS9930 -> GestureTest
* Plug in your Arduino and APDS-9930 with the following connections
*-OR-*
* Use the library manager
| Arduino Pin | APDS-9930 Board | Function |
|---|---|---|
| 3.3V | VCC | Power |
| GND | GND | Ground |
| A4 | SDA | I²C Data |
| A5 | SCL | I²C Clock |
| 2 | INT | Interrupt |
*P.S.: you already know you can't use this purple little thing with your 5V Arduino without a level shifter, right? :) In case you don't have a level shifter, you can detach the microcontroller from an Arduino Uno, reconnect the oscillator pins, the RX and TX pins, the reset and the LED/SCK pins back to the board with some jumper wires. You can then power the microcontroller from a 3.3V source (the 3V3 output on the board should work) and connect the sensor directly to the MCU. Look up "Arduino on Breadboard".*
* Go to Tools -> Board and select your Arduino board
* Go to Tools -> Serial Port and select the COM port of your Arduino board
* Click "Upload"
* Go to Tools -> Serial Monitor
* Ensure the baud rate is set at 9600 baud
* Swipe your hand over the sensor in various directions!
Repository Contents
-------------------
* **/examples** - Example sketches for the library (.ino). Run these from the Arduino IDE.
* **/extras** - Additional documentation for the user. These files are ignored by the IDE.
* **/src** - Source files for the library (.cpp, .h).
* **keywords.txt** - Keywords from this library that will be highlighted in the Arduino IDE.
* **library.properties** - General library properties for the Arduino package manager.
Documentation
--------------
* **[Quickstart Guide](https://web.archive.org/web/20151224052223/http://davideddu.org/blog/posts/apds-9930-arduino-quickstart/)** - Basic hookup guide for the sensor.
* **[Product Repository](https://github.com/Davideddu/APDS9930)** - Main repository (including hardware files) for the APDS9930 ambient light and proximity sensor.
* **[Installing an Arduino Library Guide](https://learn.sparkfun.com/tutorials/installing-an-arduino-library)** - Basic information on how to install an Arduino library.
Version History
---------------
* master - Adapted for use with APDS-9930
* [V_1.4.0](https://github.com/sparkfun/APDS-9960_RGB_and_Gesture_Sensor_Arduino_Library/tree/V_1.4.0) - Updated to new library structure
* V_1.3.0 - Implemented disableProximitySensor(). Thanks to jmg5150 for catching that!
* V_1.2.0 - Added pinMode line to GestureTest demo to fix interrupt bug with some Arduinos
* V_1.1.0 - Updated GestureTest demo to not freeze with fast swipes
* V_1.0.0: Initial release
* Ambient and RGB light sensing implemented
* Ambient light interrupts working
* Proximity sensing implemented
* Proximity interrupts working
License Information
-------------------
This product is _**open source**_!
Please use, reuse, and modify these files as you see fit. Please maintain attribution to SparkFun Electronics and release anything derivative under the same license.
Distributed as-is; no warranty is given.
- Your friends at SparkFun. And Davide Depau :*

View File

@ -1,180 +0,0 @@
/****************************************************************
AmbientLightInterrupt.ino
APDS-9930 RGB and Gesture Sensor
Shawn Hymel @ SparkFun Electronics
October 24, 2014
https://github.com/sparkfun/APDS-9930_RGB_and_Gesture_Sensor
Tests the ambient light interrupt abilities of the APDS-9930.
Configures the APDS-9930 over I2C and waits for an external
interrupt based on high or low light conditions. Try covering
the sensor with your hand or bringing the sensor close to a
bright light source. You might need to adjust the LIGHT_INT_HIGH
and LIGHT_INT_LOW values to get the interrupt to work correctly.
Hardware Connections:
IMPORTANT: The APDS-9930 can only accept 3.3V!
Arduino Pin APDS-9930 Board Function
3.3V VCC Power
GND GND Ground
A4 SDA I2C Data
A5 SCL I2C Clock
2 INT Interrupt
13 - LED
Resources:
Include Wire.h and APDS9930.h
Development environment specifics:
Written in Arduino 1.0.5
Tested with SparkFun Arduino Pro Mini 3.3V
This code is beerware; if you see me (or any other SparkFun
employee) at the local, and you've found our code helpful, please
buy us a round!
Distributed as-is; no warranty is given.
****************************************************************/
#define DUMP_REGS
#include <Wire.h>
#include <APDS9930.h>
// Pins
#define APDS9930_INT 2 // Needs to be an interrupt pin
#define LED_PIN 13 // LED for showing interrupt
// Constants
#define LIGHT_INT_HIGH 1000 // High light level for interrupt
#define LIGHT_INT_LOW 10 // Low light level for interrupt
// Global variables
APDS9930 apds = APDS9930();
float ambient_light = 0;
uint16_t ch0 = 0;
uint16_t ch1 = 1;
volatile bool isr_flag = false;
uint16_t threshold = 0;
void setup() {
// Set LED as output
pinMode(LED_PIN, OUTPUT);
pinMode(APDS9930_INT, INPUT);
// Initialize Serial port
Serial.begin(9600);
Serial.println();
Serial.println(F("----------------------------"));
Serial.println(F("APDS-9930 - Light Interrupts"));
Serial.println(F("----------------------------"));
// Initialize interrupt service routine
attachInterrupt(0, interruptRoutine, FALLING);
// Initialize APDS-9930 (configure I2C and initial values)
if ( apds.init() ) {
Serial.println(F("APDS-9930 initialization complete"));
} else {
Serial.println(F("Something went wrong during APDS-9930 init!"));
}
// Set high and low interrupt thresholds
if ( !apds.setLightIntLowThreshold(LIGHT_INT_LOW) ) {
Serial.println(F("Error writing low threshold"));
}
if ( !apds.setLightIntHighThreshold(LIGHT_INT_HIGH) ) {
Serial.println(F("Error writing high threshold"));
}
// Start running the APDS-9930 light sensor (no interrupts)
if ( apds.enableLightSensor(false) ) {
Serial.println(F("Light sensor is now running"));
} else {
Serial.println(F("Something went wrong during light sensor init!"));
}
// Read high and low interrupt thresholds
if ( !apds.getLightIntLowThreshold(threshold) ) {
Serial.println(F("Error reading low threshold"));
} else {
Serial.print(F("Low Threshold: "));
Serial.println(threshold);
}
if ( !apds.getLightIntHighThreshold(threshold) ) {
Serial.println(F("Error reading high threshold"));
} else {
Serial.print(F("High Threshold: "));
Serial.println(threshold);
}
// Enable interrupts
if ( !apds.setAmbientLightIntEnable(1) ) {
Serial.println(F("Error enabling interrupts"));
}
#ifdef DUMP_REGS
/* Register dump */
uint8_t reg;
uint8_t val;
for(reg = 0x00; reg <= 0x19; reg++) {
if( (reg != 0x10) && \
(reg != 0x11) )
{
apds.wireReadDataByte(reg, val);
Serial.print(reg, HEX);
Serial.print(": 0x");
Serial.println(val, HEX);
}
}
apds.wireReadDataByte(0x1E, val);
Serial.print(0x1E, HEX);
Serial.print(": 0x");
Serial.println(val, HEX);
#endif
// Wait for initialization and calibration to finish
delay(500);
}
void loop() {
// If interrupt occurs, print out the light levels
if ( isr_flag ) {
// Read the light levels (ambient, red, green, blue) and print
if ( !apds.readAmbientLightLux(ambient_light) ||
!apds.readCh0Light(ch0) ||
!apds.readCh1Light(ch1) ) {
Serial.println("Error reading light values");
} else {
Serial.print("Interrupt! Ambient: ");
Serial.print(ambient_light);
Serial.print(F(" Ch0: "));
Serial.print(ch0);
Serial.print(F(" Ch1: "));
Serial.println(ch1);
}
// Turn on LED for a half a second
digitalWrite(LED_PIN, HIGH);
delay(500);
digitalWrite(LED_PIN, LOW);
// Reset flag and clear APDS-9930 interrupt (IMPORTANT!)
isr_flag = false;
if ( !apds.clearAmbientLightInt() ) {
Serial.println("Error clearing interrupt");
}
}
}
void interruptRoutine() {
isr_flag = true;
}

View File

@ -1,113 +0,0 @@
/****************************************************************
AmbientLightLED.ino
Tests the ambient light sensing abilities of the
APDS-9930. Configures APDS-9930 over I2C and polls the sensor for
ambient light levels, which are displayed over the
serial console.
Hardware Connections:
IMPORTANT: The APDS-9930 can only accept 3.3V!
Arduino Pin APDS-9930 Board Function
3.3V VCC Power
GND GND Ground
A4 SDA I2C Data
A5 SCL I2C Clock
10 (pwm) LED anode
Distributed as-is; no warranty is given.
****************************************************************/
#define PWM_LED_PIN 10
#define DUMP_REGS
#include <Wire.h>
#include <APDS9930.h>
// Global Variables
APDS9930 apds = APDS9930();
float ambient_light = 0; // can also be an unsigned long
uint16_t ch0 = 0;
uint16_t ch1 = 1;
float max_light = 0;
void setup() {
//analogReference(EXTERNAL);
pinMode(PWM_LED_PIN, OUTPUT);
// Initialize Serial port
Serial.begin(9600);
Serial.println();
Serial.println(F("--------------------------------"));
Serial.println(F("APDS-9930 - Ambient light sensor"));
Serial.println(F("--------------------------------"));
// Initialize APDS-9930 (configure I2C and initial values)
if ( apds.init() ) {
Serial.println(F("APDS-9930 initialization complete"));
} else {
Serial.println(F("Something went wrong during APDS-9930 init!"));
}
// Start running the APDS-9930 light sensor (no interrupts)
if ( apds.enableLightSensor(false) ) {
Serial.println(F("Light sensor is now running"));
} else {
Serial.println(F("Something went wrong during light sensor init!"));
}
#ifdef DUMP_REGS
/* Register dump */
uint8_t reg;
uint8_t val;
for(reg = 0x00; reg <= 0x19; reg++) {
if( (reg != 0x10) && \
(reg != 0x11) )
{
apds.wireReadDataByte(reg, val);
Serial.print(reg, HEX);
Serial.print(": 0x");
Serial.println(val, HEX);
}
}
apds.wireReadDataByte(0x1E, val);
Serial.print(0x1E, HEX);
Serial.print(": 0x");
Serial.println(val, HEX);
#endif
// Wait for initialization and calibration to finish
delay(500);
}
void loop() {
// Read the light levels (ambient, red, green, blue)
if ( !apds.readAmbientLightLux(ambient_light) ||
!apds.readCh0Light(ch0) ||
!apds.readCh1Light(ch1) ) {
Serial.println(F("Error reading light values"));
} else {
Serial.print(F("Ambient: "));
Serial.print(ambient_light);
Serial.print(F(" Ch0: "));
Serial.print(ch0);
Serial.print(F(" Ch1: "));
Serial.println(ch1);
if ( ambient_light > max_light ) {
max_light = ambient_light;
}
ambient_light = map(ambient_light, 0, max_light, 0, 1023);
analogWrite(PWM_LED_PIN, ambient_light);
}
// Wait 1 second before next reading
delay(50);
}

View File

@ -1,120 +0,0 @@
/****************************************************************
AmbientLightSensor.ino
APDS-9930 Ambient light and proximity sensor
Davide Depau
December 11, 2015
https://github.com/Davideddu/APDS9930
Shawn Hymel @ SparkFun Electronics
October 15, 2014
https://github.com/sparkfun/APDS-9930_RGB_and_Gesture_Sensor
Tests thembient light sensing abilities of the
APDS-9930. Configures APDS-9930 over I2C and polls the sensor for
ambient light levels, which are displayed over the
serial console.
Hardware Connections:
IMPORTANT: The APDS-9930 can only accept 3.3V!
Arduino Pin APDS-9930 Board Function
3.3V VCC Power
GND GND Ground
A4 SDA I2C Data
A5 SCL I2C Clock
Resources:
Include Wire.h and APDS-9930.h
Development environment specifics:
Written in Arduino 1.6.5
Tested with Arduino Uno and Mega.
This code is beerware; if you see me (or any other SparkFun
employee) at the local, and you've found our code helpful, please
buy us a round!
Distributed as-is; no warranty is given.
****************************************************************/
#define DUMP_REGS
#include <Wire.h>
#include <APDS9930.h>
// Global Variables
APDS9930 apds = APDS9930();
float ambient_light = 0; // can also be an unsigned long
uint16_t ch0 = 0;
uint16_t ch1 = 1;
void setup() {
//analogReference(EXTERNAL);
// Initialize Serial port
Serial.begin(9600);
Serial.println();
Serial.println(F("--------------------------------"));
Serial.println(F("APDS-9930 - Ambient light sensor"));
Serial.println(F("--------------------------------"));
// Initialize APDS-9930 (configure I2C and initial values)
if ( apds.init() ) {
Serial.println(F("APDS-9930 initialization complete"));
} else {
Serial.println(F("Something went wrong during APDS-9930 init!"));
}
// Start running the APDS-9930 light sensor (no interrupts)
if ( apds.enableLightSensor(false) ) {
Serial.println(F("Light sensor is now running"));
} else {
Serial.println(F("Something went wrong during light sensor init!"));
}
#ifdef DUMP_REGS
/* Register dump */
uint8_t reg;
uint8_t val;
for(reg = 0x00; reg <= 0x19; reg++) {
if( (reg != 0x10) && \
(reg != 0x11) )
{
apds.wireReadDataByte(reg, val);
Serial.print(reg, HEX);
Serial.print(": 0x");
Serial.println(val, HEX);
}
}
apds.wireReadDataByte(0x1E, val);
Serial.print(0x1E, HEX);
Serial.print(": 0x");
Serial.println(val, HEX);
#endif
// Wait for initialization and calibration to finish
delay(500);
}
void loop() {
// Read the light levels (ambient, red, green, blue)
if ( !apds.readAmbientLightLux(ambient_light) ||
!apds.readCh0Light(ch0) ||
!apds.readCh1Light(ch1) ) {
Serial.println(F("Error reading light values"));
} else {
Serial.print(F("Ambient: "));
Serial.print(ambient_light);
Serial.print(F(" Ch0: "));
Serial.print(ch0);
Serial.print(F(" Ch1: "));
Serial.println(ch1);
}
// Wait 1 second before next reading
delay(1000);
}

View File

@ -1,108 +0,0 @@
/****************************************************************
AmbientLightToneAC.ino
Tests the ambient light sensing abilities of the
APDS-9930. Configures APDS-9930 over I2C and polls the sensor for
ambient light levels, which are displayed over the
serial console.
Hardware Connections:
IMPORTANT: The APDS-9930 can only accept 3.3V!
Arduino Pin APDS-9930 Board Function
3.3V VCC Power
GND GND Ground
A4 SDA I2C Data
A5 SCL I2C Clock
Connect speakers to the correct pins. Check toneAC.h for more info.
Distributed as-is; no warranty is given.
****************************************************************/
#define DUMP_REGS
#include <Wire.h>
#include <APDS9930.h>
#include <toneAC.h>
// Global Variables
APDS9930 apds = APDS9930();
float ambient_light = 0; // can also be an unsigned long
uint16_t ch0 = 0;
uint16_t ch1 = 1;
float max_light = 0;
void setup() {
//analogReference(EXTERNAL);
// Initialize Serial port
Serial.begin(9600);
Serial.println();
Serial.println(F("--------------------------------"));
Serial.println(F("APDS-9930 - Ambient light sensor"));
Serial.println(F("--------------------------------"));
// Initialize APDS-9930 (configure I2C and initial values)
if ( apds.init() ) {
Serial.println(F("APDS-9930 initialization complete"));
} else {
Serial.println(F("Something went wrong during APDS-9930 init!"));
}
// Start running the APDS-9930 light sensor (no interrupts)
if ( apds.enableLightSensor(false) ) {
Serial.println(F("Light sensor is now running"));
} else {
Serial.println(F("Something went wrong during light sensor init!"));
}
#ifdef DUMP_REGS
/* Register dump */
uint8_t reg;
uint8_t val;
for(reg = 0x00; reg <= 0x19; reg++) {
if( (reg != 0x10) && \
(reg != 0x11) )
{
apds.wireReadDataByte(reg, val);
Serial.print(reg, HEX);
Serial.print(": 0x");
Serial.println(val, HEX);
}
}
apds.wireReadDataByte(0x1E, val);
Serial.print(0x1E, HEX);
Serial.print(": 0x");
Serial.println(val, HEX);
#endif
// Wait for initialization and calibration to finish
delay(500);
}
void loop() {
// Read the light levels (ambient, red, green, blue)
if ( !apds.readAmbientLightLux(ambient_light) ||
!apds.readCh0Light(ch0) ||
!apds.readCh1Light(ch1) ) {
Serial.println(F("Error reading light values"));
} else {
Serial.print(F("Ambient: "));
Serial.print(ambient_light);
Serial.print(F(" Ch0: "));
Serial.print(ch0);
Serial.print(F(" Ch1: "));
Serial.println(ch1);
unsigned long freq = map(ch0, 0, 1024, 60, 16000);
toneAC(freq, 10, 50, true);
}
// Wait 1 second before next reading
delay(50);
}

View File

@ -1,157 +0,0 @@
/****************************************************************
ProximityInterrupt.ino
APDS-9930 Ambient light and proximity sensor
Davide Depau
December 11, 2015
https://github.com/Davideddu/APDS9930
Shawn Hymel @ SparkFun Electronics
October 24, 2014
https://github.com/sparkfun/APDS-9930_RGB_and_Gesture_Sensor
Tests the proximity interrupt abilities of the APDS-9930.
Configures the APDS-9930 over I2C and waits for an external
interrupt based on high or low proximity conditions. Move your
hand near the sensor and watch the LED on pin 13.
Hardware Connections:
IMPORTANT: The APDS-9930 can only accept 3.3V!
Arduino Pin APDS-9930 Board Function
3.3V VCC Power
GND GND Ground
A4 SDA I2C Data
A5 SCL I2C Clock
2 INT Interrupt
13 - LED
Resources:
Include Wire.h and APDS9930.h
Development environment specifics:
Written in Arduino 1.6.5
Tested with Arduino Uno and Mega
This code is beerware; if you see me (or any other SparkFun
employee) at the local, and you've found our code helpful, please
buy us a round!
Distributed as-is; no warranty is given.
****************************************************************/
#define DUMP_REGS
#include <Wire.h>
#include <APDS9930.h>
// Pins
#define APDS9930_INT 2 // Needs to be an interrupt pin
#define LED_PIN 13 // LED for showing interrupt
// Constants
#define PROX_INT_HIGH 600 // Proximity level for interrupt
#define PROX_INT_LOW 0 // No far interrupt
// Global variables
APDS9930 apds = APDS9930();
uint16_t proximity_data = 0;
volatile bool isr_flag = false;
void setup() {
// Set LED as output
pinMode(LED_PIN, OUTPUT);
pinMode(APDS9930_INT, INPUT);
// Initialize Serial port
Serial.begin(9600);
Serial.println();
Serial.println(F("------------------------------"));
Serial.println(F("APDS-9930 - ProximityInterrupt"));
Serial.println(F("------------------------------"));
// Initialize interrupt service routine
attachInterrupt(0, interruptRoutine, FALLING);
// Initialize APDS-9930 (configure I2C and initial values)
if ( apds.init() ) {
Serial.println(F("APDS-9930 initialization complete"));
} else {
Serial.println(F("Something went wrong during APDS-9930 init!"));
}
// Adjust the Proximity sensor gain
if ( !apds.setProximityGain(PGAIN_2X) ) {
Serial.println(F("Something went wrong trying to set PGAIN"));
}
// Set proximity interrupt thresholds
if ( !apds.setProximityIntLowThreshold(PROX_INT_LOW) ) {
Serial.println(F("Error writing low threshold"));
}
if ( !apds.setProximityIntHighThreshold(PROX_INT_HIGH) ) {
Serial.println(F("Error writing high threshold"));
}
// Start running the APDS-9930 proximity sensor (interrupts)
if ( apds.enableProximitySensor(true) ) {
Serial.println(F("Proximity sensor is now running"));
} else {
Serial.println(F("Something went wrong during sensor init!"));
}
#ifdef DUMP_REGS
/* Register dump */
uint8_t reg;
uint8_t val;
for(reg = 0x00; reg <= 0x19; reg++) {
if( (reg != 0x10) && \
(reg != 0x11) )
{
apds.wireReadDataByte(reg, val);
Serial.print(reg, HEX);
Serial.print(": 0x");
Serial.println(val, HEX);
}
}
apds.wireReadDataByte(0x1E, val);
Serial.print(0x1E, HEX);
Serial.print(": 0x");
Serial.println(val, HEX);
#endif
}
void loop() {
// If interrupt occurs, print out the proximity level
if ( isr_flag ) {
// Read proximity level and print it out
if ( !apds.readProximity(proximity_data) ) {
Serial.println("Error reading proximity value");
} else {
Serial.print("Proximity detected! Level: ");
Serial.println(proximity_data);
}
// Turn on LED for a half a second
digitalWrite(LED_PIN, HIGH);
delay(500);
digitalWrite(LED_PIN, LOW);
// Reset flag and clear APDS-9930 interrupt (IMPORTANT!)
isr_flag = false;
if ( !apds.clearProximityInt() ) {
Serial.println("Error clearing interrupt");
}
}
}
void interruptRoutine() {
isr_flag = true;
}

View File

@ -1,131 +0,0 @@
/****************************************************************
ProximityLED.ino
Davide Depau
December 11, 2015
https://github.com/Davideddu/APDS9930
https://github.com/sparkfun/APDS-9930_RGB_and_Gesture_Sensor
Tests the proximity sensing abilities of the APDS-9930.
Configures the APDS-9930 over I2C and polls for the distance to
the object nearest the sensor, then turns on an LED accordingly.
Hardware Connections:
IMPORTANT: The APDS-9930 can only accept 3.3V!
Arduino Pin APDS-9930 Board Function
3.3V VCC Power
GND GND Ground
A4 SDA I2C Data
A5 SCL I2C Clock
10 (PWM) LED Anode
Resources:
Include Wire.h and APDS9930.h
Development environment specifics:
Written in Sublime Text + Stino + Arduino 1.7.2
Tested with Arduino Uno + level shifter
This code is chocolateware; if you see me at the grocery store,
and you've found our code helpful, please buy us me a chocolate bar! :D
Distributed as-is; no warranty is given.
****************************************************************/
#define DUMP_REGS
#define PWM_LED_PIN 10
#include <Wire.h>
#include <APDS9930.h>
// Global Variables
APDS9930 apds = APDS9930();
uint16_t proximity_data = 0;
int proximity_max = 0;
void setup() {
//analogReference(EXTERNAL);
pinMode(PWM_LED_PIN, OUTPUT);
// Initialize Serial port
Serial.begin(9600);
Serial.println();
Serial.println(F("------------------------"));
Serial.println(F("APDS-9930 - ProximityLED"));
Serial.println(F("------------------------"));
// Initialize APDS-9930 (configure I2C and initial values)
if ( apds.init() ) {
Serial.println(F("APDS-9930 initialization complete"));
} else {
Serial.println(F("Something went wrong during APDS-9930 init!"));
}
// Adjust the Proximity sensor gain
if ( !apds.setProximityGain(PGAIN_1X) ) {
Serial.println(F("Something went wrong trying to set PGAIN"));
}
// Start running the APDS-9930 proximity sensor (no interrupts)
if ( apds.enableProximitySensor(false) ) {
Serial.println(F("Proximity sensor is now running"));
} else {
Serial.println(F("Something went wrong during sensor init!"));
}
#ifdef DUMP_REGS
/* Register dump */
uint8_t reg;
uint8_t val;
for(reg = 0x00; reg <= 0x19; reg++) {
if( (reg != 0x10) && \
(reg != 0x11) )
{
apds.wireReadDataByte(reg, val);
Serial.print(reg, HEX);
Serial.print(": 0x");
Serial.println(val, HEX);
}
}
apds.wireReadDataByte(0x1E, val);
Serial.print(0x1E, HEX);
Serial.print(": 0x");
Serial.println(val, HEX);
#endif
}
void loop() {
// Read the proximity value
if ( !apds.readProximity(proximity_data) ) {
Serial.println("Error reading proximity value");
} else {
Serial.print("Proximity: ");
Serial.print(proximity_data);
// This is an ugly hack to reduce sensor noise.
// You may want to adjust POFFSET instead.
/*
proximity_data -= 200;
if (proximity_data > 50000) {
proximity_data = 0;
}
if (proximity_data > proximity_max) {
proximity_max = proximity_data;
}
proximity_data = map(proximity_data, 0, proximity_max, 0, 1023);
*/
Serial.print(F(" Remapped: "));
Serial.println(proximity_data);
analogWrite(PWM_LED_PIN, proximity_data);
}
// Wait 250 ms before next reading
delay(10);
}

View File

@ -1,113 +0,0 @@
/****************************************************************
ProximitySensor.ino
APDS-9930 ambient light and proximity sensor
Davide Depau
December 11, 2015
https://github.com/Davideddu/APDS9930
Shawn Hymel @ SparkFun Electronics
October 28, 2014
https://github.com/sparkfun/APDS-9960_RGB_and_Gesture_Sensor
Tests the proximity sensing abilities of the APDS-9930.
Configures the APDS-9930 over I2C and polls for the distance to
the object nearest the sensor.
Hardware Connections:
IMPORTANT: The APDS-9930 can only accept 3.3V!
Arduino Pin APDS-9930 Board Function
3.3V VCC Power
GND GND Ground
A4 SDA I2C Data
A5 SCL I2C Clock
Resources:
Include Wire.h and SparkFun_APDS-9930.h
Development environment specifics:
Written in Arduino 1.0.5
Tested with SparkFun Arduino Pro Mini 3.3V
This code is beerware; if you see me (or any other SparkFun
employee) at the local, and you've found our code helpful, please
buy us a round!
Distributed as-is; no warranty is given.
****************************************************************/
#define DUMP_REGS
#include <Wire.h>
#include <APDS9930.h>
// Global Variables
APDS9930 apds = APDS9930();
uint16_t proximity_data = 0;
void setup() {
//analogReference(EXTERNAL);
// Initialize Serial port
Serial.begin(9600);
Serial.println();
Serial.println(F("---------------------------"));
Serial.println(F("APDS-9930 - ProximitySensor"));
Serial.println(F("---------------------------"));
// Initialize APDS-9930 (configure I2C and initial values)
if ( apds.init() ) {
Serial.println(F("APDS-9930 initialization complete"));
} else {
Serial.println(F("Something went wrong during APDS-9930 init!"));
}
// // Adjust the Proximity sensor gain
// if ( !apds.setProximityGain(PGAIN_2X) ) {
// Serial.println(F("Something went wrong trying to set PGAIN"));
// }
// Start running the APDS-9930 proximity sensor (no interrupts)
if ( apds.enableProximitySensor(false) ) {
Serial.println(F("Proximity sensor is now running"));
} else {
Serial.println(F("Something went wrong during sensor init!"));
}
#ifdef DUMP_REGS
/* Register dump */
uint8_t reg;
uint8_t val;
for(reg = 0x00; reg <= 0x19; reg++) {
if( (reg != 0x10) && \
(reg != 0x11) )
{
apds.wireReadDataByte(reg, val);
Serial.print(reg, HEX);
Serial.print(": 0x");
Serial.println(val, HEX);
}
}
apds.wireReadDataByte(0x1E, val);
Serial.print(0x1E, HEX);
Serial.print(": 0x");
Serial.println(val, HEX);
#endif
}
void loop() {
// Read the proximity value
if ( !apds.readProximity(proximity_data) ) {
Serial.println("Error reading proximity value");
} else {
Serial.print("Proximity: ");
Serial.println(proximity_data);
}
// Wait 250 ms before next reading
delay(250);
}

View File

@ -1,9 +0,0 @@
name=APDS-9930 Ambient Light and Proximity Sensor
version=1.5.1
author=Davide Depau
maintainer=Davide Depau
sentence=Library for the Avago APDS-9930 sensor
paragraph=This library works with the breakout board for the Avago APDS-9930 proximity and light sensor
category=Sensors
url=https://github.com/Davideddu/APDS9930
architectures=*

File diff suppressed because it is too large Load Diff

View File

@ -1,231 +0,0 @@
/**
* @file APDS-9930.h
* @brief Library for the SparkFun APDS-9930 breakout board
* @author Shawn Hymel (SparkFun Electronics)
*
* @copyright This code is public domain but you buy me a beer if you use
* this and we meet someday (Beerware license).
*
* This library interfaces the Avago APDS-9930 to Arduino over I2C. The library
* relies on the Arduino Wire (I2C) library. to use the library, instantiate an
* APDS9930 object, call init(), and call the appropriate functions.
*/
#ifndef APDS9930_H
#define APDS9930_H
#include <Arduino.h>
/* Debug */
#define DEBUG 0
/* APDS-9930 I2C address */
#define APDS9930_I2C_ADDR 0x39
/* Command register modes */
#define REPEATED_BYTE 0x80
#define AUTO_INCREMENT 0xA0
#define SPECIAL_FN 0xE0
/* Error code for returned values */
#define ERROR 0xFF
/* Acceptable device IDs */
#define APDS9930_ID_1 0x12
#define APDS9930_ID_2 0x39
/* Misc parameters */
#define FIFO_PAUSE_TIME 30 // Wait period (ms) between FIFO reads
/* APDS-9930 register addresses */
#define APDS9930_ENABLE 0x00
#define APDS9930_ATIME 0x01
#define APDS9930_PTIME 0x02
#define APDS9930_WTIME 0x03
#define APDS9930_AILTL 0x04
#define APDS9930_AILTH 0x05
#define APDS9930_AIHTL 0x06
#define APDS9930_AIHTH 0x07
#define APDS9930_PILTL 0x08
#define APDS9930_PILTH 0x09
#define APDS9930_PIHTL 0x0A
#define APDS9930_PIHTH 0x0B
#define APDS9930_PERS 0x0C
#define APDS9930_CONFIG 0x0D
#define APDS9930_PPULSE 0x0E
#define APDS9930_CONTROL 0x0F
#define APDS9930_ID 0x12
#define APDS9930_STATUS 0x13
#define APDS9930_Ch0DATAL 0x14
#define APDS9930_Ch0DATAH 0x15
#define APDS9930_Ch1DATAL 0x16
#define APDS9930_Ch1DATAH 0x17
#define APDS9930_PDATAL 0x18
#define APDS9930_PDATAH 0x19
#define APDS9930_POFFSET 0x1E
/* Bit fields */
#define APDS9930_PON 0b00000001
#define APDS9930_AEN 0b00000010
#define APDS9930_PEN 0b00000100
#define APDS9930_WEN 0b00001000
#define APSD9930_AIEN 0b00010000
#define APDS9930_PIEN 0b00100000
#define APDS9930_SAI 0b01000000
/* On/Off definitions */
#define OFF 0
#define ON 1
/* Acceptable parameters for setMode */
#define POWER 0
#define AMBIENT_LIGHT 1
#define PROXIMITY 2
#define WAIT 3
#define AMBIENT_LIGHT_INT 4
#define PROXIMITY_INT 5
#define SLEEP_AFTER_INT 6
#define ALL 7
/* LED Drive values */
#define LED_DRIVE_100MA 0
#define LED_DRIVE_50MA 1
#define LED_DRIVE_25MA 2
#define LED_DRIVE_12_5MA 3
/* Proximity Gain (PGAIN) values */
#define PGAIN_1X 0
#define PGAIN_2X 1
#define PGAIN_4X 2
#define PGAIN_8X 3
/* ALS Gain (AGAIN) values */
#define AGAIN_1X 0
#define AGAIN_8X 1
#define AGAIN_16X 2
#define AGAIN_120X 3
/* Interrupt clear values */
#define CLEAR_PROX_INT 0xE5
#define CLEAR_ALS_INT 0xE6
#define CLEAR_ALL_INTS 0xE7
/* Default values */
#define DEFAULT_ATIME 0xED
#define DEFAULT_WTIME 0xFF
#define DEFAULT_PTIME 0xFF
#define DEFAULT_PPULSE 0x08
#define DEFAULT_POFFSET 0 // 0 offset
#define DEFAULT_CONFIG 0
#define DEFAULT_PDRIVE LED_DRIVE_100MA
#define DEFAULT_PDIODE 2
#define DEFAULT_PGAIN PGAIN_8X
#define DEFAULT_AGAIN AGAIN_1X
#define DEFAULT_PILT 0 // Low proximity threshold
#define DEFAULT_PIHT 50 // High proximity threshold
#define DEFAULT_AILT 0xFFFF // Force interrupt for calibration
#define DEFAULT_AIHT 0
#define DEFAULT_PERS 0x22 // 2 consecutive prox or ALS for int.
/* ALS coefficients */
#define DF 52
#define GA 0.49
#define B 1.862
#define C 0.746
#define D 1.291
/* State definitions */
enum {
NOTAVAILABLE_STATE,
NEAR_STATE,
FAR_STATE,
ALL_STATE
};
#ifdef _AVR_IO_H_
// Do not use this alias as it's deprecated
#define NA_STATE NOTAVAILABLE_STATE
#endif
/* APDS9930 Class */
class APDS9930 {
public:
/* Initialization methods */
APDS9930();
~APDS9930();
bool init();
uint8_t getMode();
bool setMode(uint8_t mode, uint8_t enable);
/* Turn the APDS-9930 on and off */
bool enablePower();
bool disablePower();
/* Enable or disable specific sensors */
bool enableLightSensor(bool interrupts = false);
bool disableLightSensor();
bool enableProximitySensor(bool interrupts = false);
bool disableProximitySensor();
/* LED drive strength control */
uint8_t getLEDDrive();
bool setLEDDrive(uint8_t drive);
// uint8_t getGestureLEDDrive();
// bool setGestureLEDDrive(uint8_t drive);
/* Gain control */
uint8_t getAmbientLightGain();
bool setAmbientLightGain(uint8_t gain);
uint8_t getProximityGain();
bool setProximityGain(uint8_t gain);
bool setProximityDiode(uint8_t drive);
uint8_t getProximityDiode();
/* Get and set light interrupt thresholds */
bool getLightIntLowThreshold(uint16_t &threshold);
bool setLightIntLowThreshold(uint16_t threshold);
bool getLightIntHighThreshold(uint16_t &threshold);
bool setLightIntHighThreshold(uint16_t threshold);
/* Get and set interrupt enables */
uint8_t getAmbientLightIntEnable();
bool setAmbientLightIntEnable(uint8_t enable);
uint8_t getProximityIntEnable();
bool setProximityIntEnable(uint8_t enable);
/* Clear interrupts */
bool clearAmbientLightInt();
bool clearProximityInt();
bool clearAllInts();
/* Proximity methods */
bool readProximity(uint16_t &val);
/* Ambient light methods */
bool readAmbientLightLux(float &val);
bool readAmbientLightLux(unsigned long &val);
float floatAmbientToLux(uint16_t Ch0, uint16_t Ch1);
unsigned long ulongAmbientToLux(uint16_t Ch0, uint16_t Ch1);
bool readCh0Light(uint16_t &val);
bool readCh1Light(uint16_t &val);
//private:
/* Proximity Interrupt Threshold */
uint16_t getProximityIntLowThreshold();
bool setProximityIntLowThreshold(uint16_t threshold);
uint16_t getProximityIntHighThreshold();
bool setProximityIntHighThreshold(uint16_t threshold);
/* Raw I2C Commands */
bool wireWriteByte(uint8_t val);
bool wireWriteDataByte(uint8_t reg, uint8_t val);
bool wireWriteDataBlock(uint8_t reg, uint8_t *val, unsigned int len);
bool wireReadDataByte(uint8_t reg, uint8_t &val);
int wireReadDataBlock(uint8_t reg, uint8_t *val, unsigned int len);
};
#endif

View File

@ -1,726 +0,0 @@
/*!
* @file Adafruit_APDS9960.cpp
*
* @mainpage Adafruit APDS9960 Proximity, Light, RGB, and Gesture Sensor
*
* @section author Author
*
* Ladyada, Dean Miller (Adafruit Industries)
*
* @section license License
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2017, 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.
*/
#ifdef __AVR
#include <avr/pgmspace.h>
#elif defined(ESP8266)
#include <pgmspace.h>
#endif
#include <math.h>
#include <stdlib.h>
#include "Adafruit_APDS9960.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 Enables the device
* Disables the device (putting it in lower power sleep mode)
* @param en
* Enable (True/False)
*/
void Adafruit_APDS9960::enable(boolean en) {
_enable.PON = en;
this->write8(APDS9960_ENABLE, _enable.get());
}
/*!
* @brief Initializes I2C and configures the sensor
* @param iTimeMS
* Integration time
* @param aGain
* Gain
* @param addr
* I2C address
* @param *theWire
* Wire object
* @return True if initialization was successful, otherwise false.
*/
boolean Adafruit_APDS9960::begin(uint16_t iTimeMS, apds9960AGain_t aGain,
uint8_t addr, TwoWire *theWire) {
_wire = theWire;
_i2c_init();
_i2caddr = addr;
/* Make sure we're actually connected */
uint8_t x = read8(APDS9960_ID);
if (x != 0xAB) {
return false;
}
/* Set default integration time and gain */
setADCIntegrationTime(iTimeMS);
setADCGain(aGain);
// disable everything to start
enableGesture(false);
enableProximity(false);
enableColor(false);
disableColorInterrupt();
disableProximityInterrupt();
clearInterrupt();
/* Note: by default, the device is in power down mode on bootup */
enable(false);
delay(10);
enable(true);
delay(10);
// default to all gesture dimensions
setGestureDimensions(APDS9960_DIMENSIONS_ALL);
setGestureFIFOThreshold(APDS9960_GFIFO_4);
setGestureGain(APDS9960_GGAIN_4);
setGestureProximityThreshold(50);
resetCounts();
_gpulse.GPLEN = APDS9960_GPULSE_32US;
_gpulse.GPULSE = 9; // 10 pulses
this->write8(APDS9960_GPULSE, _gpulse.get());
return true;
}
/*!
* @brief Sets the integration time for the ADC of the APDS9960, in millis
* @param iTimeMS
* Integration time
*/
void Adafruit_APDS9960::setADCIntegrationTime(uint16_t iTimeMS) {
float temp;
// convert ms into 2.78ms increments
temp = iTimeMS;
temp /= 2.78;
temp = 256 - temp;
if (temp > 255)
temp = 255;
if (temp < 0)
temp = 0;
/* Update the timing register */
write8(APDS9960_ATIME, (uint8_t)temp);
}
/*!
* @brief Returns the integration time for the ADC of the APDS9960, in millis
* @return Integration time
*/
float Adafruit_APDS9960::getADCIntegrationTime() {
float temp;
temp = read8(APDS9960_ATIME);
// convert to units of 2.78 ms
temp = 256 - temp;
temp *= 2.78;
return temp;
}
/*!
* @brief Adjusts the color/ALS gain on the APDS9960 (adjusts the sensitivity
* to light)
* @param aGain
* Gain
*/
void Adafruit_APDS9960::setADCGain(apds9960AGain_t aGain) {
_control.AGAIN = aGain;
/* Update the timing register */
write8(APDS9960_CONTROL, _control.get());
}
/*!
* @brief Returns the ADC gain
* @return ADC gain
*/
apds9960AGain_t Adafruit_APDS9960::getADCGain() {
return (apds9960AGain_t)(read8(APDS9960_CONTROL) & 0x03);
}
/*!
* @brief Adjusts the Proximity gain on the APDS9960
* @param pGain
* Gain
*/
void Adafruit_APDS9960::setProxGain(apds9960PGain_t pGain) {
_control.PGAIN = pGain;
/* Update the timing register */
write8(APDS9960_CONTROL, _control.get());
}
/*!
* @brief Returns the Proximity gain on the APDS9960
* @return Proxmity gain
*/
apds9960PGain_t Adafruit_APDS9960::getProxGain() {
return (apds9960PGain_t)(read8(APDS9960_CONTROL) & 0x0C);
}
/*!
* @brief Sets number of proxmity pulses
* @param pLen
* Pulse Length
* @param pulses
* Number of pulses
*/
void Adafruit_APDS9960::setProxPulse(apds9960PPulseLen_t pLen, uint8_t pulses) {
if (pulses < 1)
pulses = 1;
if (pulses > 64)
pulses = 64;
pulses--;
_ppulse.PPLEN = pLen;
_ppulse.PPULSE = pulses;
write8(APDS9960_PPULSE, _ppulse.get());
}
/*!
* @brief Enable proximity readings on APDS9960
* @param en
* Enable (True/False)
*/
void Adafruit_APDS9960::enableProximity(boolean en) {
_enable.PEN = en;
write8(APDS9960_ENABLE, _enable.get());
}
/*!
* @brief Enable proximity interrupts
*/
void Adafruit_APDS9960::enableProximityInterrupt() {
_enable.PIEN = 1;
write8(APDS9960_ENABLE, _enable.get());
clearInterrupt();
}
/*!
* @brief Disable proximity interrupts
*/
void Adafruit_APDS9960::disableProximityInterrupt() {
_enable.PIEN = 0;
write8(APDS9960_ENABLE, _enable.get());
}
/*!
* @brief Set proxmity interrupt thresholds
* @param low
* Low threshold
* @param high
* High threshold
* @param persistance
* Persistance
*/
void Adafruit_APDS9960::setProximityInterruptThreshold(uint8_t low,
uint8_t high,
uint8_t persistance) {
write8(APDS9960_PILT, low);
write8(APDS9960_PIHT, high);
if (persistance > 7)
persistance = 7;
_pers.PPERS = persistance;
write8(APDS9960_PERS, _pers.get());
}
/*!
* @brief Returns proxmity interrupt status
* @return True if enabled, false otherwise.
*/
bool Adafruit_APDS9960::getProximityInterrupt() {
_status.set(this->read8(APDS9960_STATUS));
return _status.PINT;
};
/*!
* @brief Read proximity data
* @return Proximity
*/
uint8_t Adafruit_APDS9960::readProximity() { return read8(APDS9960_PDATA); }
/*!
* @brief Returns validity status of a gesture
* @return Status (True/False)
*/
bool Adafruit_APDS9960::gestureValid() {
_gstatus.set(this->read8(APDS9960_GSTATUS));
return _gstatus.GVALID;
}
/*!
* @brief Sets gesture dimensions
* @param dims
* Dimensions (APDS9960_DIMENSIONS_ALL, APDS9960_DIMENSIONS_UP_DOWM,
* APDS9960_DIMENSIONS_UP_DOWN, APGS9960_DIMENSIONS_LEFT_RIGHT)
*/
void Adafruit_APDS9960::setGestureDimensions(uint8_t dims) {
_gconf3.GDIMS = dims;
this->write8(APDS9960_GCONF3, _gconf3.get());
}
/*!
* @brief Sets gesture FIFO Threshold
* @param thresh
* Threshold (APDS9960_GFIFO_1, APDS9960_GFIFO_4, APDS9960_GFIFO_8,
* APDS9960_GFIFO_16)
*/
void Adafruit_APDS9960::setGestureFIFOThreshold(uint8_t thresh) {
_gconf1.GFIFOTH = thresh;
this->write8(APDS9960_GCONF1, _gconf1.get());
}
/*!
* @brief Sets gesture sensor gain
* @param gain
* Gain (APDS9960_GAIN_1, APDS9960_GAIN_2, APDS9960_GAIN_4,
* APDS9960_GAIN_8)
*/
void Adafruit_APDS9960::setGestureGain(uint8_t gain) {
_gconf2.GGAIN = gain;
this->write8(APDS9960_GCONF2, _gconf2.get());
}
/*!
* @brief Sets gesture sensor threshold
* @param thresh
* Threshold
*/
void Adafruit_APDS9960::setGestureProximityThreshold(uint8_t thresh) {
this->write8(APDS9960_GPENTH, thresh);
}
/*!
* @brief Sets gesture sensor offset
* @param offset_up
* Up offset
* @param offset_down
* Down offset
* @param offset_left
* Left offset
* @param offset_right
* Right offset
*/
void Adafruit_APDS9960::setGestureOffset(uint8_t offset_up, uint8_t offset_down,
uint8_t offset_left,
uint8_t offset_right) {
this->write8(APDS9960_GOFFSET_U, offset_up);
this->write8(APDS9960_GOFFSET_D, offset_down);
this->write8(APDS9960_GOFFSET_L, offset_left);
this->write8(APDS9960_GOFFSET_R, offset_right);
}
/*!
* @brief Enable gesture readings on APDS9960
* @param en
* Enable (True/False)
*/
void Adafruit_APDS9960::enableGesture(boolean en) {
if (!en) {
_gconf4.GMODE = 0;
write8(APDS9960_GCONF4, _gconf4.get());
}
_enable.GEN = en;
write8(APDS9960_ENABLE, _enable.get());
resetCounts();
}
/*!
* @brief Resets gesture counts
*/
void Adafruit_APDS9960::resetCounts() {
gestCnt = 0;
UCount = 0;
DCount = 0;
LCount = 0;
RCount = 0;
}
/*!
* @brief Reads gesture
* @return Received gesture (APDS9960_DOWN APDS9960_UP, APDS9960_LEFT
* APDS9960_RIGHT)
*/
uint8_t Adafruit_APDS9960::readGesture() {
uint8_t toRead, bytesRead;
uint8_t buf[256];
unsigned long t = 0;
uint8_t gestureReceived;
while (1) {
int up_down_diff = 0;
int left_right_diff = 0;
gestureReceived = 0;
if (!gestureValid())
return 0;
delay(30);
toRead = this->read8(APDS9960_GFLVL);
// bytesRead is unused but produces sideffects needed for readGesture to work
bytesRead = this->read(APDS9960_GFIFO_U, buf, toRead);
if (abs((int)buf[0] - (int)buf[1]) > 13)
up_down_diff += (int)buf[0] - (int)buf[1];
if (abs((int)buf[2] - (int)buf[3]) > 13)
left_right_diff += (int)buf[2] - (int)buf[3];
if (up_down_diff != 0) {
if (up_down_diff < 0) {
if (DCount > 0) {
gestureReceived = APDS9960_UP;
} else
UCount++;
} else if (up_down_diff > 0) {
if (UCount > 0) {
gestureReceived = APDS9960_DOWN;
} else
DCount++;
}
}
if (left_right_diff != 0) {
if (left_right_diff < 0) {
if (RCount > 0) {
gestureReceived = APDS9960_LEFT;
} else
LCount++;
} else if (left_right_diff > 0) {
if (LCount > 0) {
gestureReceived = APDS9960_RIGHT;
} else
RCount++;
}
}
if (up_down_diff != 0 || left_right_diff != 0)
t = millis();
if (gestureReceived || millis() - t > 300) {
resetCounts();
return gestureReceived;
}
}
}
/*!
* @brief Set LED brightness for proximity/gesture
* @param drive
* LED Drive
* @param boost
* LED Boost
*/
void Adafruit_APDS9960::setLED(apds9960LedDrive_t drive,
apds9960LedBoost_t boost) {
// set BOOST
_config2.LED_BOOST = boost;
write8(APDS9960_CONFIG2, _config2.get());
_control.LDRIVE = drive;
write8(APDS9960_CONTROL, _control.get());
}
/*!
* @brief Enable proximity readings on APDS9960
* @param en
* Enable (True/False)
*/
void Adafruit_APDS9960::enableColor(boolean en) {
_enable.AEN = en;
write8(APDS9960_ENABLE, _enable.get());
}
/*!
* @brief Returns status of color data
* @return True if color data ready, False otherwise
*/
bool Adafruit_APDS9960::colorDataReady() {
_status.set(this->read8(APDS9960_STATUS));
return _status.AVALID;
}
/*!
* @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_APDS9960::getColorData(uint16_t *r, uint16_t *g, uint16_t *b,
uint16_t *c) {
*c = read16R(APDS9960_CDATAL);
*r = read16R(APDS9960_RDATAL);
*g = read16R(APDS9960_GDATAL);
*b = read16R(APDS9960_BDATAL);
}
/*!
* @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
*/
uint16_t Adafruit_APDS9960::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 Calculate ambient light values
* @param r
* Red value
* @param g
* Green value
* @param b
* Blue value
* @return LUX value
*/
uint16_t Adafruit_APDS9960::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 Enables color interrupt
*/
void Adafruit_APDS9960::enableColorInterrupt() {
_enable.AIEN = 1;
write8(APDS9960_ENABLE, _enable.get());
}
/*!
* @brief Disables color interrupt
*/
void Adafruit_APDS9960::disableColorInterrupt() {
_enable.AIEN = 0;
write8(APDS9960_ENABLE, _enable.get());
}
/*!
* @brief Clears interrupt
*/
void Adafruit_APDS9960::clearInterrupt() {
this->write(APDS9960_AICLEAR, NULL, 0);
}
/*!
* @brief Sets interrupt limits
* @param low
* Low limit
* @param high
* High limit
*/
void Adafruit_APDS9960::setIntLimits(uint16_t low, uint16_t high) {
write8(APDS9960_AILTIL, low & 0xFF);
write8(APDS9960_AILTH, low >> 8);
write8(APDS9960_AIHTL, high & 0xFF);
write8(APDS9960_AIHTH, high >> 8);
}
/*!
* @brief Writes specified value to given register
* @param reg
* Register to write to
* @param value
* Value to write
*/
void Adafruit_APDS9960::write8(byte reg, byte value) {
this->write(reg, &value, 1);
}
/*!
* @brief Reads 8 bits from specified register
* @param reg
* Register to write to
* @return Value in register
*/
uint8_t Adafruit_APDS9960::read8(byte reg) {
uint8_t ret;
this->read(reg, &ret, 1);
return ret;
}
/*!
* @brief Reads 32 bits from specified register
* @param reg
* Register to write to
* @return Value in register
*/
uint32_t Adafruit_APDS9960::read32(uint8_t reg) {
uint8_t ret[4];
this->read(reg, ret, 4);
return (ret[0] << 24) | (ret[1] << 16) | (ret[2] << 8) | ret[3];
}
/*!
* @brief Reads 16 bites from specified register
* @param reg
* Register to write to
* @return Value in register
*/
uint16_t Adafruit_APDS9960::read16(uint8_t reg) {
uint8_t ret[2];
this->read(reg, ret, 2);
return (ret[0] << 8) | ret[1];
}
/*!
* @brief Reads 16 bites from specified register
* @param reg
* Register to write to
* @return Value in register
*/
uint16_t Adafruit_APDS9960::read16R(uint8_t reg) {
uint8_t ret[2];
this->read(reg, ret, 2);
return (ret[1] << 8) | ret[0];
}
/*!
* @brief Begins I2C communication
*/
void Adafruit_APDS9960::_i2c_init() { _wire->begin(); }
/*!
* @brief Reads num bytes from specified register into a given buffer
* @param reg
* Register
* @param *buf
* Buffer
* @param num
* Number of bytes
* @return Position after reading
*/
uint8_t Adafruit_APDS9960::read(uint8_t reg, uint8_t *buf, uint8_t num) {
uint8_t pos = 0;
bool eof = false;
// on arduino we need to read in 32 byte chunks
while (pos < num && !eof) {
uint8_t read_now = min(32, num - pos);
_wire->beginTransmission((uint8_t)_i2caddr);
_wire->write((uint8_t)reg + pos);
_wire->endTransmission();
_wire->requestFrom((uint8_t)_i2caddr, read_now);
for (int i = 0; i < read_now; i++) {
if (!_wire->available()) {
eof = true;
break;
}
buf[pos] = _wire->read();
pos++;
}
}
return pos;
}
/*!
* @brief Writes num bytes from specified buffer into a given register
* @param reg
* Register
* @param *buf
* Buffer
* @param num
* Number of bytes
*/
void Adafruit_APDS9960::write(uint8_t reg, uint8_t *buf, uint8_t num) {
_wire->beginTransmission((uint8_t)_i2caddr);
_wire->write((uint8_t)reg);
_wire->write((uint8_t *)buf, num);
_wire->endTransmission();
}

View File

@ -1,531 +0,0 @@
/*!
* @file Adafruit_APDS9960.h
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2017, 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 _APDS9960_H_
#define _APDS9960_H_
#include <Arduino.h>
#include <Wire.h>
#define APDS9960_ADDRESS (0x39) /**< I2C Address */
/** I2C Registers */
enum {
APDS9960_RAM = 0x00,
APDS9960_ENABLE = 0x80,
APDS9960_ATIME = 0x81,
APDS9960_WTIME = 0x83,
APDS9960_AILTIL = 0x84,
APDS9960_AILTH = 0x85,
APDS9960_AIHTL = 0x86,
APDS9960_AIHTH = 0x87,
APDS9960_PILT = 0x89,
APDS9960_PIHT = 0x8B,
APDS9960_PERS = 0x8C,
APDS9960_CONFIG1 = 0x8D,
APDS9960_PPULSE = 0x8E,
APDS9960_CONTROL = 0x8F,
APDS9960_CONFIG2 = 0x90,
APDS9960_ID = 0x92,
APDS9960_STATUS = 0x93,
APDS9960_CDATAL = 0x94,
APDS9960_CDATAH = 0x95,
APDS9960_RDATAL = 0x96,
APDS9960_RDATAH = 0x97,
APDS9960_GDATAL = 0x98,
APDS9960_GDATAH = 0x99,
APDS9960_BDATAL = 0x9A,
APDS9960_BDATAH = 0x9B,
APDS9960_PDATA = 0x9C,
APDS9960_POFFSET_UR = 0x9D,
APDS9960_POFFSET_DL = 0x9E,
APDS9960_CONFIG3 = 0x9F,
APDS9960_GPENTH = 0xA0,
APDS9960_GEXTH = 0xA1,
APDS9960_GCONF1 = 0xA2,
APDS9960_GCONF2 = 0xA3,
APDS9960_GOFFSET_U = 0xA4,
APDS9960_GOFFSET_D = 0xA5,
APDS9960_GOFFSET_L = 0xA7,
APDS9960_GOFFSET_R = 0xA9,
APDS9960_GPULSE = 0xA6,
APDS9960_GCONF3 = 0xAA,
APDS9960_GCONF4 = 0xAB,
APDS9960_GFLVL = 0xAE,
APDS9960_GSTATUS = 0xAF,
APDS9960_IFORCE = 0xE4,
APDS9960_PICLEAR = 0xE5,
APDS9960_CICLEAR = 0xE6,
APDS9960_AICLEAR = 0xE7,
APDS9960_GFIFO_U = 0xFC,
APDS9960_GFIFO_D = 0xFD,
APDS9960_GFIFO_L = 0xFE,
APDS9960_GFIFO_R = 0xFF,
};
/** ADC gain settings */
typedef enum {
APDS9960_AGAIN_1X = 0x00, /**< No gain */
APDS9960_AGAIN_4X = 0x01, /**< 2x gain */
APDS9960_AGAIN_16X = 0x02, /**< 16x gain */
APDS9960_AGAIN_64X = 0x03 /**< 64x gain */
} apds9960AGain_t;
/** Proxmity gain settings */
typedef enum {
APDS9960_PGAIN_1X = 0x00, /**< 1x gain */
APDS9960_PGAIN_2X = 0x04, /**< 2x gain */
APDS9960_PGAIN_4X = 0x08, /**< 4x gain */
APDS9960_PGAIN_8X = 0x0C /**< 8x gain */
} apds9960PGain_t;
/** Pulse length settings */
typedef enum {
APDS9960_PPULSELEN_4US = 0x00, /**< 4uS */
APDS9960_PPULSELEN_8US = 0x40, /**< 8uS */
APDS9960_PPULSELEN_16US = 0x80, /**< 16uS */
APDS9960_PPULSELEN_32US = 0xC0 /**< 32uS */
} apds9960PPulseLen_t;
/** LED drive settings */
typedef enum {
APDS9960_LEDDRIVE_100MA = 0x00, /**< 100mA */
APDS9960_LEDDRIVE_50MA = 0x40, /**< 50mA */
APDS9960_LEDDRIVE_25MA = 0x80, /**< 25mA */
APDS9960_LEDDRIVE_12MA = 0xC0 /**< 12.5mA */
} apds9960LedDrive_t;
/** LED boost settings */
typedef enum {
APDS9960_LEDBOOST_100PCNT = 0x00, /**< 100% */
APDS9960_LEDBOOST_150PCNT = 0x10, /**< 150% */
APDS9960_LEDBOOST_200PCNT = 0x20, /**< 200% */
APDS9960_LEDBOOST_300PCNT = 0x30 /**< 300% */
} apds9960LedBoost_t;
/** Dimensions */
enum {
APDS9960_DIMENSIONS_ALL = 0x00, // All dimensions
APDS9960_DIMENSIONS_UP_DOWN = 0x01, // Up/Down dimensions
APGS9960_DIMENSIONS_LEFT_RIGHT = 0x02, // Left/Right dimensions
};
/** FIFO Interrupts */
enum {
APDS9960_GFIFO_1 = 0x00, // Generate interrupt after 1 dataset in FIFO
APDS9960_GFIFO_4 = 0x01, // Generate interrupt after 2 datasets in FIFO
APDS9960_GFIFO_8 = 0x02, // Generate interrupt after 3 datasets in FIFO
APDS9960_GFIFO_16 = 0x03, // Generate interrupt after 4 datasets in FIFO
};
/** Gesture Gain */
enum {
APDS9960_GGAIN_1 = 0x00, // Gain 1x
APDS9960_GGAIN_2 = 0x01, // Gain 2x
APDS9960_GGAIN_4 = 0x02, // Gain 4x
APDS9960_GGAIN_8 = 0x03, // Gain 8x
};
/** Pulse Lenghts */
enum {
APDS9960_GPULSE_4US = 0x00, // Pulse 4us
APDS9960_GPULSE_8US = 0x01, // Pulse 8us
APDS9960_GPULSE_16US = 0x02, // Pulse 16us
APDS9960_GPULSE_32US = 0x03, // Pulse 32us
};
#define APDS9960_UP 0x01 /**< Gesture Up */
#define APDS9960_DOWN 0x02 /**< Gesture Down */
#define APDS9960_LEFT 0x03 /**< Gesture Left */
#define APDS9960_RIGHT 0x04 /**< Gesture Right */
/*!
* @brief Class that stores state and functions for interacting with
* APDS9960 Sensor
*/
class Adafruit_APDS9960 {
public:
Adafruit_APDS9960(){};
~Adafruit_APDS9960(){};
boolean begin(uint16_t iTimeMS = 10, apds9960AGain_t = APDS9960_AGAIN_4X,
uint8_t addr = APDS9960_ADDRESS, TwoWire *theWire = &Wire);
void setADCIntegrationTime(uint16_t iTimeMS);
float getADCIntegrationTime();
void setADCGain(apds9960AGain_t gain);
apds9960AGain_t getADCGain();
void setLED(apds9960LedDrive_t drive, apds9960LedBoost_t boost);
// proximity
void enableProximity(boolean en = true);
void setProxGain(apds9960PGain_t gain);
apds9960PGain_t getProxGain();
void setProxPulse(apds9960PPulseLen_t pLen, uint8_t pulses);
void enableProximityInterrupt();
void disableProximityInterrupt();
uint8_t readProximity();
void setProximityInterruptThreshold(uint8_t low, uint8_t high,
uint8_t persistance = 4);
bool getProximityInterrupt();
// gesture
void enableGesture(boolean en = true);
bool gestureValid();
void setGestureDimensions(uint8_t dims);
void setGestureFIFOThreshold(uint8_t thresh);
void setGestureGain(uint8_t gain);
void setGestureProximityThreshold(uint8_t thresh);
void setGestureOffset(uint8_t offset_up, uint8_t offset_down,
uint8_t offset_left, uint8_t offset_right);
uint8_t readGesture();
void resetCounts();
// light & color
void enableColor(boolean en = true);
bool colorDataReady();
void getColorData(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 calculateLux(uint16_t r, uint16_t g, uint16_t b);
void enableColorInterrupt();
void disableColorInterrupt();
void clearInterrupt();
void setIntLimits(uint16_t l, uint16_t h);
// turn on/off elements
void enable(boolean en = true);
private:
uint8_t _i2caddr;
TwoWire *_wire;
uint32_t read32(uint8_t reg);
uint16_t read16(uint8_t reg);
uint16_t read16R(uint8_t reg);
void write8(byte reg, byte value);
uint8_t read8(byte reg);
uint8_t gestCnt;
uint8_t UCount;
uint8_t DCount;
uint8_t LCount;
uint8_t RCount;
uint8_t read(uint8_t reg, uint8_t *buf, uint8_t num);
void write(uint8_t reg, uint8_t *buf, uint8_t num);
void _i2c_init();
struct enable {
// power on
uint8_t PON : 1;
// ALS enable
uint8_t AEN : 1;
// Proximity detect enable
uint8_t PEN : 1;
// wait timer enable
uint8_t WEN : 1;
// ALS interrupt enable
uint8_t AIEN : 1;
// proximity interrupt enable
uint8_t PIEN : 1;
// gesture enable
uint8_t GEN : 1;
uint8_t get() {
return (GEN << 6) | (PIEN << 5) | (AIEN << 4) | (WEN << 3) | (PEN << 2) |
(AEN << 1) | PON;
};
};
struct enable _enable;
struct pers {
// ALS Interrupt Persistence. Controls rate of Clear channel interrupt to
// the host processor
uint8_t APERS : 4;
// proximity interrupt persistence, controls rate of prox interrupt to host
// processor
uint8_t PPERS : 4;
uint8_t get() { return (PPERS << 4) | APERS; };
};
pers _pers;
struct config1 {
uint8_t WLONG : 1;
uint8_t get() { return WLONG << 1; };
};
config1 _config1;
struct ppulse {
/*Proximity Pulse Count. Specifies the number of proximity pulses to be
generated on LDR. Number of pulses is set by PPULSE value plus 1.
*/
uint8_t PPULSE : 6;
// Proximity Pulse Length. Sets the LED-ON pulse width during a proximity
// LDR pulse.
uint8_t PPLEN : 2;
uint8_t get() { return (PPLEN << 6) | PPULSE; }
};
ppulse _ppulse;
struct control {
// ALS and Color gain control
uint8_t AGAIN : 2;
// proximity gain control
uint8_t PGAIN : 2;
// led drive strength
uint8_t LDRIVE : 2;
uint8_t get() { return (LDRIVE << 6) | (PGAIN << 2) | AGAIN; }
};
control _control;
struct config2 {
/* Additional LDR current during proximity and gesture LED pulses. Current
value, set by LDRIVE, is increased by the percentage of LED_BOOST.
*/
uint8_t LED_BOOST : 2;
// clear photodiode saturation int enable
uint8_t CPSIEN : 1;
// proximity saturation interrupt enable
uint8_t PSIEN : 1;
uint8_t get() {
return (PSIEN << 7) | (CPSIEN << 6) | (LED_BOOST << 4) | 1;
}
};
config2 _config2;
struct status {
/* ALS Valid. Indicates that an ALS cycle has completed since AEN was
asserted or since a read from any of the ALS/Color data registers.
*/
uint8_t AVALID : 1;
/* Proximity Valid. Indicates that a proximity cycle has completed since PEN
was asserted or since PDATA was last read. A read of PDATA automatically
clears PVALID.
*/
uint8_t PVALID : 1;
/* Gesture Interrupt. GINT is asserted when GFVLV becomes greater than
GFIFOTH or if GVALID has become asserted when GMODE transitioned to zero.
The bit is reset when FIFO is completely emptied (read).
*/
uint8_t GINT : 1;
// ALS Interrupt. This bit triggers an interrupt if AIEN in ENABLE is set.
uint8_t AINT : 1;
// Proximity Interrupt. This bit triggers an interrupt if PIEN in ENABLE is
// set.
uint8_t PINT : 1;
/* Indicates that an analog saturation event occurred during a previous
proximity or gesture cycle. Once set, this bit remains set until cleared by
clear proximity interrupt special function command (0xE5 PICLEAR) or by
disabling Prox (PEN=0). This bit triggers an interrupt if PSIEN is set.
*/
uint8_t PGSAT : 1;
/* Clear Photodiode Saturation. When asserted, the analog sensor was at the
upper end of its dynamic range. The bit can be de-asserted by sending a
Clear channel interrupt command (0xE6 CICLEAR) or by disabling the ADC
(AEN=0). This bit triggers an interrupt if CPSIEN is set.
*/
uint8_t CPSAT : 1;
void set(uint8_t data) {
AVALID = data & 0x01;
PVALID = (data >> 1) & 0x01;
GINT = (data >> 2) & 0x01;
AINT = (data >> 4) & 0x01;
PINT = (data >> 5) & 0x01;
PGSAT = (data >> 6) & 0x01;
CPSAT = (data >> 7) & 0x01;
}
};
status _status;
struct config3 {
// proximity mask
uint8_t PMASK_R : 1;
uint8_t PMASK_L : 1;
uint8_t PMASK_D : 1;
uint8_t PMASK_U : 1;
/* Sleep After Interrupt. When enabled, the device will automatically enter
low power mode when the INT pin is asserted and the state machine has
progressed to the SAI decision block. Normal operation is resumed when INT
pin is cleared over I2C.
*/
uint8_t SAI : 1;
/* Proximity Gain Compensation Enable. This bit provides gain compensation
when proximity photodiode signal is reduced as a result of sensor masking.
If only one diode of the diode pair is contributing, then only half of the
signal is available at the ADC; this results in a maximum ADC value of 127.
Enabling PCMP enables an additional gain of 2X, resulting in a maximum ADC
value of 255.
*/
uint8_t PCMP : 1;
uint8_t get() {
return (PCMP << 5) | (SAI << 4) | (PMASK_U << 3) | (PMASK_D << 2) |
(PMASK_L << 1) | PMASK_R;
}
};
config3 _config3;
struct gconf1 {
/* Gesture Exit Persistence. When a number of consecutive “gesture end”
occurrences become equal or greater to the GEPERS value, the Gesture state
machine is exited.
*/
uint8_t GEXPERS : 2;
/* Gesture Exit Mask. Controls which of the gesture detector photodiodes
(UDLR) will be included to determine a “gesture end” and subsequent exit
of the gesture state machine. Unmasked UDLR data will be compared with the
value in GTHR_OUT. Field value bits correspond to UDLR detectors.
*/
uint8_t GEXMSK : 4;
/* Gesture FIFO Threshold. This value is compared with the FIFO Level (i.e.
the number of UDLR datasets) to generate an interrupt (if enabled).
*/
uint8_t GFIFOTH : 2;
uint8_t get() { return (GFIFOTH << 6) | (GEXMSK << 2) | GEXPERS; }
};
gconf1 _gconf1;
struct gconf2 {
/* Gesture Wait Time. The GWTIME controls the amount of time in a low power
mode between gesture detection cycles.
*/
uint8_t GWTIME : 3;
// Gesture LED Drive Strength. Sets LED Drive Strength in gesture mode.
uint8_t GLDRIVE : 2;
// Gesture Gain Control. Sets the gain of the proximity receiver in gesture
// mode.
uint8_t GGAIN : 2;
uint8_t get() { return (GGAIN << 5) | (GLDRIVE << 3) | GWTIME; }
};
gconf2 _gconf2;
struct gpulse {
/* Number of Gesture Pulses. Specifies the number of pulses to be generated
on LDR. Number of pulses is set by GPULSE value plus 1.
*/
uint8_t GPULSE : 6;
// Gesture Pulse Length. Sets the LED_ON pulse width during a Gesture LDR
// Pulse.
uint8_t GPLEN : 2;
uint8_t get() { return (GPLEN << 6) | GPULSE; }
};
gpulse _gpulse;
struct gconf3 {
/* Gesture Dimension Select. Selects which gesture photodiode pairs are
enabled to gather results during gesture.
*/
uint8_t GDIMS : 2;
uint8_t get() { return GDIMS; }
};
gconf3 _gconf3;
struct gconf4 {
/* Gesture Mode. Reading this bit reports if the gesture state machine is
actively running, 1 = Gesture, 0= ALS, Proximity, Color. Writing a 1 to this
bit causes immediate entry in to the gesture state machine (as if GPENTH had
been exceeded). Writing a 0 to this bit causes exit of gesture when current
analog conversion has finished (as if GEXTH had been exceeded).
*/
uint8_t GMODE : 1;
/* Gesture interrupt enable. Gesture Interrupt Enable. When asserted, all
gesture related interrupts are unmasked.
*/
uint8_t GIEN : 2;
uint8_t get() { return (GIEN << 1) | GMODE; }
void set(uint8_t data) {
GIEN = (data >> 1) & 0x01;
GMODE = data & 0x01;
}
};
gconf4 _gconf4;
struct gstatus {
/* Gesture FIFO Data. GVALID bit is sent when GFLVL becomes greater than
GFIFOTH (i.e. FIFO has enough data to set GINT). GFIFOD is reset when GMODE
= 0 and the GFLVL=0 (i.e. All FIFO data has been read).
*/
uint8_t GVALID : 1;
/* Gesture FIFO Overflow. A setting of 1 indicates that the FIFO has filled
to capacity and that new gesture detector data has been lost.
*/
uint8_t GFOV : 1;
void set(uint8_t data) {
GFOV = (data >> 1) & 0x01;
GVALID = data & 0x01;
}
};
gstatus _gstatus;
};
#endif

View File

@ -1,18 +0,0 @@
# Adafruit APDS9960 Library [![Build Status](https://travis-ci.com/adafruit/Adafruit_APDS9960.svg?branch=master)](https://travis-ci.com/adafruit/Adafruit_APDS9960)
<a href="https://www.adafruit.com/product/3595"><img src="assets/board.jpg?raw=true" width="500px"></a>
This is the Adafruit APDS9960 Proximity, Light, RGB, and Gesture sensor Library
Tested and works great with the Adafruit APDS9960 Board
* http://www.adafruit.com/products/3595
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!
Written by Dean Miller, Limor Fried 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 APDS9960 Library" and install the library.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 285 KiB

View File

@ -1,127 +0,0 @@
# 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

@ -1,59 +0,0 @@
/***************************************************************************
This is a library for the APDS9960 digital proximity, ambient light, RGB, and gesture sensor
This sketch puts the sensor in color mode and reads the RGB and clear values.
Designed specifically to work with the Adafruit APDS9960 breakout
----> http://www.adafruit.com/products/3595
These sensors use I2C to communicate. The device's I2C address is 0x39
Adafruit invests time and resources providing this open source code,
please support Adafruit andopen-source hardware by purchasing products
from Adafruit!
Written by Dean Miller for Adafruit Industries.
BSD license, all text above must be included in any redistribution
***************************************************************************/
#include "Adafruit_APDS9960.h"
Adafruit_APDS9960 apds;
void setup() {
Serial.begin(115200);
if(!apds.begin()){
Serial.println("failed to initialize device! Please check your wiring.");
}
else Serial.println("Device initialized!");
//enable color sensign mode
apds.enableColor(true);
}
void loop() {
//create some variables to store the color data in
uint16_t r, g, b, c;
//wait for color data to be ready
while(!apds.colorDataReady()){
delay(5);
}
//get the data and print the different channels
apds.getColorData(&r, &g, &b, &c);
Serial.print("red: ");
Serial.print(r);
Serial.print(" green: ");
Serial.print(g);
Serial.print(" blue: ");
Serial.print(b);
Serial.print(" clear: ");
Serial.println(c);
Serial.println();
delay(500);
}

View File

@ -1,47 +0,0 @@
/***************************************************************************
This is a library for the APDS9960 digital proximity, ambient light, RGB, and gesture sensor
This sketch puts the sensor in gesture mode and decodes gestures.
To use this, first put your hand close to the sensor to enable gesture mode.
Then move your hand about 6" from the sensor in the up -> down, down -> up,
left -> right, or right -> left direction.
Designed specifically to work with the Adafruit APDS9960 breakout
----> http://www.adafruit.com/products/3595
These sensors use I2C to communicate. The device's I2C address is 0x39
Adafruit invests time and resources providing this open source code,
please support Adafruit andopen-source hardware by purchasing products
from Adafruit!
Written by Dean Miller for Adafruit Industries.
BSD license, all text above must be included in any redistribution
***************************************************************************/
#include "Adafruit_APDS9960.h"
Adafruit_APDS9960 apds;
// the setup function runs once when you press reset or power the board
void setup() {
Serial.begin(115200);
if(!apds.begin()){
Serial.println("failed to initialize device! Please check your wiring.");
}
else Serial.println("Device initialized!");
//gesture mode will be entered once proximity mode senses something close
apds.enableProximity(true);
apds.enableGesture(true);
}
// the loop function runs over and over again forever
void loop() {
//read a gesture from the device
uint8_t gesture = apds.readGesture();
if(gesture == APDS9960_DOWN) Serial.println("v");
if(gesture == APDS9960_UP) Serial.println("^");
if(gesture == APDS9960_LEFT) Serial.println("<");
if(gesture == APDS9960_RIGHT) Serial.println(">");
}

View File

@ -1,56 +0,0 @@
/***************************************************************************
This is a library for the APDS9960 digital proximity, ambient light, RGB, and gesture sensor
This sketch puts the sensor in proximity mode and enables the interrupt
to fire when proximity goes over a set value
Designed specifically to work with the Adafruit APDS9960 breakout
----> http://www.adafruit.com/products/3595
These sensors use I2C to communicate. The device's I2C address is 0x39
Adafruit invests time and resources providing this open source code,
please support Adafruit andopen-source hardware by purchasing products
from Adafruit!
Written by Dean Miller for Adafruit Industries.
BSD license, all text above must be included in any redistribution
***************************************************************************/
#include "Adafruit_APDS9960.h"
//the pin that the interrupt is attached to
#define INT_PIN 3
//create the APDS9960 object
Adafruit_APDS9960 apds;
void setup() {
Serial.begin(115200);
pinMode(INT_PIN, INPUT_PULLUP);
if(!apds.begin()){
Serial.println("failed to initialize device! Please check your wiring.");
}
else Serial.println("Device initialized!");
//enable proximity mode
apds.enableProximity(true);
//set the interrupt threshold to fire when proximity reading goes above 175
apds.setProximityInterruptThreshold(0, 175);
//enable the proximity interrupt
apds.enableProximityInterrupt();
}
void loop() {
//print the proximity reading when the interrupt pin goes low
if(!digitalRead(INT_PIN)){
Serial.println(apds.readProximity());
//clear the interrupt
apds.clearInterrupt();
}
}

View File

@ -1,9 +0,0 @@
name=Adafruit APDS9960 Library
version=1.1.1
author=Adafruit
maintainer=Adafruit <info@adafruit.com>
sentence=This is a library for the Adafruit APDS9960 gesture/proximity/color/light sensor.
paragraph=This is a library for the Adafruit APDS9960 gesture/proximity/color/light sensor.
category=Sensors
url=https://github.com/adafruit/Adafruit_APDS9960
architectures=*

View File

@ -1,26 +0,0 @@
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.

View File

@ -1,560 +0,0 @@
/*!
* @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/2652
*
* 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.
* See the LICENSE file for details.
*
*/
#include "Adafruit_BME280.h"
#include "Arduino.h"
#include <SPI.h>
#include <Wire.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
* @param *theSPI
* optional SPI object
*/
Adafruit_BME280::Adafruit_BME280(int8_t cspin, SPIClass *theSPI) {
_cs = cspin;
_mosi = _miso = _sck = -1;
_spi = theSPI;
}
/*!
* @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) {
bool status = false;
_i2caddr = BME280_ADDRESS;
_wire = &Wire;
status = init();
if (!status) {
_i2caddr = BME280_ADDRESS_ALTERNATE;
status = init();
}
return status;
}
/*!
* @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
_sensorID = read8(BME280_REGISTER_CHIPID);
if (_sensorID != 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);
}
/*!
* Returns Sensor ID found by init() for diagnostics
* @returns Sensor ID 0x60 for BME280, 0x56, 0x57, 0x58 BMP280
*/
uint32_t Adafruit_BME280::sensorID(void) { return _sensorID; }

View File

@ -1,339 +0,0 @@
/*!
* @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.
* See the LICENSE file for details.
*
*/
#ifndef __BME280_H__
#define __BME280_H__
#include "Arduino.h"
#include <Adafruit_Sensor.h>
#include <SPI.h>
#include <Wire.h>
/*!
* @brief default I2C address
*/
#define BME280_ADDRESS (0x77) // Primary I2C Address
/*!
* @brief alternate I2C address
*/
#define BME280_ADDRESS_ALTERNATE (0x76) // Alternate Address
/*!
* @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();
Adafruit_BME280(int8_t cspin, SPIClass *theSPI = &SPI);
Adafruit_BME280(int8_t cspin, int8_t mosipin, int8_t misopin,
int8_t sckpin);
bool begin();
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);
uint32_t sensorID(void);
protected:
TwoWire *_wire; //!< pointer to a TwoWire object
SPIClass *_spi; //!< pointer to SPI object
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; //!< I2C addr for the TwoWire interface
int32_t _sensorID; //!< ID of the BME Sensor
int32_t t_fine; //!< temperature with high resolution, stored as an attribute
//!< as this is used for temperature compensation reading
//!< humidity and pressure
int8_t _cs; //!< for the SPI interface
int8_t _mosi; //!< for the SPI interface
int8_t _miso; //!< for the SPI interface
int8_t _sck; //!< for the SPI interface
bme280_calib_data _bme280_calib; //!< here calibration data is stored
/**************************************************************************/
/*!
@brief 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; ///< inactive duration (standby time) in normal mode
// filter settings
// 000 = filter off
// 001 = 2x filter
// 010 = 4x filter
// 011 = 8x filter
// 100 and above = 16x filter
unsigned int filter : 3; ///< filter settings
// unused - don't set
unsigned int none : 1; ///< unused - don't set
unsigned int spi3w_en : 1; ///< unused - don't set
/// @return combined config register
unsigned int get() { return (t_sb << 5) | (filter << 2) | spi3w_en; }
};
config _configReg; //!< config register object
/**************************************************************************/
/*!
@brief 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; ///< temperature oversampling
// pressure oversampling
// 000 = skipped
// 001 = x1
// 010 = x2
// 011 = x4
// 100 = x8
// 101 and above = x16
unsigned int osrs_p : 3; ///< pressure oversampling
// device mode
// 00 = sleep
// 01 or 10 = forced
// 11 = normal
unsigned int mode : 2; ///< device mode
/// @return combined ctrl register
unsigned int get() { return (osrs_t << 5) | (osrs_p << 2) | mode; }
};
ctrl_meas _measReg; //!< measurement register object
/**************************************************************************/
/*!
@brief 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; ///< pressure oversampling
/// @return combined ctrl hum register
unsigned int get() { return (osrs_h); }
};
ctrl_hum _humReg; //!< hum register object
};
#endif

View File

@ -1,27 +0,0 @@
Copyright (c) 2015, Limor Fried & Kevin Townsend for 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:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* 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.
* Neither the name of Adafruit Industries 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 AND CONTRIBUTORS "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 OWNER OR CONTRIBUTORS 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.

View File

@ -1,31 +0,0 @@
# Adafruit BME280 Library [![Build Status](https://travis-ci.com/adafruit/Adafruit_BME280_Library.svg?branch=master)](https://travis-ci.com/adafruit/Adafruit_BME280_Library)
<a href="http://www.adafruit.com/products/2652"><img src="./assets/board.jpg" width="500"/></a>
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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 431 KiB

View File

@ -1,159 +0,0 @@
/***************************************************************************
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
See the LICENSE file for details.
***************************************************************************/
#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

@ -1,89 +0,0 @@
/***************************************************************************
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
See the LICENSE file for details.
***************************************************************************/
#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);
while(!Serial); // time to get serial running
Serial.println(F("BME280 test"));
unsigned 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, address, sensor ID!");
Serial.print("SensorID was: 0x"); Serial.println(bme.sensorID(),16);
Serial.print(" ID of 0xFF probably means a bad address, a BMP 180 or BMP 085\n");
Serial.print(" ID of 0x56-0x58 represents a BMP 280,\n");
Serial.print(" ID of 0x60 represents a BME 280.\n");
Serial.print(" ID of 0x61 represents a BME 680.\n");
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

@ -1,9 +0,0 @@
name=Adafruit BME280 Library
version=1.0.9
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

@ -1,493 +0,0 @@
/*!
* @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>
/*!
* @brief BMP280 constructor using i2c
* @param *theWire
* optional wire
*/
Adafruit_BMP280::Adafruit_BMP280(TwoWire *theWire) {
_wire = theWire;
temp_sensor = new Adafruit_BMP280_Temp(this);
pressure_sensor = new Adafruit_BMP280_Pressure(this);
}
/*!
* @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) {
spi_dev = new Adafruit_SPIDevice(cspin, 1000000, SPI_BITORDER_MSBFIRST,
SPI_MODE0, theSPI);
temp_sensor = new Adafruit_BMP280_Temp(this);
pressure_sensor = new Adafruit_BMP280_Pressure(this);
}
/*!
* @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) {
spi_dev = new Adafruit_SPIDevice(cspin, sckpin, misopin, mosipin);
temp_sensor = new Adafruit_BMP280_Temp(this);
pressure_sensor = new Adafruit_BMP280_Pressure(this);
}
Adafruit_BMP280::~Adafruit_BMP280(void) {
if (spi_dev)
delete spi_dev;
if (i2c_dev)
delete i2c_dev;
if (temp_sensor)
delete temp_sensor;
if (pressure_sensor)
delete pressure_sensor;
}
/*!
* 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) {
if (spi_dev == NULL) {
// I2C mode
if (i2c_dev)
delete i2c_dev;
i2c_dev = new Adafruit_I2CDevice(addr, _wire);
if (!i2c_dev->begin())
return false;
} else {
// SPI mode
if (!spi_dev->begin())
return false;
}
// check if sensor, i.e. the chip ID is correct
_sensorID = read8(BMP280_REGISTER_CHIPID);
if (_sensorID != 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) {
if (!_sensorID)
return; // begin() not called yet
_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());
}
/**************************************************************************/
/*!
@brief Writes an 8 bit value over I2C/SPI
*/
/**************************************************************************/
void Adafruit_BMP280::write8(byte reg, byte value) {
byte buffer[2];
buffer[1] = value;
if (i2c_dev) {
buffer[0] = reg;
i2c_dev->write(buffer, 2);
} else {
buffer[0] = reg & ~0x80;
spi_dev->write(buffer, 2);
}
}
/*!
* @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 buffer[1];
if (i2c_dev) {
buffer[0] = uint8_t(reg);
i2c_dev->write_then_read(buffer, 1, buffer, 1);
} else {
buffer[0] = uint8_t(reg | 0x80);
spi_dev->write_then_read(buffer, 1, buffer, 1);
}
return buffer[0];
}
/*!
* @brief Reads a 16 bit value over I2C/SPI
*/
uint16_t Adafruit_BMP280::read16(byte reg) {
uint8_t buffer[2];
if (i2c_dev) {
buffer[0] = uint8_t(reg);
i2c_dev->write_then_read(buffer, 1, buffer, 2);
} else {
buffer[0] = uint8_t(reg | 0x80);
spi_dev->write_then_read(buffer, 1, buffer, 2);
}
return uint16_t(buffer[0]) << 8 | uint16_t(buffer[1]);
}
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) {
uint8_t buffer[3];
if (i2c_dev) {
buffer[0] = uint8_t(reg);
i2c_dev->write_then_read(buffer, 1, buffer, 3);
} else {
buffer[0] = uint8_t(reg | 0x80);
spi_dev->write_then_read(buffer, 1, buffer, 3);
}
return uint32_t(buffer[0]) << 16 | uint32_t(buffer[1]) << 8 |
uint32_t(buffer[2]);
}
/*!
* @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 degrees celsius.
*/
float Adafruit_BMP280::readTemperature() {
int32_t var1, var2;
if (!_sensorID)
return NAN; // begin() not called yet
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 Pa.
*/
float Adafruit_BMP280::readPressure() {
int64_t var1, var2, p;
if (!_sensorID)
return NAN; // begin() not called yet
// 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;
}
/*!
* Calculates the pressure at sea level (QNH) from the specified altitude,
* and atmospheric pressure (QFE).
* @param altitude Altitude in m
* @param atmospheric Atmospheric pressure in hPa
* @return The approximate pressure in hPa
*/
float Adafruit_BMP280::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);
}
/*!
@brief calculates the boiling point of water by a given pressure
@param pressure pressure in hPa
@return temperature in °C
*/
float Adafruit_BMP280::waterBoilingPoint(float pressure) {
// Magnusformular for calculation of the boiling point of water at a given
// pressure
return (234.175 * log(pressure / 6.1078)) /
(17.08085 - log(pressure / 6.1078));
}
/*!
@brief Take a new measurement (only possible in forced mode)
@return true if successful, otherwise false
*/
bool 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);
return true;
}
return false;
}
/*!
* @brief Resets the chip via soft reset
*/
void Adafruit_BMP280::reset(void) {
write8(BMP280_REGISTER_SOFTRESET, MODE_SOFT_RESET_CODE);
}
/*!
* Returns Sensor ID for diagnostics
* @returns 0x61 for BME680, 0x60 for BME280, 0x56, 0x57, 0x58 for BMP280
*/
uint8_t Adafruit_BMP280::sensorID(void) { return _sensorID; };
/*!
@brief Gets the most recent sensor event from the hardware status register.
@return Sensor status as a byte.
*/
uint8_t Adafruit_BMP280::getStatus(void) {
return read8(BMP280_REGISTER_STATUS);
}
/*!
@brief Gets an Adafruit Unified Sensor object for the temp sensor component
@return Adafruit_Sensor pointer to temperature sensor
*/
Adafruit_Sensor *Adafruit_BMP280::getTemperatureSensor(void) {
return temp_sensor;
}
/*!
@brief Gets an Adafruit Unified Sensor object for the pressure sensor
component
@return Adafruit_Sensor pointer to pressure sensor
*/
Adafruit_Sensor *Adafruit_BMP280::getPressureSensor(void) {
return pressure_sensor;
}
/**************************************************************************/
/*!
@brief Gets the sensor_t data for the BMP280's temperature sensor
*/
/**************************************************************************/
void Adafruit_BMP280_Temp::getSensor(sensor_t *sensor) {
/* Clear the sensor_t object */
memset(sensor, 0, sizeof(sensor_t));
/* Insert the sensor name in the fixed length char array */
strncpy(sensor->name, "BMP280", sizeof(sensor->name) - 1);
sensor->name[sizeof(sensor->name) - 1] = 0;
sensor->version = 1;
sensor->sensor_id = _sensorID;
sensor->type = SENSOR_TYPE_AMBIENT_TEMPERATURE;
sensor->min_delay = 0;
sensor->min_value = -40.0; /* Temperature range -40 ~ +85 C */
sensor->max_value = +85.0;
sensor->resolution = 0.01; /* 0.01 C */
}
/**************************************************************************/
/*!
@brief Gets the temperature as a standard sensor event
@param event Sensor event object that will be populated
@returns True
*/
/**************************************************************************/
bool Adafruit_BMP280_Temp::getEvent(sensors_event_t *event) {
/* Clear the event */
memset(event, 0, sizeof(sensors_event_t));
event->version = sizeof(sensors_event_t);
event->sensor_id = _sensorID;
event->type = SENSOR_TYPE_AMBIENT_TEMPERATURE;
event->timestamp = millis();
event->temperature = _theBMP280->readTemperature();
return true;
}
/**************************************************************************/
/*!
@brief Gets the sensor_t data for the BMP280's pressure sensor
*/
/**************************************************************************/
void Adafruit_BMP280_Pressure::getSensor(sensor_t *sensor) {
/* Clear the sensor_t object */
memset(sensor, 0, sizeof(sensor_t));
/* Insert the sensor name in the fixed length char array */
strncpy(sensor->name, "BMP280", sizeof(sensor->name) - 1);
sensor->name[sizeof(sensor->name) - 1] = 0;
sensor->version = 1;
sensor->sensor_id = _sensorID;
sensor->type = SENSOR_TYPE_PRESSURE;
sensor->min_delay = 0;
sensor->min_value = 300.0; /* 300 ~ 1100 hPa */
sensor->max_value = 1100.0;
sensor->resolution = 0.012; /* 0.12 hPa relative */
}
/**************************************************************************/
/*!
@brief Gets the pressure as a standard sensor event
@param event Sensor event object that will be populated
@returns True
*/
/**************************************************************************/
bool Adafruit_BMP280_Pressure::getEvent(sensors_event_t *event) {
/* Clear the event */
memset(event, 0, sizeof(sensors_event_t));
event->version = sizeof(sensors_event_t);
event->sensor_id = _sensorID;
event->type = SENSOR_TYPE_PRESSURE;
event->timestamp = millis();
event->pressure = _theBMP280->readPressure() / 100; // convert Pa to hPa
return true;
}

View File

@ -1,267 +0,0 @@
/*!
* @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__
// clang-format off
#include <Arduino.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_I2CDevice.h>
#include <Adafruit_SPIDevice.h>
// clang-format on
/*!
* 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_STATUS = 0xF3,
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. */
} bmp280_calib_data;
class Adafruit_BMP280;
/** Adafruit Unified Sensor interface for temperature component of BMP280 */
class Adafruit_BMP280_Temp : public Adafruit_Sensor {
public:
/** @brief Create an Adafruit_Sensor compatible object for the temp sensor
@param parent A pointer to the BMP280 class */
Adafruit_BMP280_Temp(Adafruit_BMP280 *parent) { _theBMP280 = parent; }
bool getEvent(sensors_event_t *);
void getSensor(sensor_t *);
private:
int _sensorID = 280;
Adafruit_BMP280 *_theBMP280 = NULL;
};
/** Adafruit Unified Sensor interface for pressure component of BMP280 */
class Adafruit_BMP280_Pressure : public Adafruit_Sensor {
public:
/** @brief Create an Adafruit_Sensor compatible object for the pressure sensor
@param parent A pointer to the BMP280 class */
Adafruit_BMP280_Pressure(Adafruit_BMP280 *parent) { _theBMP280 = parent; }
bool getEvent(sensors_event_t *);
void getSensor(sensor_t *);
private:
int _sensorID = 0;
Adafruit_BMP280 *_theBMP280 = NULL;
};
/**
* 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,
/** 62.5 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);
~Adafruit_BMP280(void);
bool begin(uint8_t addr = BMP280_ADDRESS, uint8_t chipid = BMP280_CHIPID);
void reset(void);
uint8_t getStatus(void);
uint8_t sensorID(void);
float readTemperature();
float readPressure(void);
float readAltitude(float seaLevelhPa = 1013.25);
float seaLevelForAltitude(float altitude, float atmospheric);
float waterBoilingPoint(float pressure);
bool takeForcedMeasurement();
Adafruit_Sensor *getTemperatureSensor(void);
Adafruit_Sensor *getPressureSensor(void);
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);
private:
TwoWire *_wire; /**< Wire object */
Adafruit_I2CDevice *i2c_dev = NULL; ///< Pointer to I2C bus interface
Adafruit_SPIDevice *spi_dev = NULL; ///< Pointer to SPI bus interface
Adafruit_BMP280_Temp *temp_sensor = NULL;
Adafruit_BMP280_Pressure *pressure_sensor = NULL;
/** Encapsulates the config register */
struct config {
/** Initialize to power-on-reset state */
config() : t_sb(STANDBY_MS_1), filter(FILTER_OFF), none(0), spi3w_en(0) {}
/** 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 {
/** Initialize to power-on-reset state */
ctrl_meas()
: osrs_t(SAMPLING_NONE), osrs_p(SAMPLING_NONE), mode(MODE_SLEEP) {}
/** 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 = 0;
int32_t t_fine;
// int8_t _cs, _mosi, _miso, _sck;
bmp280_calib_data _bmp280_calib;
config _configReg;
ctrl_meas _measReg;
};
#endif

View File

@ -1,47 +0,0 @@
# Adafruit BMP280 Driver (Barometric Pressure Sensor) [![Build Status](https://travis-ci.com/adafruit/Adafruit_BMP280_Library.svg?branch=master)](https://travis-ci.com/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.

Before

Width:  |  Height:  |  Size: 453 KiB

View File

@ -1,72 +0,0 @@
/***************************************************************************
This is a library for the BMP280 humidity, temperature & pressure sensor
Designed specifically to work with the Adafruit BMP280 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 <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 Forced Mode Test."));
//if (!bmp.begin(BMP280_ADDRESS_ALT, BMP280_CHIPID)) {
if (!bmp.begin()) {
Serial.println(F("Could not find a valid BMP280 sensor, check wiring or "
"try a different address!"));
while (1) delay(10);
}
/* Default settings from datasheet. */
bmp.setSampling(Adafruit_BMP280::MODE_FORCED, /* 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() {
// must call this to wake sensor up and get new measurement data
// it blocks until measurement is complete
if (bmp.takeForcedMeasurement()) {
// can now print out the new measurements
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);
} else {
Serial.println("Forced measurement failed!");
}
}

View File

@ -1,71 +0,0 @@
/***************************************************************************
This is a library for the BMP280 humidity, temperature & pressure sensor
This example shows how to take Sensor Events instead of direct readings
Designed specifically to work with the Adafruit BMP280 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 and open-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>
Adafruit_BMP280 bmp; // use I2C interface
Adafruit_Sensor *bmp_temp = bmp.getTemperatureSensor();
Adafruit_Sensor *bmp_pressure = bmp.getPressureSensor();
void setup() {
Serial.begin(9600);
while ( !Serial ) delay(100); // wait for native usb
Serial.println(F("BMP280 Sensor event test"));
unsigned status;
//status = bmp.begin(BMP280_ADDRESS_ALT, BMP280_CHIPID);
status = bmp.begin();
if (!status) {
Serial.println(F("Could not find a valid BMP280 sensor, check wiring or "
"try a different address!"));
Serial.print("SensorID was: 0x"); Serial.println(bmp.sensorID(),16);
Serial.print(" ID of 0xFF probably means a bad address, a BMP 180 or BMP 085\n");
Serial.print(" ID of 0x56-0x58 represents a BMP 280,\n");
Serial.print(" ID of 0x60 represents a BME 280.\n");
Serial.print(" ID of 0x61 represents a BME 680.\n");
while (1) delay(10);
}
/* 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. */
bmp_temp->printSensorDetails();
}
void loop() {
sensors_event_t temp_event, pressure_event;
bmp_temp->getEvent(&temp_event);
bmp_pressure->getEvent(&pressure_event);
Serial.print(F("Temperature = "));
Serial.print(temp_event.temperature);
Serial.println(" *C");
Serial.print(F("Pressure = "));
Serial.print(pressure_event.pressure);
Serial.println(" hPa");
Serial.println();
delay(2000);
}

View File

@ -1,72 +0,0 @@
/***************************************************************************
This is a library for the BMP280 humidity, temperature & pressure sensor
Designed specifically to work with the Adafruit BMP280 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);
while ( !Serial ) delay(100); // wait for native usb
Serial.println(F("BMP280 test"));
unsigned status;
//status = bmp.begin(BMP280_ADDRESS_ALT, BMP280_CHIPID);
status = bmp.begin();
if (!status) {
Serial.println(F("Could not find a valid BMP280 sensor, check wiring or "
"try a different address!"));
Serial.print("SensorID was: 0x"); Serial.println(bmp.sensorID(),16);
Serial.print(" ID of 0xFF probably means a bad address, a BMP 180 or BMP 085\n");
Serial.print(" ID of 0x56-0x58 represents a BMP 280,\n");
Serial.print(" ID of 0x60 represents a BME 280.\n");
Serial.print(" ID of 0x61 represents a BME 680.\n");
while (1) delay(10);
}
/* 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

@ -1,57 +0,0 @@
#######################################
# Syntax Coloring Map for BMP280 library
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
Adafruit_BMP280 KEYWORD1
Adafruit_BMP280_Temp KEYWORD1
Adafruit_BMP280_Pressure KEYWORD1
bmp280_calib_data KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
begin KEYWORD2
reset KEYWORD2
getStatus KEYWORD2
sensorID KEYWORD2
getEvent KEYWORD2
getSensor KEYWORD2
readTemperature KEYWORD2
readPressure KEYWORD2
readAltitude KEYWORD2
seaLevelForAltitude KEYWORD2
waterBoilingPoint KEYWORD2
takeForcedMeasurement KEYWORD2
getTemperatureSensor KEYWORD2
getPressureSensor KEYWORD2
setSampling KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
SAMPLING_NONE LITERAL1
SAMPLING_X1 LITERAL1
SAMPLING_X2 LITERAL1
SAMPLING_X4 LITERAL1
SAMPLING_X8 LITERAL1
SAMPLING_X16 LITERAL1
MODE_SLEEP LITERAL1
MODE_FORCED LITERAL1
MODE_NORMAL LITERAL1
MODE_SOFT_RESET_CODE LITERAL1
FILTER_OFF LITERAL1
FILTER_X2 LITERAL1
FILTER_X4 LITERAL1
FILTER_X8 LITERAL1
FILTER_X16 LITERAL1
STANDBY_MS_1 LITERAL1
STANDBY_MS_63 LITERAL1
STANDBY_MS_125 LITERAL1
STANDBY_MS_250 LITERAL1
STANDBY_MS_500 LITERAL1
STANDBY_MS_1000 LITERAL1
STANDBY_MS_2000 LITERAL1
STANDBY_MS_4000 LITERAL1

View File

@ -1,10 +0,0 @@
name=Adafruit BMP280 Library
version=2.6.6
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=*
depends=Adafruit Unified Sensor, Adafruit BusIO

View File

@ -1,365 +0,0 @@
#include <Adafruit_BusIO_Register.h>
#if !defined(SPI_INTERFACES_COUNT) || \
(defined(SPI_INTERFACES_COUNT) && (SPI_INTERFACES_COUNT > 0))
/*!
* @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 byteorder The byte 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 byteorder,
uint8_t address_width) {
_i2cdevice = i2cdevice;
_spidevice = nullptr;
_addrwidth = address_width;
_address = reg_addr;
_byteorder = byteorder;
_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 SPI access
* @param reg_addr The address pointer value for the SPI 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 byteorder The byte 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 byteorder,
uint8_t address_width) {
_spidevice = spidevice;
_spiregtype = type;
_i2cdevice = nullptr;
_addrwidth = address_width;
_address = reg_addr;
_byteorder = byteorder;
_width = width;
}
/*!
* @brief Create a register we access over an I2C or SPI Device. This is a
* handy function because we can pass in nullptr for the unused interface,
* allowing libraries to mass-define all the registers
* @param i2cdevice The I2CDevice to use for underlying I2C access, if
* nullptr we use SPI
* @param spidevice The SPIDevice to use for underlying SPI access, if
* nullptr we use I2C
* @param reg_addr The address pointer value for the I2C/SMBus/SPI 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 byteorder The byte 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 byteorder, uint8_t address_width) {
_spidevice = spidevice;
_i2cdevice = i2cdevice;
_spiregtype = type;
_addrwidth = address_width;
_address = reg_addr;
_byteorder = byteorder;
_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 == ADDRESSED_OPCODE_BIT0_LOW_TO_WRITE) {
// very special case!
// pass the special opcode address which we set as the high byte of the
// regaddr
addrbuffer[0] =
(uint8_t)(_address >> 8) & ~0x01; // set bottom bit low to write
// the 'actual' reg addr is the second byte then
addrbuffer[1] = (uint8_t)(_address & 0xFF);
// the address appears to be a byte longer
return _spidevice->write(buffer, len, addrbuffer, _addrwidth + 1);
}
if (_spiregtype == ADDRBIT8_HIGH_TOREAD) {
addrbuffer[0] &= ~0x80;
}
if (_spiregtype == ADDRBIT8_HIGH_TOWRITE) {
addrbuffer[0] |= 0x80;
}
if (_spiregtype == AD8_HIGH_TOREAD_AD7_HIGH_TOINC) {
addrbuffer[0] &= ~0x80;
addrbuffer[0] |= 0x40;
}
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;
}
// store a copy
_cached = value;
for (int i = 0; i < numbytes; i++) {
if (_byteorder == 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 (_byteorder == LSBFIRST) {
value |= _buffer[_width - i - 1];
} else {
value |= _buffer[i];
}
}
return value;
}
/*!
* @brief Read cached data from last time we wrote to this register
* @return Returns 0xFFFFFFFF on failure, value otherwise
*/
uint32_t Adafruit_BusIO_Register::readCached(void) { return _cached; }
/*!
* @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 == ADDRESSED_OPCODE_BIT0_LOW_TO_WRITE) {
// very special case!
// pass the special opcode address which we set as the high byte of the
// regaddr
addrbuffer[0] =
(uint8_t)(_address >> 8) | 0x01; // set bottom bit high to read
// the 'actual' reg addr is the second byte then
addrbuffer[1] = (uint8_t)(_address & 0xFF);
// the address appears to be a byte longer
return _spidevice->write_then_read(addrbuffer, _addrwidth + 1, buffer,
len);
}
if (_spiregtype == ADDRBIT8_HIGH_TOREAD) {
addrbuffer[0] |= 0x80;
}
if (_spiregtype == ADDRBIT8_HIGH_TOWRITE) {
addrbuffer[0] &= ~0x80;
}
if (_spiregtype == AD8_HIGH_TOREAD_AD7_HIGH_TOINC) {
addrbuffer[0] |= 0x80 | 0x40;
}
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 (_byteorder == 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);
}
/*!
* @brief Write 4 bytes of data to the register
* @param data The 4 bytes to write
* @return True on successful write (only really useful for I2C as SPI is
* uncheckable)
*/
bool Adafruit_BusIO_RegisterBits::write(uint32_t data) {
uint32_t val = _register->read();
// mask off the data before writing
uint32_t mask = (1 << (_bits)) - 1;
data &= mask;
mask <<= _shift;
val &= ~mask; // remove the current data at that spot
val |= data << _shift; // and add in the new data
return _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; }
/*!
* @brief Set the default width of data
* @param width the default width of data read from register
*/
void Adafruit_BusIO_Register::setWidth(uint8_t width) { _width = width; }
/*!
* @brief Set register address
* @param address the address from register
*/
void Adafruit_BusIO_Register::setAddress(uint16_t address) {
_address = address;
}
/*!
* @brief Set the width of register address
* @param address_width the width for register address
*/
void Adafruit_BusIO_Register::setAddressWidth(uint16_t address_width) {
_addrwidth = address_width;
}
#endif // SPI exists

View File

@ -1,105 +0,0 @@
#ifndef Adafruit_BusIO_Register_h
#define Adafruit_BusIO_Register_h
#include <Arduino.h>
#if !defined(SPI_INTERFACES_COUNT) || \
(defined(SPI_INTERFACES_COUNT) && (SPI_INTERFACES_COUNT > 0))
#include <Adafruit_I2CDevice.h>
#include <Adafruit_SPIDevice.h>
typedef enum _Adafruit_BusIO_SPIRegType {
ADDRBIT8_HIGH_TOREAD = 0,
/*!<
* ADDRBIT8_HIGH_TOREAD
* When reading a register you must actually send the value 0x80 + register
* address to the device. e.g. To read the register 0x0B the register value
* 0x8B is sent and to write 0x0B is sent.
*/
AD8_HIGH_TOREAD_AD7_HIGH_TOINC = 1,
/*!<
* ADDRBIT8_HIGH_TOWRITE
* When writing to a register you must actually send the value 0x80 +
* the register address to the device. e.g. To write to the register 0x19 the
* register value 0x99 is sent and to read 0x19 is sent.
*/
ADDRBIT8_HIGH_TOWRITE = 2,
/*!<
* ADDRESSED_OPCODE_LOWBIT_TO_WRITE
* Used by the MCP23S series, we send 0x40 |'rd with the opcode
* Then set the lowest bit to write
*/
ADDRESSED_OPCODE_BIT0_LOW_TO_WRITE = 3,
} 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 byteorder = 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 byteorder = 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 byteorder = 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);
uint32_t readCached(void);
bool write(uint8_t *buffer, uint8_t len);
bool write(uint32_t value, uint8_t numbytes = 0);
uint8_t width(void);
void setWidth(uint8_t width);
void setAddress(uint16_t address);
void setAddressWidth(uint16_t address_width);
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, _byteorder;
uint8_t _buffer[4]; // we won't support anything larger than uint32 for
// non-buffered read
uint32_t _cached = 0;
};
/*!
* @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);
bool write(uint32_t value);
uint32_t read(void);
private:
Adafruit_BusIO_Register *_register;
uint8_t _bits, _shift;
};
#endif // SPI exists
#endif // BusIO_Register_h

View File

@ -1,313 +0,0 @@
#include "Adafruit_I2CDevice.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;
#ifdef ARDUINO_ARCH_SAMD
_maxBufferSize = 250; // as defined in Wire.h's RingBuffer
#elif defined(ESP32)
_maxBufferSize = I2C_BUFFER_LENGTH;
#else
_maxBufferSize = 32;
#endif
}
/*!
* @brief Initializes and does basic address detection
* @param addr_detect Whether we should attempt to detect the I2C address
* with a scan. 99% of sensors/devices don't mind but once in a while, they spaz
* on a scan!
* @return True if I2C initialized and a device with the addr found
*/
bool Adafruit_I2CDevice::begin(bool addr_detect) {
_wire->begin();
_begun = true;
if (addr_detect) {
return detected();
}
return true;
}
/*!
* @brief De-initialize device, turn off the Wire interface
*/
void Adafruit_I2CDevice::end(void) {
// Not all port implement Wire::end(), such as
// - ESP8266
// - AVR core without WIRE_HAS_END
// - ESP32: end() is implemented since 2.0.1 which is latest at the moment.
// Temporarily disable for now to give time for user to update.
#if !(defined(ESP8266) || \
(defined(ARDUINO_ARCH_AVR) && !defined(WIRE_HAS_END)) || \
defined(ARDUINO_ARCH_ESP32))
_wire->end();
_begun = false;
#endif
}
/*!
* @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) {
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.println(F("Detected"));
#endif
return true;
}
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.println(F("Not detected"));
#endif
return false;
}
/*!
* @brief Write a buffer or two to the I2C device. Cannot be more than
* maxBufferSize() bytes.
* @param buffer Pointer to buffer of data to write. This is const to
* ensure the content of this buffer doesn't change.
* @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 maxBufferSize() bytes. This is const to
* ensure the content of this buffer doesn't change.
* @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(const uint8_t *buffer, size_t len, bool stop,
const uint8_t *prefix_buffer,
size_t prefix_len) {
if ((len + prefix_len) > maxBufferSize()) {
// 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 != nullptr)) {
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("\tI2CWRITE @ 0x"));
DEBUG_SERIAL.print(_addr, HEX);
DEBUG_SERIAL.print(F(" :: "));
if ((prefix_len != 0) && (prefix_buffer != nullptr)) {
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 (i % 32 == 31) {
DEBUG_SERIAL.println();
}
}
if (stop) {
DEBUG_SERIAL.print("\tSTOP");
}
#endif
if (_wire->endTransmission(stop) == 0) {
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.println();
// DEBUG_SERIAL.println("Sent!");
#endif
return true;
} else {
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.println("\tFailed to send!");
#endif
return false;
}
}
/*!
* @brief Read from I2C into a buffer from the I2C device.
* Cannot be more than maxBufferSize() 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) {
size_t pos = 0;
while (pos < len) {
size_t read_len =
((len - pos) > maxBufferSize()) ? maxBufferSize() : (len - pos);
bool read_stop = (pos < (len - read_len)) ? false : stop;
if (!_read(buffer + pos, read_len, read_stop))
return false;
pos += read_len;
}
return true;
}
bool Adafruit_I2CDevice::_read(uint8_t *buffer, size_t len, bool stop) {
#if defined(TinyWireM_h)
size_t recv = _wire->requestFrom((uint8_t)_addr, (uint8_t)len);
#elif defined(ARDUINO_ARCH_MEGAAVR)
size_t recv = _wire->requestFrom(_addr, len, stop);
#else
size_t recv = _wire->requestFrom((uint8_t)_addr, (uint8_t)len, (uint8_t)stop);
#endif
if (recv != len) {
// Not enough data available to fulfill our obligation!
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.print(F("\tI2CDevice did not receive enough data: "));
DEBUG_SERIAL.println(recv);
#endif
return false;
}
for (uint16_t i = 0; i < len; i++) {
buffer[i] = _wire->read();
}
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.print(F("\tI2CREAD @ 0x"));
DEBUG_SERIAL.print(_addr, 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 Write some data, then read some data from I2C into another buffer.
* Cannot be more than maxBufferSize() 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(const 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; }
/*!
* @brief Change the I2C clock speed to desired (relies on
* underlying Wire support!
* @param desiredclk The desired I2C SCL frequency
* @return True if this platform supports changing I2C speed.
* Not necessarily that the speed was achieved!
*/
bool Adafruit_I2CDevice::setSpeed(uint32_t desiredclk) {
#if defined(__AVR_ATmega328__) || \
defined(__AVR_ATmega328P__) // fix arduino core set clock
// calculate TWBR correctly
if ((F_CPU / 18) < desiredclk) {
#ifdef DEBUG_SERIAL
Serial.println(F("I2C.setSpeed too high."));
#endif
return false;
}
uint32_t atwbr = ((F_CPU / desiredclk) - 16) / 2;
if (atwbr > 16320) {
#ifdef DEBUG_SERIAL
Serial.println(F("I2C.setSpeed too low."));
#endif
return false;
}
if (atwbr <= 255) {
atwbr /= 1;
TWSR = 0x0;
} else if (atwbr <= 1020) {
atwbr /= 4;
TWSR = 0x1;
} else if (atwbr <= 4080) {
atwbr /= 16;
TWSR = 0x2;
} else { // if (atwbr <= 16320)
atwbr /= 64;
TWSR = 0x3;
}
TWBR = atwbr;
#ifdef DEBUG_SERIAL
Serial.print(F("TWSR prescaler = "));
Serial.println(pow(4, TWSR));
Serial.print(F("TWBR = "));
Serial.println(atwbr);
#endif
return true;
#elif (ARDUINO >= 157) && !defined(ARDUINO_STM32_FEATHER) && \
!defined(TinyWireM_h)
_wire->setClock(desiredclk);
return true;
#else
(void)desiredclk;
return false;
#endif
}

View File

@ -1,36 +0,0 @@
#ifndef Adafruit_I2CDevice_h
#define Adafruit_I2CDevice_h
#include <Arduino.h>
#include <Wire.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(bool addr_detect = true);
void end(void);
bool detected(void);
bool read(uint8_t *buffer, size_t len, bool stop = true);
bool write(const uint8_t *buffer, size_t len, bool stop = true,
const uint8_t *prefix_buffer = nullptr, size_t prefix_len = 0);
bool write_then_read(const uint8_t *write_buffer, size_t write_len,
uint8_t *read_buffer, size_t read_len,
bool stop = false);
bool setSpeed(uint32_t desiredclk);
/*! @brief How many bytes we can read in a transaction
* @return The size of the Wire receive/transmit buffer */
size_t maxBufferSize() { return _maxBufferSize; }
private:
uint8_t _addr;
TwoWire *_wire;
bool _begun;
size_t _maxBufferSize;
bool _read(uint8_t *buffer, size_t len, bool stop);
};
#endif // Adafruit_I2CDevice_h

View File

@ -1,10 +0,0 @@
#ifndef _ADAFRUIT_I2C_REGISTER_H_
#define _ADAFRUIT_I2C_REGISTER_H_
#include <Adafruit_BusIO_Register.h>
#include <Arduino.h>
typedef Adafruit_BusIO_Register Adafruit_I2CRegister;
typedef Adafruit_BusIO_RegisterBits Adafruit_I2CRegisterBits;
#endif

View File

@ -1,508 +0,0 @@
#include "Adafruit_SPIDevice.h"
//#define DEBUG_SERIAL Serial
/*!
* @brief Create an SPI device with the given CS pin and settings
* @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,
BusIOBitOrder dataOrder,
uint8_t dataMode, SPIClass *theSPI) {
#ifdef BUSIO_HAS_HW_SPI
_cs = cspin;
_sck = _mosi = _miso = -1;
_spi = theSPI;
_begun = false;
_spiSetting = new SPISettings(freq, dataOrder, dataMode);
_freq = freq;
_dataOrder = dataOrder;
_dataMode = dataMode;
#else
// unused, but needed to suppress compiler warns
(void)cspin;
(void)freq;
(void)dataOrder;
(void)dataMode;
(void)theSPI;
#endif
}
/*!
* @brief Create an SPI device with the given CS pin and settings
* @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, BusIOBitOrder dataOrder,
uint8_t dataMode) {
_cs = cspin;
_sck = sckpin;
_miso = misopin;
_mosi = mosipin;
#ifdef BUSIO_USE_FAST_PINIO
csPort = (BusIO_PortReg *)portOutputRegister(digitalPinToPort(cspin));
csPinMask = digitalPinToBitMask(cspin);
if (mosipin != -1) {
mosiPort = (BusIO_PortReg *)portOutputRegister(digitalPinToPort(mosipin));
mosiPinMask = digitalPinToBitMask(mosipin);
}
if (misopin != -1) {
misoPort = (BusIO_PortReg *)portInputRegister(digitalPinToPort(misopin));
misoPinMask = digitalPinToBitMask(misopin);
}
clkPort = (BusIO_PortReg *)portOutputRegister(digitalPinToPort(sckpin));
clkPinMask = digitalPinToBitMask(sckpin);
#endif
_freq = freq;
_dataOrder = dataOrder;
_dataMode = dataMode;
_begun = false;
}
/*!
* @brief Release memory allocated in constructors
*/
Adafruit_SPIDevice::~Adafruit_SPIDevice() {
if (_spiSetting)
delete _spiSetting;
}
/*!
* @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) {
if (_cs != -1) {
pinMode(_cs, OUTPUT);
digitalWrite(_cs, HIGH);
}
if (_spi) { // hardware SPI
#ifdef BUSIO_HAS_HW_SPI
_spi->begin();
#endif
} else {
pinMode(_sck, OUTPUT);
if ((_dataMode == SPI_MODE0) || (_dataMode == SPI_MODE1)) {
// idle low on mode 0 and 1
digitalWrite(_sck, LOW);
} else {
// idle high on mode 2 or 3
digitalWrite(_sck, HIGH);
}
if (_mosi != -1) {
pinMode(_mosi, OUTPUT);
digitalWrite(_mosi, HIGH);
}
if (_miso != -1) {
pinMode(_miso, INPUT);
}
}
_begun = true;
return true;
}
/*!
* @brief Transfer (send/receive) a buffer over hard/soft SPI, without
* transaction management
* @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) {
//
// HARDWARE SPI
//
if (_spi) {
#ifdef BUSIO_HAS_HW_SPI
#if defined(SPARK)
_spi->transfer(buffer, buffer, len, nullptr);
#elif defined(STM32)
for (size_t i = 0; i < len; i++) {
_spi->transfer(buffer[i]);
}
#else
_spi->transfer(buffer, len);
#endif
return;
#endif
}
//
// SOFTWARE SPI
//
uint8_t startbit;
if (_dataOrder == SPI_BITORDER_LSBFIRST) {
startbit = 0x1;
} else {
startbit = 0x80;
}
bool towrite, lastmosi = !(buffer[0] & startbit);
uint8_t bitdelay_us = (1000000 / _freq) / 2;
for (size_t i = 0; i < len; i++) {
uint8_t reply = 0;
uint8_t send = buffer[i];
/*
Serial.print("\tSending software SPI byte 0x");
Serial.print(send, HEX);
Serial.print(" -> 0x");
*/
// Serial.print(send, HEX);
for (uint8_t b = startbit; b != 0;
b = (_dataOrder == SPI_BITORDER_LSBFIRST) ? b << 1 : b >> 1) {
if (bitdelay_us) {
delayMicroseconds(bitdelay_us);
}
if (_dataMode == SPI_MODE0 || _dataMode == SPI_MODE2) {
towrite = send & b;
if ((_mosi != -1) && (lastmosi != towrite)) {
#ifdef BUSIO_USE_FAST_PINIO
if (towrite)
*mosiPort |= mosiPinMask;
else
*mosiPort &= ~mosiPinMask;
#else
digitalWrite(_mosi, towrite);
#endif
lastmosi = towrite;
}
#ifdef BUSIO_USE_FAST_PINIO
*clkPort |= clkPinMask; // Clock high
#else
digitalWrite(_sck, HIGH);
#endif
if (bitdelay_us) {
delayMicroseconds(bitdelay_us);
}
if (_miso != -1) {
#ifdef BUSIO_USE_FAST_PINIO
if (*misoPort & misoPinMask) {
#else
if (digitalRead(_miso)) {
#endif
reply |= b;
}
}
#ifdef BUSIO_USE_FAST_PINIO
*clkPort &= ~clkPinMask; // Clock low
#else
digitalWrite(_sck, LOW);
#endif
} else { // if (_dataMode == SPI_MODE1 || _dataMode == SPI_MODE3)
#ifdef BUSIO_USE_FAST_PINIO
*clkPort |= clkPinMask; // Clock high
#else
digitalWrite(_sck, HIGH);
#endif
if (bitdelay_us) {
delayMicroseconds(bitdelay_us);
}
if (_mosi != -1) {
#ifdef BUSIO_USE_FAST_PINIO
if (send & b)
*mosiPort |= mosiPinMask;
else
*mosiPort &= ~mosiPinMask;
#else
digitalWrite(_mosi, send & b);
#endif
}
#ifdef BUSIO_USE_FAST_PINIO
*clkPort &= ~clkPinMask; // Clock low
#else
digitalWrite(_sck, LOW);
#endif
if (_miso != -1) {
#ifdef BUSIO_USE_FAST_PINIO
if (*misoPort & misoPinMask) {
#else
if (digitalRead(_miso)) {
#endif
reply |= b;
}
}
}
if (_miso != -1) {
buffer[i] = reply;
}
}
}
return;
}
/*!
* @brief Transfer (send/receive) one byte over hard/soft SPI, without
* transaction management
* @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 Manually begin a transaction (calls beginTransaction if hardware
* SPI)
*/
void Adafruit_SPIDevice::beginTransaction(void) {
if (_spi) {
#ifdef BUSIO_HAS_HW_SPI
_spi->beginTransaction(*_spiSetting);
#endif
}
}
/*!
* @brief Manually end a transaction (calls endTransaction if hardware SPI)
*/
void Adafruit_SPIDevice::endTransaction(void) {
if (_spi) {
#ifdef BUSIO_HAS_HW_SPI
_spi->endTransaction();
#endif
}
}
/*!
* @brief Assert/Deassert the CS pin if it is defined
* @param value The state the CS is set to
*/
void Adafruit_SPIDevice::setChipSelect(int value) {
if (_cs != -1) {
digitalWrite(_cs, value);
}
}
/*!
* @brief Write a buffer or two to the SPI device, with transaction
* management.
* @brief Manually begin a transaction (calls beginTransaction if hardware
* SPI) with asserting the CS pin
*/
void Adafruit_SPIDevice::beginTransactionWithAssertingCS() {
beginTransaction();
setChipSelect(LOW);
}
/*!
* @brief Manually end a transaction (calls endTransaction if hardware SPI)
* with deasserting the CS pin
*/
void Adafruit_SPIDevice::endTransactionWithDeassertingCS() {
setChipSelect(HIGH);
endTransaction();
}
/*!
* @brief Write a buffer or two to the SPI device, with transaction
* management.
* @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(const uint8_t *buffer, size_t len,
const uint8_t *prefix_buffer,
size_t prefix_len) {
beginTransactionWithAssertingCS();
// do the writing
#if defined(ARDUINO_ARCH_ESP32)
if (_spi) {
if (prefix_len > 0) {
_spi->transferBytes(prefix_buffer, nullptr, prefix_len);
}
if (len > 0) {
_spi->transferBytes(buffer, nullptr, len);
}
} else
#endif
{
for (size_t i = 0; i < prefix_len; i++) {
transfer(prefix_buffer[i]);
}
for (size_t i = 0; i < len; i++) {
transfer(buffer[i]);
}
}
endTransactionWithDeassertingCS();
#ifdef DEBUG_SERIAL
DEBUG_SERIAL.print(F("\tSPIDevice Wrote: "));
if ((prefix_len != 0) && (prefix_buffer != nullptr)) {
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 (i % 32 == 31) {
DEBUG_SERIAL.println();
}
}
DEBUG_SERIAL.println();
#endif
return true;
}
/*!
* @brief Read from SPI into a buffer from the SPI device, with transaction
* management.
* @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
beginTransactionWithAssertingCS();
transfer(buffer, len);
endTransactionWithDeassertingCS();
#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,
* with transaction management. 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(const uint8_t *write_buffer,
size_t write_len, uint8_t *read_buffer,
size_t read_len, uint8_t sendvalue) {
beginTransactionWithAssertingCS();
// do the writing
#if defined(ARDUINO_ARCH_ESP32)
if (_spi) {
if (write_len > 0) {
_spi->transferBytes(write_buffer, nullptr, write_len);
}
} else
#endif
{
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
endTransactionWithDeassertingCS();
return true;
}
/*!
* @brief Write some data and read some data at the same time from SPI
* into the same buffer, with transaction management. This is basicaly a wrapper
* for transfer() with CS-pin and transaction management. This /does/
* transmit-receive at the same time!
* @param buffer Pointer to buffer of data to write/read to/from
* @param len Number of bytes from buffer to write/read.
* @return Always returns true because there's no way to test success of SPI
* writes
*/
bool Adafruit_SPIDevice::write_and_read(uint8_t *buffer, size_t len) {
beginTransactionWithAssertingCS();
transfer(buffer, len);
endTransactionWithDeassertingCS();
return true;
}

View File

@ -1,138 +0,0 @@
#ifndef Adafruit_SPIDevice_h
#define Adafruit_SPIDevice_h
#include <Arduino.h>
#if !defined(SPI_INTERFACES_COUNT) || \
(defined(SPI_INTERFACES_COUNT) && (SPI_INTERFACES_COUNT > 0))
// HW SPI available
#include <SPI.h>
#define BUSIO_HAS_HW_SPI
#else
// SW SPI ONLY
enum { SPI_MODE0, SPI_MODE1, SPI_MODE2, _SPI_MODE4 };
typedef uint8_t SPIClass;
#endif
// some modern SPI definitions don't have BitOrder enum
#if (defined(__AVR__) && !defined(ARDUINO_ARCH_MEGAAVR)) || \
defined(ESP8266) || defined(TEENSYDUINO) || defined(SPARK) || \
defined(ARDUINO_ARCH_SPRESENSE) || defined(MEGATINYCORE) || \
defined(DXCORE) || defined(ARDUINO_AVR_ATmega4809) || \
defined(ARDUINO_AVR_ATmega4808) || defined(ARDUINO_AVR_ATmega3209) || \
defined(ARDUINO_AVR_ATmega3208) || defined(ARDUINO_AVR_ATmega1609) || \
defined(ARDUINO_AVR_ATmega1608) || defined(ARDUINO_AVR_ATmega809) || \
defined(ARDUINO_AVR_ATmega808) || defined(ARDUINO_ARCH_ARC32)
typedef enum _BitOrder {
SPI_BITORDER_MSBFIRST = MSBFIRST,
SPI_BITORDER_LSBFIRST = LSBFIRST,
} BusIOBitOrder;
#elif defined(ESP32) || defined(__ASR6501__) || defined(__ASR6502__)
// some modern SPI definitions don't have BitOrder enum and have different SPI
// mode defines
typedef enum _BitOrder {
SPI_BITORDER_MSBFIRST = SPI_MSBFIRST,
SPI_BITORDER_LSBFIRST = SPI_LSBFIRST,
} BusIOBitOrder;
#else
// Some platforms have a BitOrder enum but its named MSBFIRST/LSBFIRST
#define SPI_BITORDER_MSBFIRST MSBFIRST
#define SPI_BITORDER_LSBFIRST LSBFIRST
typedef BitOrder BusIOBitOrder;
#endif
#if defined(__IMXRT1062__) // Teensy 4.x
// *Warning* I disabled the usage of FAST_PINIO as the set/clear operations
// used in the cpp file are not atomic and can effect multiple IO pins
// and if an interrupt happens in between the time the code reads the register
// and writes out the updated value, that changes one or more other IO pins
// on that same IO port, those change will be clobbered when the updated
// values are written back. A fast version can be implemented that uses the
// ports set and clear registers which are atomic.
// typedef volatile uint32_t BusIO_PortReg;
// typedef uint32_t BusIO_PortMask;
//#define BUSIO_USE_FAST_PINIO
#elif defined(__AVR__) || defined(TEENSYDUINO)
typedef volatile uint8_t BusIO_PortReg;
typedef uint8_t BusIO_PortMask;
#define BUSIO_USE_FAST_PINIO
#elif defined(ESP8266) || defined(ESP32) || defined(__SAM3X8E__) || \
defined(ARDUINO_ARCH_SAMD)
typedef volatile uint32_t BusIO_PortReg;
typedef uint32_t BusIO_PortMask;
#define BUSIO_USE_FAST_PINIO
#elif (defined(__arm__) || defined(ARDUINO_FEATHER52)) && \
!defined(ARDUINO_ARCH_MBED) && !defined(ARDUINO_ARCH_RP2040)
typedef volatile uint32_t BusIO_PortReg;
typedef uint32_t BusIO_PortMask;
#if !defined(__ASR6501__) && !defined(__ASR6502__)
#define BUSIO_USE_FAST_PINIO
#endif
#else
#undef BUSIO_USE_FAST_PINIO
#endif
/**! The class which defines how we will talk to this device over SPI **/
class Adafruit_SPIDevice {
public:
#ifdef BUSIO_HAS_HW_SPI
Adafruit_SPIDevice(int8_t cspin, uint32_t freq = 1000000,
BusIOBitOrder dataOrder = SPI_BITORDER_MSBFIRST,
uint8_t dataMode = SPI_MODE0, SPIClass *theSPI = &SPI);
#else
Adafruit_SPIDevice(int8_t cspin, uint32_t freq = 1000000,
BusIOBitOrder dataOrder = SPI_BITORDER_MSBFIRST,
uint8_t dataMode = SPI_MODE0, SPIClass *theSPI = nullptr);
#endif
Adafruit_SPIDevice(int8_t cspin, int8_t sck, int8_t miso, int8_t mosi,
uint32_t freq = 1000000,
BusIOBitOrder dataOrder = SPI_BITORDER_MSBFIRST,
uint8_t dataMode = SPI_MODE0);
~Adafruit_SPIDevice();
bool begin(void);
bool read(uint8_t *buffer, size_t len, uint8_t sendvalue = 0xFF);
bool write(const uint8_t *buffer, size_t len,
const uint8_t *prefix_buffer = nullptr, size_t prefix_len = 0);
bool write_then_read(const uint8_t *write_buffer, size_t write_len,
uint8_t *read_buffer, size_t read_len,
uint8_t sendvalue = 0xFF);
bool write_and_read(uint8_t *buffer, size_t len);
uint8_t transfer(uint8_t send);
void transfer(uint8_t *buffer, size_t len);
void beginTransaction(void);
void endTransaction(void);
void beginTransactionWithAssertingCS();
void endTransactionWithDeassertingCS();
private:
#ifdef BUSIO_HAS_HW_SPI
SPIClass *_spi = nullptr;
SPISettings *_spiSetting = nullptr;
#else
uint8_t *_spi = nullptr;
uint8_t *_spiSetting = nullptr;
#endif
uint32_t _freq;
BusIOBitOrder _dataOrder;
uint8_t _dataMode;
void setChipSelect(int value);
int8_t _cs, _sck, _mosi, _miso;
#ifdef BUSIO_USE_FAST_PINIO
BusIO_PortReg *mosiPort, *clkPort, *misoPort, *csPort;
BusIO_PortMask mosiPinMask, misoPinMask, clkPinMask, csPinMask;
#endif
bool _begun;
};
#endif // Adafruit_SPIDevice_h

View File

@ -1,11 +0,0 @@
# Adafruit Bus IO Library
# https://github.com/adafruit/Adafruit_BusIO
# MIT License
cmake_minimum_required(VERSION 3.5)
idf_component_register(SRCS "Adafruit_I2CDevice.cpp" "Adafruit_BusIO_Register.cpp" "Adafruit_SPIDevice.cpp"
INCLUDE_DIRS "."
REQUIRES arduino)
project(Adafruit_BusIO)

View File

@ -1,21 +0,0 @@
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

@ -1,8 +0,0 @@
# Adafruit Bus IO Library [![Build Status](https://github.com/adafruit/Adafruit_BusIO/workflows/Arduino%20Library%20CI/badge.svg)](https://github.com/adafruit/Adafruit_BusIO/actions)
This is a helper library 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

@ -1 +0,0 @@
COMPONENT_ADD_INCLUDEDIRS = .

View File

@ -1,21 +0,0 @@
#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

@ -1,41 +0,0 @@
#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

@ -1,38 +0,0 @@
#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

@ -1,38 +0,0 @@
#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=0;
id_reg.read(&id);
Serial.print("ID register = 0x"); Serial.println(id, HEX);
}
void loop() {
}

View File

@ -1,29 +0,0 @@
#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

@ -1,39 +0,0 @@
#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

@ -1,192 +0,0 @@
/***************************************************
This is an example for how to use Adafruit_BusIO_RegisterBits from Adafruit_BusIO library.
Designed specifically to work with the Adafruit RTD Sensor
----> https://www.adafruit.com/products/3328
uisng a MAX31865 RTD-to-Digital Converter
----> https://datasheets.maximintegrated.com/en/ds/MAX31865.pdf
This sensor uses SPI to communicate, 4 pins are required to
interface.
A fifth pin helps to detect when a new conversion is ready.
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Example written (2020/3) by Andreas Hardtung/AnHard.
BSD license, all text above must be included in any redistribution
****************************************************/
#include <Adafruit_BusIO_Register.h>
#include <Adafruit_SPIDevice.h>
#define MAX31865_SPI_SPEED (5000000)
#define MAX31865_SPI_BITORDER (SPI_BITORDER_MSBFIRST)
#define MAX31865_SPI_MODE (SPI_MODE1)
#define MAX31865_SPI_CS (10)
#define MAX31865_READY_PIN (2)
Adafruit_SPIDevice spi_dev = Adafruit_SPIDevice( MAX31865_SPI_CS, MAX31865_SPI_SPEED, MAX31865_SPI_BITORDER, MAX31865_SPI_MODE, &SPI); // Hardware SPI
// Adafruit_SPIDevice spi_dev = Adafruit_SPIDevice( MAX31865_SPI_CS, 13, 12, 11, MAX31865_SPI_SPEED, MAX31865_SPI_BITORDER, MAX31865_SPI_MODE); // Software SPI
// MAX31865 chip related *********************************************************************************************
Adafruit_BusIO_Register config_reg = Adafruit_BusIO_Register(&spi_dev, 0x00, ADDRBIT8_HIGH_TOWRITE, 1, MSBFIRST);
Adafruit_BusIO_RegisterBits bias_bit = Adafruit_BusIO_RegisterBits(&config_reg, 1, 7);
Adafruit_BusIO_RegisterBits auto_bit = Adafruit_BusIO_RegisterBits(&config_reg, 1, 6);
Adafruit_BusIO_RegisterBits oneS_bit = Adafruit_BusIO_RegisterBits(&config_reg, 1, 5);
Adafruit_BusIO_RegisterBits wire_bit = Adafruit_BusIO_RegisterBits(&config_reg, 1, 4);
Adafruit_BusIO_RegisterBits faultT_bits = Adafruit_BusIO_RegisterBits(&config_reg, 2, 2);
Adafruit_BusIO_RegisterBits faultR_bit = Adafruit_BusIO_RegisterBits(&config_reg, 1, 1);
Adafruit_BusIO_RegisterBits fi50hz_bit = Adafruit_BusIO_RegisterBits(&config_reg, 1, 0);
Adafruit_BusIO_Register rRatio_reg = Adafruit_BusIO_Register(&spi_dev, 0x01, ADDRBIT8_HIGH_TOWRITE, 2, MSBFIRST);
Adafruit_BusIO_RegisterBits rRatio_bits = Adafruit_BusIO_RegisterBits(&rRatio_reg, 15, 1);
Adafruit_BusIO_RegisterBits fault_bit = Adafruit_BusIO_RegisterBits(&rRatio_reg, 1, 0);
Adafruit_BusIO_Register maxRratio_reg = Adafruit_BusIO_Register(&spi_dev, 0x03, ADDRBIT8_HIGH_TOWRITE, 2, MSBFIRST);
Adafruit_BusIO_RegisterBits maxRratio_bits = Adafruit_BusIO_RegisterBits(&maxRratio_reg, 15, 1);
Adafruit_BusIO_Register minRratio_reg = Adafruit_BusIO_Register(&spi_dev, 0x05, ADDRBIT8_HIGH_TOWRITE, 2, MSBFIRST);
Adafruit_BusIO_RegisterBits minRratio_bits = Adafruit_BusIO_RegisterBits(&minRratio_reg, 15, 1);
Adafruit_BusIO_Register fault_reg = Adafruit_BusIO_Register(&spi_dev, 0x07, ADDRBIT8_HIGH_TOWRITE, 1, MSBFIRST);
Adafruit_BusIO_RegisterBits range_high_fault_bit = Adafruit_BusIO_RegisterBits(&fault_reg, 1, 7);
Adafruit_BusIO_RegisterBits range_low_fault_bit = Adafruit_BusIO_RegisterBits(&fault_reg, 1, 6);
Adafruit_BusIO_RegisterBits refin_high_fault_bit = Adafruit_BusIO_RegisterBits(&fault_reg, 1, 5);
Adafruit_BusIO_RegisterBits refin_low_fault_bit = Adafruit_BusIO_RegisterBits(&fault_reg, 1, 4);
Adafruit_BusIO_RegisterBits rtdin_low_fault_bit = Adafruit_BusIO_RegisterBits(&fault_reg, 1, 3);
Adafruit_BusIO_RegisterBits voltage_fault_bit = Adafruit_BusIO_RegisterBits(&fault_reg, 1, 2);
// Print the details of the configuration register.
void printConfig( void ) {
Serial.print("BIAS: "); if (bias_bit.read() ) Serial.print("ON"); else Serial.print("OFF");
Serial.print(", AUTO: "); if (auto_bit.read() ) Serial.print("ON"); else Serial.print("OFF");
Serial.print(", ONES: "); if (oneS_bit.read() ) Serial.print("ON"); else Serial.print("OFF");
Serial.print(", WIRE: "); if (wire_bit.read() ) Serial.print("3"); else Serial.print("2/4");
Serial.print(", FAULTCLEAR: "); if (faultR_bit.read() ) Serial.print("ON"); else Serial.print("OFF");
Serial.print(", "); if (fi50hz_bit.read() ) Serial.print("50HZ"); else Serial.print("60HZ");
Serial.println();
}
// Check and print faults. Then clear them.
void checkFaults( void ) {
if (fault_bit.read()) {
Serial.print("MAX: "); Serial.println(maxRratio_bits.read());
Serial.print("VAL: "); Serial.println( rRatio_bits.read());
Serial.print("MIN: "); Serial.println(minRratio_bits.read());
if (range_high_fault_bit.read() ) Serial.println("Range high fault");
if ( range_low_fault_bit.read() ) Serial.println("Range low fault");
if (refin_high_fault_bit.read() ) Serial.println("REFIN high fault");
if ( refin_low_fault_bit.read() ) Serial.println("REFIN low fault");
if ( rtdin_low_fault_bit.read() ) Serial.println("RTDIN low fault");
if ( voltage_fault_bit.read() ) Serial.println("Voltage fault");
faultR_bit.write(1); // clear fault
}
}
void setup() {
#if (MAX31865_1_READY_PIN != -1)
pinMode(MAX31865_READY_PIN ,INPUT_PULLUP);
#endif
while (!Serial) { delay(10); }
Serial.begin(115200);
Serial.println("SPI Adafruit_BusIO_RegisterBits test on MAX31865");
if (!spi_dev.begin()) {
Serial.println("Could not initialize SPI device");
while (1);
}
// Set up for automode 50Hz. We don't care about selfheating. We want the highest possible sampling rate.
auto_bit.write(0); // Don't switch filtermode while auto_mode is on.
fi50hz_bit.write(1); // Set filter to 50Hz mode.
faultR_bit.write(1); // Clear faults.
bias_bit.write(1); // In automode we want to have the bias current always on.
delay(5); // Wait until bias current settles down.
// 10.5 time constants of the input RC network is required.
// 10ms worst case for 10kω reference resistor and a 0.1µF capacitor across the RTD inputs.
// Adafruit Module has 0.1µF and only 430/4300ω So here 0.43/4.3ms
auto_bit.write(1); // Now we can set automode. Automatically starting first conversion.
// Test the READY_PIN
#if (defined( MAX31865_READY_PIN ) && (MAX31865_READY_PIN != -1))
int i = 0;
while (digitalRead(MAX31865_READY_PIN) && i++ <= 100) { delay(1); }
if (i >= 100) {
Serial.print("ERROR: Max31865 Pin detection does not work. PIN:");
Serial.println(MAX31865_READY_PIN);
}
#else
delay(100);
#endif
// Set ratio range.
// Setting the temperatures would need some more calculation - not related to Adafruit_BusIO_RegisterBits.
uint16_t ratio = rRatio_bits.read();
maxRratio_bits.write( (ratio < 0x8fffu-1000u) ? ratio + 1000u : 0x8fffu );
minRratio_bits.write( (ratio > 1000u) ? ratio - 1000u : 0u );
printConfig();
checkFaults();
}
void loop() {
#if (defined( MAX31865_READY_PIN ) && (MAX31865_1_READY_PIN != -1))
// Is conversion ready?
if (!digitalRead(MAX31865_READY_PIN))
#else
// Warant conversion is ready.
delay(21); // 21ms for 50Hz-mode. 19ms in 60Hz-mode.
#endif
{
// Read ratio, calculate temperature, scale, filter and print.
Serial.println( rRatio2C( rRatio_bits.read() ) * 100.0f, 0); // Temperature scaled by 100
// Check, print, clear faults.
checkFaults();
}
// Do something else.
//delay(15000);
}
// Module/Sensor related. Here Adafruit PT100 module with a 2_Wire PT100 Class C *****************************
float rRatio2C(uint16_t ratio) {
// A simple linear conversion.
const float R0 = 100.0f;
const float Rref = 430.0f;
const float alphaPT = 0.003850f;
const float ADCmax = (1u << 15) - 1.0f;
const float rscale = Rref / ADCmax;
// Measured temperature in boiling water 101.08°C with factor a = 1 and b = 0. Rref and MAX at about 22±2°C.
// Measured temperature in ice/water bath 0.76°C with factor a = 1 and b = 0. Rref and MAX at about 22±2°C.
//const float a = 1.0f / (alphaPT * R0);
const float a = (100.0f/101.08f) / (alphaPT * R0);
//const float b = 0.0f; // 101.08
const float b = -0.76f; // 100.32 > 101.08
return filterRing( ((ratio * rscale) - R0) * a + b );
}
// General purpose *********************************************************************************************
#define RINGLENGTH 250
float filterRing( float newVal ) {
static float ring[RINGLENGTH] = { 0.0 };
static uint8_t ringIndex = 0;
static bool ringFull = false;
if ( ringIndex == RINGLENGTH ) { ringFull = true; ringIndex = 0; }
ring[ringIndex] = newVal;
uint8_t loopEnd = (ringFull) ? RINGLENGTH : ringIndex + 1;
float ringSum = 0.0f;
for (uint8_t i = 0; i < loopEnd; i++) ringSum += ring[i];
ringIndex++;
return ringSum / loopEnd;
}

View File

@ -1,34 +0,0 @@
#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 = 0;
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 = 0;
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

@ -1,9 +0,0 @@
name=Adafruit BusIO
version=1.14.1
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

@ -1,81 +0,0 @@
#include "Adafruit_Sensor.h"
/**************************************************************************/
/*!
@brief Prints sensor information to serial console
*/
/**************************************************************************/
void Adafruit_Sensor::printSensorDetails(void) {
sensor_t sensor;
getSensor(&sensor);
Serial.println(F("------------------------------------"));
Serial.print(F("Sensor: "));
Serial.println(sensor.name);
Serial.print(F("Type: "));
switch ((sensors_type_t)sensor.type) {
case SENSOR_TYPE_ACCELEROMETER:
Serial.print(F("Acceleration (m/s2)"));
break;
case SENSOR_TYPE_MAGNETIC_FIELD:
Serial.print(F("Magnetic (uT)"));
break;
case SENSOR_TYPE_ORIENTATION:
Serial.print(F("Orientation (degrees)"));
break;
case SENSOR_TYPE_GYROSCOPE:
Serial.print(F("Gyroscopic (rad/s)"));
break;
case SENSOR_TYPE_LIGHT:
Serial.print(F("Light (lux)"));
break;
case SENSOR_TYPE_PRESSURE:
Serial.print(F("Pressure (hPa)"));
break;
case SENSOR_TYPE_PROXIMITY:
Serial.print(F("Distance (cm)"));
break;
case SENSOR_TYPE_GRAVITY:
Serial.print(F("Gravity (m/s2)"));
break;
case SENSOR_TYPE_LINEAR_ACCELERATION:
Serial.print(F("Linear Acceleration (m/s2)"));
break;
case SENSOR_TYPE_ROTATION_VECTOR:
Serial.print(F("Rotation vector"));
break;
case SENSOR_TYPE_RELATIVE_HUMIDITY:
Serial.print(F("Relative Humidity (%)"));
break;
case SENSOR_TYPE_AMBIENT_TEMPERATURE:
Serial.print(F("Ambient Temp (C)"));
break;
case SENSOR_TYPE_OBJECT_TEMPERATURE:
Serial.print(F("Object Temp (C)"));
break;
case SENSOR_TYPE_VOLTAGE:
Serial.print(F("Voltage (V)"));
break;
case SENSOR_TYPE_CURRENT:
Serial.print(F("Current (mA)"));
break;
case SENSOR_TYPE_COLOR:
Serial.print(F("Color (RGBA)"));
break;
case SENSOR_TYPE_TVOC:
Serial.print(F("Total Volatile Organic Compounds (ppb)"));
break;
}
Serial.println();
Serial.print(F("Driver Ver: "));
Serial.println(sensor.version);
Serial.print(F("Unique ID: "));
Serial.println(sensor.sensor_id);
Serial.print(F("Min Value: "));
Serial.println(sensor.min_value);
Serial.print(F("Max Value: "));
Serial.println(sensor.max_value);
Serial.print(F("Resolution: "));
Serial.println(sensor.resolution);
Serial.println(F("------------------------------------\n"));
}

View File

@ -1,190 +0,0 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software< /span>
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Update by K. Townsend (Adafruit Industries) for lighter typedefs, and
* extended sensor support to include color, voltage and current */
#ifndef _ADAFRUIT_SENSOR_H
#define _ADAFRUIT_SENSOR_H
#ifndef ARDUINO
#include <stdint.h>
#elif ARDUINO >= 100
#include "Arduino.h"
#include "Print.h"
#else
#include "WProgram.h"
#endif
/* Constants */
#define SENSORS_GRAVITY_EARTH (9.80665F) /**< Earth's gravity in m/s^2 */
#define SENSORS_GRAVITY_MOON (1.6F) /**< The moon's gravity in m/s^2 */
#define SENSORS_GRAVITY_SUN (275.0F) /**< The sun's gravity in m/s^2 */
#define SENSORS_GRAVITY_STANDARD (SENSORS_GRAVITY_EARTH)
#define SENSORS_MAGFIELD_EARTH_MAX \
(60.0F) /**< Maximum magnetic field on Earth's surface */
#define SENSORS_MAGFIELD_EARTH_MIN \
(30.0F) /**< Minimum magnetic field on Earth's surface */
#define SENSORS_PRESSURE_SEALEVELHPA \
(1013.25F) /**< Average sea level pressure is 1013.25 hPa */
#define SENSORS_DPS_TO_RADS \
(0.017453293F) /**< Degrees/s to rad/s multiplier \
*/
#define SENSORS_RADS_TO_DPS \
(57.29577793F) /**< Rad/s to degrees/s multiplier */
#define SENSORS_GAUSS_TO_MICROTESLA \
(100) /**< Gauss to micro-Tesla multiplier */
/** Sensor types */
typedef enum {
SENSOR_TYPE_ACCELEROMETER = (1), /**< Gravity + linear acceleration */
SENSOR_TYPE_MAGNETIC_FIELD = (2),
SENSOR_TYPE_ORIENTATION = (3),
SENSOR_TYPE_GYROSCOPE = (4),
SENSOR_TYPE_LIGHT = (5),
SENSOR_TYPE_PRESSURE = (6),
SENSOR_TYPE_PROXIMITY = (8),
SENSOR_TYPE_GRAVITY = (9),
SENSOR_TYPE_LINEAR_ACCELERATION =
(10), /**< Acceleration not including gravity */
SENSOR_TYPE_ROTATION_VECTOR = (11),
SENSOR_TYPE_RELATIVE_HUMIDITY = (12),
SENSOR_TYPE_AMBIENT_TEMPERATURE = (13),
SENSOR_TYPE_OBJECT_TEMPERATURE = (14),
SENSOR_TYPE_VOLTAGE = (15),
SENSOR_TYPE_CURRENT = (16),
SENSOR_TYPE_COLOR = (17),
SENSOR_TYPE_TVOC = (18)
} sensors_type_t;
/** struct sensors_vec_s is used to return a vector in a common format. */
typedef struct {
union {
float v[3]; ///< 3D vector elements
struct {
float x; ///< X component of vector
float y; ///< Y component of vector
float z; ///< Z component of vector
}; ///< Struct for holding XYZ component
/* Orientation sensors */
struct {
float roll; /**< Rotation around the longitudinal axis (the plane body, 'X
axis'). Roll is positive and increasing when moving
downward. -90 degrees <= roll <= 90 degrees */
float pitch; /**< Rotation around the lateral axis (the wing span, 'Y
axis'). Pitch is positive and increasing when moving
upwards. -180 degrees <= pitch <= 180 degrees) */
float heading; /**< Angle between the longitudinal axis (the plane body)
and magnetic north, measured clockwise when viewing from
the top of the device. 0-359 degrees */
}; ///< Struct for holding roll/pitch/heading
}; ///< Union that can hold 3D vector array, XYZ components or
///< roll/pitch/heading
int8_t status; ///< Status byte
uint8_t reserved[3]; ///< Reserved
} sensors_vec_t;
/** struct sensors_color_s is used to return color data in a common format. */
typedef struct {
union {
float c[3]; ///< Raw 3-element data
/* RGB color space */
struct {
float r; /**< Red component */
float g; /**< Green component */
float b; /**< Blue component */
}; ///< RGB data in floating point notation
}; ///< Union of various ways to describe RGB colorspace
uint32_t rgba; /**< 24-bit RGBA value */
} sensors_color_t;
/* Sensor event (36 bytes) */
/** struct sensor_event_s is used to provide a single sensor event in a common
* format. */
typedef struct {
int32_t version; /**< must be sizeof(struct sensors_event_t) */
int32_t sensor_id; /**< unique sensor identifier */
int32_t type; /**< sensor type */
int32_t reserved0; /**< reserved */
int32_t timestamp; /**< time is in milliseconds */
union {
float data[4]; ///< Raw data
sensors_vec_t acceleration; /**< acceleration values are in meter per second
per second (m/s^2) */
sensors_vec_t
magnetic; /**< magnetic vector values are in micro-Tesla (uT) */
sensors_vec_t orientation; /**< orientation values are in degrees */
sensors_vec_t gyro; /**< gyroscope values are in rad/s */
float temperature; /**< temperature is in degrees centigrade (Celsius) */
float distance; /**< distance in centimeters */
float light; /**< light in SI lux units */
float pressure; /**< pressure in hectopascal (hPa) */
float relative_humidity; /**< relative humidity in percent */
float current; /**< current in milliamps (mA) */
float voltage; /**< voltage in volts (V) */
float tvoc; /**< Total Volatile Organic Compounds, in ppb */
sensors_color_t color; /**< color in RGB component values */
}; ///< Union for the wide ranges of data we can carry
} sensors_event_t;
/* Sensor details (40 bytes) */
/** struct sensor_s is used to describe basic information about a specific
* sensor. */
typedef struct {
char name[12]; /**< sensor name */
int32_t version; /**< version of the hardware + driver */
int32_t sensor_id; /**< unique sensor identifier */
int32_t type; /**< this sensor's type (ex. SENSOR_TYPE_LIGHT) */
float max_value; /**< maximum value of this sensor's value in SI units */
float min_value; /**< minimum value of this sensor's value in SI units */
float resolution; /**< smallest difference between two values reported by this
sensor */
int32_t min_delay; /**< min delay in microseconds between events. zero = not a
constant rate */
} sensor_t;
/** @brief Common sensor interface to unify various sensors.
* Intentionally modeled after sensors.h in the Android API:
* https://github.com/android/platform_hardware_libhardware/blob/master/include/hardware/sensors.h
*/
class Adafruit_Sensor {
public:
// Constructor(s)
Adafruit_Sensor() {}
virtual ~Adafruit_Sensor() {}
// These must be defined by the subclass
/*! @brief Whether we should automatically change the range (if possible) for
higher precision
@param enabled True if we will try to autorange */
virtual void enableAutoRange(bool enabled) {
(void)enabled; /* suppress unused warning */
};
/*! @brief Get the latest sensor event
@returns True if able to fetch an event */
virtual bool getEvent(sensors_event_t *) = 0;
/*! @brief Get info about the sensor itself */
virtual void getSensor(sensor_t *) = 0;
void printSensorDetails(void);
private:
bool _autoRange;
};
#endif

View File

@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -1,229 +0,0 @@
# Adafruit Unified Sensor Driver #
Many small embedded systems exist to collect data from sensors, analyse the data, and either take an appropriate action or send that sensor data to another system for processing.
One of the many challenges of embedded systems design is the fact that parts you used today may be out of production tomorrow, or system requirements may change and you may need to choose a different sensor down the road.
Creating new drivers is a relatively easy task, but integrating them into existing systems is both error prone and time consuming since sensors rarely use the exact same units of measurement.
By reducing all data to a single **sensors\_event\_t** 'type' and settling on specific, **standardised SI units** for each sensor family the same sensor types return values that are comparable with any other similar sensor. This enables you to switch sensor models with very little impact on the rest of the system, which can help mitigate some of the risks and problems of sensor availability and code reuse.
The unified sensor abstraction layer is also useful for data-logging and data-transmission since you only have one well-known type to log or transmit over the air or wire.
## Unified Sensor Drivers ##
The following drivers are based on the Adafruit Unified Sensor Driver:
**Accelerometers**
- [Adafruit\_ADXL345](https://github.com/adafruit/Adafruit_ADXL345)
- [Adafruit\_LSM303DLHC](https://github.com/adafruit/Adafruit_LSM303DLHC)
- [Adafruit\_MMA8451\_Library](https://github.com/adafruit/Adafruit_MMA8451_Library)
**Gyroscope**
- [Adafruit\_L3GD20\_U](https://github.com/adafruit/Adafruit_L3GD20_U)
**Light**
- [Adafruit\_TSL2561](https://github.com/adafruit/Adafruit_TSL2561)
- [Adafruit\_TSL2591\_Library](https://github.com/adafruit/Adafruit_TSL2591_Library)
**Magnetometers**
- [Adafruit\_LSM303DLHC](https://github.com/adafruit/Adafruit_LSM303DLHC)
- [Adafruit\_HMC5883\_Unified](https://github.com/adafruit/Adafruit_HMC5883_Unified)
**Barometric Pressure**
- [Adafruit\_BMP085\_Unified](https://github.com/adafruit/Adafruit_BMP085_Unified)
- [Adafruit\_BMP183\_Unified\_Library](https://github.com/adafruit/Adafruit_BMP183_Unified_Library)
**Humidity & Temperature**
- [DHT-sensor-library](https://github.com/adafruit/DHT-sensor-library)
**Humidity, Temperature, & Barometric Pressure**
- [Adafruit_BME280_Library](https://github.com/adafruit/Adafruit_BME280_Library/)
**Orientation**
- [Adafruit_BNO055](https://github.com/adafruit/Adafruit_BNO055)
**All in one device**
- [Adafruit_LSM9DS0](https://github.com/adafruit/Adafruit_LSM9DS0_Library) (accelerometer, gyroscope, magnetometer)
- [Adafruit_LSM9DS1](https://github.com/adafruit/Adafruit_LSM9DS1/) (accelerometer, gyroscope, magnetometer)
## How Does it Work? ##
Any driver that supports the Adafruit unified sensor abstraction layer will implement the Adafruit\_Sensor base class. There are two main typedefs and one enum defined in Adafruit_Sensor.h that are used to 'abstract' away the sensor details and values:
## Sensor Types (`sensors_type_t`)
These pre-defined sensor types are used to properly handle the two related typedefs below, and allows us determine what types of units the sensor uses, etc.
```c++
/** Sensor types */
typedef enum
{
SENSOR_TYPE_ACCELEROMETER = (1),
SENSOR_TYPE_MAGNETIC_FIELD = (2),
SENSOR_TYPE_ORIENTATION = (3),
SENSOR_TYPE_GYROSCOPE = (4),
SENSOR_TYPE_LIGHT = (5),
SENSOR_TYPE_PRESSURE = (6),
SENSOR_TYPE_PROXIMITY = (8),
SENSOR_TYPE_GRAVITY = (9),
SENSOR_TYPE_LINEAR_ACCELERATION = (10),
SENSOR_TYPE_ROTATION_VECTOR = (11),
SENSOR_TYPE_RELATIVE_HUMIDITY = (12),
SENSOR_TYPE_AMBIENT_TEMPERATURE = (13),
SENSOR_TYPE_VOLTAGE = (15),
SENSOR_TYPE_CURRENT = (16),
SENSOR_TYPE_COLOR = (17)
} sensors_type_t;
```
## Sensor Details (`sensor_t`)
This typedef describes the specific capabilities of this sensor, and allows us to know what sensor we are using beneath the abstraction layer.
```c++
/* Sensor details (40 bytes) */
/** struct sensor_s is used to describe basic information about a specific sensor. */
typedef struct
{
char name[12];
int32_t version;
int32_t sensor_id;
int32_t type;
float max_value;
float min_value;
float resolution;
int32_t min_delay;
} sensor_t;
```
The individual fields are intended to be used as follows:
- **name**: The sensor name or ID, up to a maximum of twelve characters (ex. "MPL115A2")
- **version**: The version of the sensor HW and the driver to allow us to differentiate versions of the board or driver
- **sensor\_id**: A unique sensor identifier that is used to differentiate this specific sensor instance from any others that are present on the system or in the sensor network
- **type**: The sensor type, based on **sensors\_type\_t** in sensors.h
- **max\_value**: The maximum value that this sensor can return (in the appropriate SI unit)
- **min\_value**: The minimum value that this sensor can return (in the appropriate SI unit)
- **resolution**: The smallest difference between two values that this sensor can report (in the appropriate SI unit)
- **min\_delay**: The minimum delay in microseconds between two sensor events, or '0' if there is no constant sensor rate
## Sensor Data/Events (`sensors_event_t`)
This typedef is used to return sensor data from any sensor supported by the abstraction layer, using standard SI units and scales.
```c++
/* Sensor event (36 bytes) */
/** struct sensor_event_s is used to provide a single sensor event in a common format. */
typedef struct
{
int32_t version;
int32_t sensor_id;
int32_t type;
int32_t reserved0;
int32_t timestamp;
union
{
float data[4];
sensors_vec_t acceleration;
sensors_vec_t magnetic;
sensors_vec_t orientation;
sensors_vec_t gyro;
float temperature;
float distance;
float light;
float pressure;
float relative_humidity;
float current;
float voltage;
sensors_color_t color;
};
} sensors_event_t;
```
It includes the following fields:
- **version**: Contain 'sizeof(sensors\_event\_t)' to identify which version of the API we're using in case this changes in the future
- **sensor\_id**: A unique sensor identifier that is used to differentiate this specific sensor instance from any others that are present on the system or in the sensor network (must match the sensor\_id value in the corresponding sensor\_t enum above!)
- **type**: the sensor type, based on **sensors\_type\_t** in sensors.h
- **timestamp**: time in milliseconds when the sensor value was read
- **data[4]**: An array of four 32-bit values that allows us to encapsulate any type of sensor data via a simple union (further described below)
## Required Functions
In addition to the two standard types and the sensor type enum, all drivers based on Adafruit_Sensor must also implement the following two functions:
```c++
bool getEvent(sensors_event_t*);
```
Calling this function will populate the supplied sensors\_event\_t reference with the latest available sensor data. You should call this function as often as you want to update your data.
```c++
void getSensor(sensor_t*);
```
Calling this function will provide some basic information about the sensor (the sensor name, driver version, min and max values, etc.
## Standardised SI values for `sensors_event_t`
A key part of the abstraction layer is the standardisation of values on SI units of a particular scale, which is accomplished via the data[4] union in sensors\_event\_t above. This 16 byte union includes fields for each main sensor type, and uses the following SI units and scales:
- **acceleration**: values are in **meter per second per second** (m/s^2)
- **magnetic**: values are in **micro-Tesla** (uT)
- **orientation**: values are in **degrees**
- **gyro**: values are in **rad/s**
- **temperature**: values in **degrees centigrade** (Celsius)
- **distance**: values are in **centimeters**
- **light**: values are in **SI lux** units
- **pressure**: values are in **hectopascal** (hPa)
- **relative\_humidity**: values are in **percent**
- **current**: values are in **milliamps** (mA)
- **voltage**: values are in **volts** (V)
- **color**: values are in 0..1.0 RGB channel luminosity and 32-bit RGBA format
## The Unified Driver Abstraction Layer in Practice ##
Using the unified sensor abstraction layer is relatively easy once a compliant driver has been created.
Every compliant sensor can now be read using a single, well-known 'type' (sensors\_event\_t), and there is a standardised way of interrogating a sensor about its specific capabilities (via sensor\_t).
An example of reading the [TSL2561](https://github.com/adafruit/Adafruit_TSL2561) light sensor can be seen below:
```c++
Adafruit_TSL2561 tsl = Adafruit_TSL2561(TSL2561_ADDR_FLOAT, 12345);
...
/* Get a new sensor event */
sensors_event_t event;
tsl.getEvent(&event);
/* Display the results (light is measured in lux) */
if (event.light)
{
Serial.print(event.light); Serial.println(" lux");
}
else
{
/* If event.light = 0 lux the sensor is probably saturated
and no reliable data could be generated! */
Serial.println("Sensor overload");
}
```
Similarly, we can get the basic technical capabilities of this sensor with the following code:
```c++
sensor_t sensor;
sensor_t sensor;
tsl.getSensor(&sensor);
/* Display the sensor details */
Serial.println("------------------------------------");
Serial.print ("Sensor: "); Serial.println(sensor.name);
Serial.print ("Driver Ver: "); Serial.println(sensor.version);
Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id);
Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println(" lux");
Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println(" lux");
Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println(" lux");
Serial.println("------------------------------------");
Serial.println("");
```

View File

@ -1,153 +0,0 @@
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_ADXL343.h>
/* Assign a unique ID to this sensor at the same time */
/* Uncomment following line for default Wire bus */
Adafruit_ADXL343 accel = Adafruit_ADXL343(12345);
/* NeoTrellis M4, etc. */
/* Uncomment following line for Wire1 bus */
//Adafruit_ADXL343 accel = Adafruit_ADXL343(12345, &Wire1);
void displaySensorDetails(void)
{
sensor_t sensor;
accel.getSensor(&sensor);
Serial.println("------------------------------------");
Serial.print ("Sensor: "); Serial.println(sensor.name);
Serial.print ("Driver Ver: "); Serial.println(sensor.version);
Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id);
Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println(" m/s^2");
Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println(" m/s^2");
Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println(" m/s^2");
Serial.println("------------------------------------");
Serial.println("");
delay(500);
}
void displayDataRate(void)
{
Serial.print ("Data Rate: ");
switch(accel.getDataRate())
{
case ADXL343_DATARATE_3200_HZ:
Serial.print ("3200 ");
break;
case ADXL343_DATARATE_1600_HZ:
Serial.print ("1600 ");
break;
case ADXL343_DATARATE_800_HZ:
Serial.print ("800 ");
break;
case ADXL343_DATARATE_400_HZ:
Serial.print ("400 ");
break;
case ADXL343_DATARATE_200_HZ:
Serial.print ("200 ");
break;
case ADXL343_DATARATE_100_HZ:
Serial.print ("100 ");
break;
case ADXL343_DATARATE_50_HZ:
Serial.print ("50 ");
break;
case ADXL343_DATARATE_25_HZ:
Serial.print ("25 ");
break;
case ADXL343_DATARATE_12_5_HZ:
Serial.print ("12.5 ");
break;
case ADXL343_DATARATE_6_25HZ:
Serial.print ("6.25 ");
break;
case ADXL343_DATARATE_3_13_HZ:
Serial.print ("3.13 ");
break;
case ADXL343_DATARATE_1_56_HZ:
Serial.print ("1.56 ");
break;
case ADXL343_DATARATE_0_78_HZ:
Serial.print ("0.78 ");
break;
case ADXL343_DATARATE_0_39_HZ:
Serial.print ("0.39 ");
break;
case ADXL343_DATARATE_0_20_HZ:
Serial.print ("0.20 ");
break;
case ADXL343_DATARATE_0_10_HZ:
Serial.print ("0.10 ");
break;
default:
Serial.print ("???? ");
break;
}
Serial.println(" Hz");
}
void displayRange(void)
{
Serial.print ("Range: +/- ");
switch(accel.getRange())
{
case ADXL343_RANGE_16_G:
Serial.print ("16 ");
break;
case ADXL343_RANGE_8_G:
Serial.print ("8 ");
break;
case ADXL343_RANGE_4_G:
Serial.print ("4 ");
break;
case ADXL343_RANGE_2_G:
Serial.print ("2 ");
break;
default:
Serial.print ("?? ");
break;
}
Serial.println(" g");
}
void setup(void)
{
Serial.begin(9600);
while (!Serial);
Serial.println("Accelerometer Test"); Serial.println("");
/* Initialise the sensor */
if(!accel.begin())
{
/* There was a problem detecting the ADXL343 ... check your connections */
Serial.println("Ooops, no ADXL343 detected ... Check your wiring!");
while(1);
}
/* Set the range to whatever is appropriate for your project */
accel.setRange(ADXL343_RANGE_16_G);
// accel.setRange(ADXL343_RANGE_8_G);
// accel.setRange(ADXL343_RANGE_4_G);
// accel.setRange(ADXL343_RANGE_2_G);
/* Display some basic information on this sensor */
displaySensorDetails();
displayDataRate();
displayRange();
Serial.println("");
}
void loop(void)
{
/* Get a new sensor event */
sensors_event_t event;
accel.getEvent(&event);
/* Display the results (acceleration is measured in m/s^2) */
Serial.print("X: "); Serial.print(event.acceleration.x); Serial.print(" ");
Serial.print("Y: "); Serial.print(event.acceleration.y); Serial.print(" ");
Serial.print("Z: "); Serial.print(event.acceleration.z); Serial.print(" ");Serial.println("m/s^2 ");
delay(500);
}

View File

@ -1,11 +0,0 @@
name=Adafruit Unified Sensor
version=1.1.6
author=Adafruit <info@adafruit.com>
maintainer=Adafruit <info@adafruit.com>
sentence=Required for all Adafruit Unified Sensor based libraries.
paragraph=A unified sensor abstraction layer used by many Adafruit sensor libraries.
category=Sensors
url=https://github.com/adafruit/Adafruit_Sensor
architectures=*
includes=Adafruit_Sensor.h

View File

@ -1,176 +0,0 @@
#include "Arduino.h"
#include "ESP8266Influxdb.h"
#include <ESP8266WiFi.h>
#define DEBUG_PRINT // comment this line to disable debug print
#ifndef DEBUG_PRINT
#define DEBUG_PRINT(a)
#else
#define DEBUG_PRINT(a) (Serial.println(String(F("[Debug]: "))+(a)))
#define _DEBUG
#endif
Influxdb::Influxdb(const char *host, uint16_t port) : WiFiClient() {
_port = port;
_host = host;
}
DB_RESPONSE Influxdb::opendb(String db, String user, String password) {
_db = "db=" + db + "&u=" + user + "&p=" + password;
}
DB_RESPONSE Influxdb::opendb(String db) {
_db = "db=" + db;
}
DB_RESPONSE Influxdb::write(FIELD data) {
return write(data.postString());
}
DB_RESPONSE Influxdb::write(String data) {
if (!connect(_host, _port)) {
DEBUG_PRINT("connection failed");
_response = DB_CONNECT_FAILED;
return _response;
}
String postHead = "POST /write?" + _db + " HTTP/1.1\r\n";
postHead += "Host: " + String(_host) + ":" + String(_port) + "\r\n";
// postHead += "Content-Type: application/x-www-form-urlencoded\r\n";
postHead += "Content-Length: " + String(data.length()) + "\r\n\r\n";
DEBUG_PRINT("Writing data to " + String(_host) + ":" + String(_port));
print(postHead + data);
DEBUG_PRINT(postHead + data);
uint8_t t = 0;
// Check the reply whether writing is success or not
while (!available() && t < 200) {
delay(10);
t++;
}
if (t==200) {_response = DB_ERROR; return DB_ERROR; } // Return error if time out.
#if !defined _DEBUG
if (available()) {
_response = (findUntil("204", "\r")) ? DB_SUCCESS : DB_ERROR;
return _response;
}
#else
_response=DB_ERROR;
while (available()) {
String line = readStringUntil('\n');
if (line.substring(9,12)=="204")
_response = DB_SUCCESS;
DEBUG_PRINT("(Responsed): " + line);
}
return _response;
#endif
return DB_ERROR;
}
DB_RESPONSE Influxdb::query(String sql) {
if (!connect(_host, _port)) {
DEBUG_PRINT("connection failed");
_response = DB_CONNECT_FAILED;
return _response;
}
String url = "/query?";
#if defined _DEBUG
url += "pretty=true&";
#endif
url += _db;
url += "&q=" + URLEncode(sql);
DEBUG_PRINT("Requesting URL: ");
DEBUG_PRINT(url);
// This will send the request to the server
print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + _host +
":" + _port + "\r\n" + "Connection: close\r\n\r\n");
// Read all the lines of the reply from server and print them to Serial
uint8_t t = 0;
while (!available() && t < 200) {
delay(10);
t++;
}
if (t==200) {_response = DB_ERROR; return DB_ERROR; } // Return error if time out.
DEBUG_PRINT("Receiving....");
uint8_t i=0;
String line = readStringUntil('\n');
DEBUG_PRINT("[HEAD] " + line);
if (line.substring(9,12) == "200") {
while (available()) {
line = readStringUntil('\n');
DEBUG_PRINT("(HEAD) " + line);
if (i < 6 ) i++; else return _response;
}
_response = DB_SUCCESS;
}
else{
_response = DB_ERROR;
#if defined _DEBUG
while (available()) {
line = readStringUntil('\n');
DEBUG_PRINT("[HEAD] " + line);
}
#endif
}
return _response;
}
DB_RESPONSE Influxdb::response() {
return _response;
}
/* -----------------------------------------------*/
// Field object
/* -----------------------------------------------*/
FIELD::FIELD(String m) {
measurement = m;
}
void FIELD::empty() {
_data = "";
_tag = "";
}
void FIELD::addTag(String key, String value) {
_tag += "," + key + "=" + value;
}
void FIELD::addField(String key, float value) {
_data = (_data == "") ? (" ") : (_data += ",");
_data += key + "=" + String(value);
}
String FIELD::postString() {
// uint32_t utc = 1448114561 + millis() /1000;
return measurement + _tag + _data;
}
// URL Encode with Arduino String object
String URLEncode(String msg) {
const char *hex = "0123456789abcdef";
String encodedMsg = "";
uint16_t i;
for (i = 0; i < msg.length(); i++) {
if (('a' <= msg.charAt(i) && msg.charAt(i) <= 'z') ||
('A' <= msg.charAt(i) && msg.charAt(i) <= 'Z') ||
('0' <= msg.charAt(i) && msg.charAt(i) <= '9')) {
encodedMsg += msg.charAt(i);
} else {
encodedMsg += '%';
encodedMsg += hex[msg.charAt(i) >> 4];
encodedMsg += hex[msg.charAt(i) & 15];
}
}
return encodedMsg;
}

View File

@ -1,72 +0,0 @@
/* Influxdb library
MIT license
Written by HW Wong
*/
#ifndef INFLUXDB_H
#define INFLUXDB_H
#include "Arduino.h"
#include <ESP8266WiFi.h>
enum DB_RESPONSE {DB_SUCCESS, DB_ERROR, DB_CONNECT_FAILED};
// Url encode function
String URLEncode(String msg);
class FIELD
{
public:
FIELD(String m);
String measurement;
void addField(String key, float value);
void addTag(String key, String value);
void empty();
String postString();
private:
String _data;
String _tag;
};
class Influxdb : private WiFiClient
{
public:
Influxdb(const char* host, uint16_t port);
DB_RESPONSE opendb(String db);
DB_RESPONSE opendb(String db, String user, String password);
DB_RESPONSE write(FIELD data);
DB_RESPONSE write(String data);
DB_RESPONSE query(String sql);
//uint8_t createDatabase(char *dbname);
DB_RESPONSE response();
using WiFiClient::available;
using WiFiClient::read;
using WiFiClient::flush;
using WiFiClient::find;
using WiFiClient::findUntil;
using WiFiClient::peek;
using WiFiClient::readBytes;
using WiFiClient::readBytesUntil;
using WiFiClient::readString;
using WiFiClient::readStringUntil;
using WiFiClient::parseInt;
using WiFiClient::setTimeout;
private:
uint16_t _port;
const char* _host;
String _db;
DB_RESPONSE _response;
};
#endif

View File

@ -1,176 +0,0 @@
#include "Arduino.h"
#include "ESP8266Influxdb.h"
#include <ESP8266WiFi.h>
#define DEBUG_PRINT // comment this line to disable debug print
#ifndef DEBUG_PRINT
#define DEBUG_PRINT(a)
#else
#define DEBUG_PRINT(a) (Serial.println(String(F("[Debug]: "))+(a)))
#define _DEBUG
#endif
Influxdb::Influxdb(const char *host, uint16_t port) : WiFiClient() {
_port = port;
_host = host;
}
DB_RESPONSE Influxdb::opendb(String db, String user, String password) {
_db = "db=" + db + "&u=" + user + "&p=" + password;
}
DB_RESPONSE Influxdb::opendb(String db) {
_db = "db=" + db;
}
DB_RESPONSE Influxdb::write(FIELD data) {
return write(data.postString());
}
DB_RESPONSE Influxdb::write(String data) {
if (!connect(_host, _port)) {
DEBUG_PRINT("connection failed");
_response = DB_CONNECT_FAILED;
return _response;
}
String postHead = "POST /write?" + _db + " HTTP/1.1\r\n";
postHead += "Host: " + String(_host) + ":" + String(_port) + "\r\n";
// postHead += "Content-Type: application/x-www-form-urlencoded\r\n";
postHead += "Content-Length: " + String(data.length()) + "\r\n\r\n";
DEBUG_PRINT("Writing data to " + String(_host) + ":" + String(_port));
print(postHead + data);
DEBUG_PRINT(postHead + data);
uint8_t t = 0;
// Check the reply whether writing is success or not
while (!available() && t < 200) {
delay(10);
t++;
}
if (t==200) {_response = DB_ERROR; return DB_ERROR; } // Return error if time out.
#if !defined _DEBUG
if (available()) {
_response = (findUntil("204", "\r")) ? DB_SUCCESS : DB_ERROR;
return _response;
}
#else
_response=DB_ERROR;
while (available()) {
String line = readStringUntil('\n');
if (line.substring(9,12)=="204")
_response = DB_SUCCESS;
DEBUG_PRINT("(Responsed): " + line);
}
return _response;
#endif
return DB_ERROR;
}
DB_RESPONSE Influxdb::query(String sql) {
if (!connect(_host, _port)) {
DEBUG_PRINT("connection failed");
_response = DB_CONNECT_FAILED;
return _response;
}
String url = "/query?";
#if defined _DEBUG
url += "pretty=true&";
#endif
url += _db;
url += "&q=" + URLEncode(sql);
DEBUG_PRINT("Requesting URL: ");
DEBUG_PRINT(url);
// This will send the request to the server
print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + _host +
":" + _port + "\r\n" + "Connection: close\r\n\r\n");
// Read all the lines of the reply from server and print them to Serial
uint8_t t = 0;
while (!available() && t < 200) {
delay(10);
t++;
}
if (t==200) {_response = DB_ERROR; return DB_ERROR; } // Return error if time out.
DEBUG_PRINT("Receiving....");
uint8_t i=0;
String line = readStringUntil('\n');
DEBUG_PRINT("[HEAD] " + line);
if (line.substring(9,12) == "200") {
while (available()) {
line = readStringUntil('\n');
DEBUG_PRINT("(HEAD) " + line);
if (i < 6 ) i++; else return _response;
}
_response = DB_SUCCESS;
}
else{
_response = DB_ERROR;
#if defined _DEBUG
while (available()) {
line = readStringUntil('\n');
DEBUG_PRINT("[HEAD] " + line);
}
#endif
}
return _response;
}
DB_RESPONSE Influxdb::response() {
return _response;
}
/* -----------------------------------------------*/
// Field object
/* -----------------------------------------------*/
FIELD::FIELD(String m) {
measurement = m;
}
void FIELD::empty() {
_data = "";
_tag = "";
}
void FIELD::addTag(String key, String value) {
_tag += "," + key + "=" + value;
}
void FIELD::addField(String key, float value) {
_data = (_data == "") ? (" ") : (_data += ",");
_data += key + "=" + String(value);
}
String FIELD::postString() {
// uint32_t utc = 1448114561 + millis() /1000;
return measurement + _tag + _data;
}
// URL Encode with Arduino String object
String URLEncode(String msg) {
const char *hex = "0123456789abcdef";
String encodedMsg = "";
uint16_t i;
for (i = 0; i < msg.length(); i++) {
if (('a' <= msg.charAt(i) && msg.charAt(i) <= 'z') ||
('A' <= msg.charAt(i) && msg.charAt(i) <= 'Z') ||
('0' <= msg.charAt(i) && msg.charAt(i) <= '9')) {
encodedMsg += msg.charAt(i);
} else {
encodedMsg += '%';
encodedMsg += hex[msg.charAt(i) >> 4];
encodedMsg += hex[msg.charAt(i) & 15];
}
}
return encodedMsg;
}

View File

@ -1,72 +0,0 @@
/* Influxdb library
MIT license
Written by HW Wong
*/
#ifndef INFLUXDB_H
#define INFLUXDB_H
#include "Arduino.h"
#include <ESP8266WiFi.h>
enum DB_RESPONSE {DB_SUCCESS, DB_ERROR, DB_CONNECT_FAILED};
// Url encode function
String URLEncode(String msg);
class FIELD
{
public:
FIELD(String m);
String measurement;
void addField(String key, float value);
void addTag(String key, String value);
void empty();
String postString();
private:
String _data;
String _tag;
};
class Influxdb : private WiFiClient
{
public:
Influxdb(const char* host, uint16_t port);
DB_RESPONSE opendb(String db);
DB_RESPONSE opendb(String db, String user, String password);
DB_RESPONSE write(FIELD data);
DB_RESPONSE write(String data);
DB_RESPONSE query(String sql);
//uint8_t createDatabase(char *dbname);
DB_RESPONSE response();
using WiFiClient::available;
using WiFiClient::read;
using WiFiClient::flush;
using WiFiClient::find;
using WiFiClient::findUntil;
using WiFiClient::peek;
using WiFiClient::readBytes;
using WiFiClient::readBytesUntil;
using WiFiClient::readString;
using WiFiClient::readStringUntil;
using WiFiClient::parseInt;
using WiFiClient::setTimeout;
private:
uint16_t _port;
const char* _host;
String _db;
DB_RESPONSE _response;
};
#endif

View File

@ -1 +0,0 @@
# ESP8266Influxdb

View File

@ -1 +0,0 @@
# ESP8266Influxdb

View File

@ -1,63 +0,0 @@
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266Influxdb.h>
const char *INFLUXDB_HOST = "host_or_ip";
const uint16_t INFLUXDB_PORT = 8086;
const char *DATABASE = "dbname";
const char *DB_USER = "dbuser";
const char *DB_PASSWORD = "dbpassword";
ESP8266WiFiMulti WiFiMulti;
Influxdb influxdb(INFLUXDB_HOST, INFLUXDB_PORT);
void setup() {
Serial.begin(115200);
WiFiMulti.addAP("SSID", "PASSWORD");
while (WiFiMulti.run() != WL_CONNECTED) {
delay(100);
}
Serial.println("Ready");
influxdb.opendb(DATABASE, DB_USER, DB_PASSWORD);
}
void loop() {
// Writing data with influxdb HTTP API
// https://influxdb.com/docs/v0.9/guides/writing_data.html
Serial.println("Writing data to host " + String(INFLUXDB_HOST) + ":" +
INFLUXDB_PORT + "'s database=" + DATABASE);
String data = "analog_read,method=HTTP_API,pin=A0 value=" + String(analogRead(A0));
influxdb.write(data);
Serial.println(influxdb.response() == DB_SUCCESS ? "HTTP write success"
: "Writing failed");
// Writing data using FIELD object
// Create field object with measurment name=analog_read
FIELD dataObj("analog_read");
dataObj.addTag("method", "Field_object"); // Add method tag
dataObj.addTag("pin", "A0"); // Add pin tag
dataObj.addField("value", analogRead(A0)); // Add value field
Serial.println(influxdb.write(dataObj) == DB_SUCCESS ? "Object write success"
: "Writing failed");
// Empty field object.
dataObj.empty();
// Querying Data
// https://influxdb.com/docs/v0.9/query_language/query_syntax.html
Serial.println("Querying data ........");
String sql = "select * from analog_read order by time desc limit 2";
if (influxdb.query(sql) == DB_SUCCESS) {
while (influxdb.available()) {
String line = influxdb.readStringUntil('\n');
Serial.println(line);
}
}
else
Serial.println("Query Failed");
delay(30000);
}

View File

@ -1,24 +0,0 @@
##################################################
# Syntax Coloring Map For ESP8266 Influxdb library
##################################################
##################################################
# Datatypes (KEYWORD1)
##################################################
Influxdb KEYWORD1
FIELD KEYWORD1
DB_RESPOND KEYWORD1
##################################################
# Methods and Functions (KEYWORD2)
##################################################
addField KEYWORD2
addTag KEYWORD2
empty KEYWORD2
opendb KEYWORD2
write KEYWORD2
query KEYWORD2
postString KEYWORD2
response KEYWORD2

View File

@ -1,24 +0,0 @@
##################################################
# Syntax Coloring Map For ESP8266 Influxdb library
##################################################
##################################################
# Datatypes (KEYWORD1)
##################################################
Influxdb KEYWORD1
FIELD KEYWORD1
DB_RESPOND KEYWORD1
##################################################
# Methods and Functions (KEYWORD2)
##################################################
addField KEYWORD2
addTag KEYWORD2
empty KEYWORD2
opendb KEYWORD2
write KEYWORD2
query KEYWORD2
postString KEYWORD2
response KEYWORD2

@ -1 +0,0 @@
Subproject commit 934e701dcee743fe1ec564d0c2d64bd99e8d7bf3

View File

@ -1,148 +0,0 @@
# Changelog
## 3.12.1 [2022-08-29]
### Fixes
- [193](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/193) - Automatically adjusting point timestamp according to the setting of write precision.
## 3.12.0 [2022-03-21]
### Features
- [185](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/185) - Added diagnostic server connection state getter `bool InfluxDBClient::isConnected()`
## 3.11.0 [2022-02-18]
### Features
- [174](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/174),[181](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/181) - All API methods with a string param allow specifying string by all basic types:
- Arduino `String` class
- C `char *` or `char[]`
- Flash string using `F`,`PSTR` or `FPSTR` macros
### Fixes
- [176](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/176) - Cleared all compiler warnings
## 3.10.0 [2022-01-20]
### Features
- [167](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/167) - Added `InfluxDBClient::writeRecord(const char *record)`.
- [167](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/167) - Added possibility to disable retrying by setting `maxRetryAttempts` to zero: `client.setWriteOptions(WriteOptions().maxRetryAttempts(0));`
- [172](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/172) - Added directly streaming batch for write. It can be enabled by `InfluxDBClient::setStreamWrite(bool enable = true)`. Writing by streaming lines of batch saves RAM as it sends data without allocating a buffer. On the other hand, this way of writing is about half times slower than the classic way, when allocating the buffer for writing the whole batch.
- [172](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/172) - Allowing larger batch size, > 255.
- [173](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/173) - Added Flux query parameters. Now supported by InfluxDB Cloud only.
## 3.9.0 [2021-09-17]
### Features
- [#147](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/147) - Updated InfluxDB 2 Cloud CA root certificate to _ISRG Root X1_.
Current InfluxDB 2 Cloud CA root certificate _DST Root CA X3_ expires on September 30th 2021!
- [#157](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/157) - Added Buckets sub-client for managing buckets in InfluxDB 2.
### Fixes
- [#150](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/150) - `HTTPOptions::httpReadTimeout` is also set as the connect timeout for HTTP connection on ESP32. It also works for HTTPS connection since ESP32 Arduino Core 2.0.0.
- [#156](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/156) - Correctly rounding _writeBufferSize_, when _bufferSize/batchSize >= 256_.
- [#162](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/162) - Fixed flushing of not full buffer after the flush timeout.
### Documentation
- [#163](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/163) - More precise description of supported devices.
## 3.8.0 [2021-04-01]
### Features
- [#143](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/143) - `InfluxDBClient::setInsecure` now works also for ESP32. Requires Arduino ESP32 SDK 1.0.5 or higher
### Documentation
- [#134](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/134):
- Added untrusted connection (skipping certificate validation) info to Readme
- `SecureWrite` and `SecureBatchWrite` demos enhanced with example about using untrusted connection
- Various fixes of typos
### Fixes
- [#137](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/137) - Fixed parsing Flux response with unexpected annotations
## 3.7.0 [2020-12-24]
### Features
- [#125](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/124) - Added credentials to the InfluxDB 1.x validation endpoint (/ping). To leverage this, [enable ping authentication](https://docs.influxdata.com/influxdb/v1.8/administration/config/#ping-auth-enabled-false)
### Fixes
- [#129](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/129) - Updated InfluxDB 2 Cloud CA certificate to trust servers from all cloud providers (AWS, Azure, GCP)
## 3.6.1 [2020-11-30]
### Features
### Fixes
- [#121](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/121) - Fixed compile error in case of warning is treated as an error
- [#122](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/122) - Deleting WiFiClient instance to avoid memory leaking when the InfluxDBClient is reinitialized
- [#124](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/124) - Fixed compilation warnings
### Doc
- [#120](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/120) - Improved language wording in the Readme
## 3.6.0 [2020-11-10]
### Features
- [#117](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/117) - Added `InfluxDBClient::pointToLineProtocol(const Point& point)` for simple creation of InfluxDB line-protocol string with respect to default tags
### Fixes
- [#114](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/114) - Renamed `getRemaingRetryTime()`->`getRemainingRetryTime()`
- [#115](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/115) - Restored writing capability after a connection failure
- [#118](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/118) - Added escaping of URL params (org, bucker, V1 username and pass)
## 3.5.0 [2020-10-30]
### Features
- [#107](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/107) - Added possibility to set default tags. Use `WriteOptions::addDefaultTag()` to add a tag that will be added to each written point using the `writePoint()` function.
- [#109](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/109) - Retry strategy improvements:
- Added `canSendRequest()` function to check if retry strategy is applied
- Added `getRemaingRetryTime()` function to get wait time before another request (write/query) can be sent
- Removed applying retry wait time in case of network error
- Better explanatory error message when a request is about to be sent in the retry wait state
### Fixes
- [#108](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/108) - Added optional param for specifying decimal places of double.: `void Point::addField(String name, double value, int decimalPlaces = 2)`
- [#111](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/111) - Fixed blocked writing after another point reached max retry count (#110)
## 3.4.0 [2020-10-02]
### Features
- [#89](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/89) - ESP8266 only - Added Max Fragment Length Negotiation for TLS communication to reduce memory allocation. If server supports MFLN, it saves ~10kB. Standalone InfluxDB OSS server doesn't support MFLN, Cloud yes. To leverage MFLN for standalone OSS, a reverse proxy needs to be used.
- [#91](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/91) - Improved API for settings of write and HTTP options:
- Introduced `WriteOptions` to wrap the write related options (write precision, batch-size, etc). It offers fluent style API allowing to change only the required options. `InfluxDBClient` has overloaded `setWriteOptions(const WriteOptions& writeOptions)` method.
- Introduced `HTTPOptions` to wrap the HTTP related options (e.g. reusing connection). It offers fluent style API allowing to change only the required options. `InfluxDBClient` has `setHTTPOptions(const HTTPOptions& httpOptions)` method.
- Added possibility to set HTTP response read timeout (part of the `HTTPOptions`).
- Method `InfluxDBClient::void setWriteOptions(WritePrecision precision, uint16_t batchSize = 1, uint16_t bufferSize = 5, uint16_t flushInterval = 60, bool preserveConnection = true)` is deprecated and it will be removed in the next release.
- [#93](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/93) - Write logic improvements
- Retry on failure logic unification with other InfluxDB clients (exponential retry, max retry count 3, max retry interval)
- Better write buffer memory management
### Documentation
- [#87](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/87) - Fixed include file name in the Readme
- [#99](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/99) - Changed default InfluxDB 2 port from 9999 to 8086 (default since InfluxDB 2 RC0)
### Fixes
- [#90](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/90) - Fixed boolean type recognition of InfluxDB Flux
- [#101](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/101) - Better memory efficient point line composition
## Version 3.3.0 (2020-07-07)
- [NEW] Added possibility skip server certification validation (`setInsecure()` method)
- [NEW] Added possibility to query flux on secured InfluxDB 1.8 using V1 approach
- [NEW] `validateConnection()` can be used also for the [forward compatibility](https://docs.influxdata.com/influxdb/latest/tools/api/#influxdb-2-0-api-compatibility-endpoints) connection to InfluxDB 1.8
- [FIX] More precise default timestamp generating, up to microseconds
- [FIX] Debug compilation error
- [FIX] SecureBatchWrite compile error
## Version 3.2.0 (2020-06-09)
- [NEW] Added possibility to read data from InfluxDB using Flux queries
- [NEW] `timeSync` utility function for synchronous time synchronization using NTP
- [FIX] Properly initialize member variable (#59)
- [FIX] ASCII chars & compilation warning fix (#60)
- [Update] ESP8266 SDK 2.7+ required
## Version 3.1.3 (2020-04-27)
- [FIX] SecureWrite crash (#54)
## Version 3.1.2 (2020-04-18)
- [FIX] Compilation error on fields order (#43)
- [FIX] Invalid precision constant for microseconds (#49)
- [FIX] Write error in case point has no tags (#50)
## Version 3.1.1 (2020-04-06)
- [Updated] CA Certificate for SSL (#38)
## Version 3.1.0 (2020-03-12)
- [NEW] Added User-agent header
- [FIX] status code check when pinging an InfluxDB version 1.x instance
## Version 3.0.0 (2020-02-11)
- New API with similar keywords as other official InfluxDB clients
- Richer set of data types for fields and timestamp methods
- Advanced features, such as implicit batching, automatic retrying on server back-pressure and connection failure, along with secured communication over TLS supported for both devices and authentication
- Special characters escaping
- Backward support for original API of V1/V2

View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2018-2020 Tobias Schürg, InfluxData
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

@ -1,696 +0,0 @@
[![PlatformIO](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/workflows/PlatformIO/badge.svg)](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/actions/)
# InfluxDB Arduino Client
Simple Arduino client for writing and reading data from [InfluxDB](https://www.influxdata.com/products/influxdb-overview/), no matter whether it is a local server or InfluxDB Cloud. The library supports authentication, secure communication over TLS, [batching](#writing-in-batches), [automatic retrying](#buffer-handling-and-retrying) on server back-pressure and connection failure.
It also allows setting data in various formats, automatically escapes special characters and offers specifying timestamp in various precisions.
Library supports both [InfluxDB 2](#basic-code-for-influxdb-2) and [InfluxDB 1](#basic-code-for-influxdb-2).
This is a new implementation and the API, [original API](#original-api) is still supported.
Supported devices:
- ESP8266 with [Arduino core for ESP8266](https://github.com/esp8266/Arduino) at least version [3.0.2](https://github.com/esp8266/Arduino/releases/tag/3.0.2).
- ESP32 with [Arduino core for the ESP32](https://github.com/espressif/arduino-esp32) at least version [2.0.2](https://github.com/espressif/arduino-esp32/releases/tag/2.0.2).
This library doesn't support using those devices as a peripheral.
:warning: Only connection over internal WiFi capability is supported for now.
## Table of contents
- [InfluxDB Arduino Client](#influxdb-arduino-client)
- [Basic code for InfluxDB 2](#basic-code-for-influxdb-2)
- [Basic code for InfluxDB 1](#basic-code-for-influxdb-1)
- [Connecting to InfluxDB Cloud 2](#connecting-to-influxdb-cloud-2)
- [Writing in Batches](#writing-in-batches)
- [Timestamp](#timestamp)
- [Configure Time](#configure-time)
- [Batch Size](#batch-size)
- [Large Batch Size](#large-batch-size)
- [Write Modes](#write-modes)
- [Buffer Handling and Retrying](#buffer-handling-and-retrying)
- [Write Options](#write-options)
- [HTTP Options](#http-options)
- [Secure Connection](#secure-connection)
- [InfluxDb 2](#influxdb-2)
- [InfluxDb 1](#influxdb-1)
- [Skipping certificate validation](#skipping-certificate-validation)
- [Querying](#querying)
- [Parametrized Queries](#parametrized-queries)
- [Original API](#original-api)
- [Initialization](#initialization)
- [Sending a single measurement](#sending-a-single-measurement)
- [Write multiple data points at once](#write-multiple-data-points-at-once)
- [Troubleshooting](#troubleshooting)
- [Contributing](#contributing)
- [License](#license)
## Basic code for InfluxDB 2
After [setting up an InfluxDB 2 server](https://docs.influxdata.com/influxdb/v2.0/get-started/), first define connection parameters and a client instance:
```cpp
// InfluxDB 2 server url, e.g. http://192.168.1.48:8086 (Use: InfluxDB UI -> Load Data -> Client Libraries)
#define INFLUXDB_URL "influxdb-url"
// InfluxDB 2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
#define INFLUXDB_TOKEN "token"
// InfluxDB 2 organization name or id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
#define INFLUXDB_ORG "org"
// InfluxDB 2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets)
#define INFLUXDB_BUCKET "bucket"
// Single InfluxDB instance
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN);
```
The next step is adding data. A single row of data is represented by the `Point` class. It consists of a measurement name (like a table name), tags (which labels data) and fields ( the values to store):
```cpp
// Define data point in the measurement named 'device_status`
Point pointDevice("device_status");
// Set tags
pointDevice.addTag("device", "ESP8266");
pointDevice.addTag("SSID", WiFi.SSID());
// Add data fields
pointDevice.addField("rssi", WiFi.RSSI());
pointDevice.addField("uptime", millis());
```
And finally, write the data to the database:
```cpp
// Write data
client.writePoint(pointDevice);
```
Complete source code is available in the [BasicWrite example](examples/BasicWrite/BasicWrite.ino).
Data can be seen in the InfluxDB UI immediately. Use the [Data Explorer](https://docs.influxdata.com/influxdb/v2.0/query-data/execute-queries/data-explorer/) or create a [Dashboard](https://docs.influxdata.com/influxdb/v2.0/visualize-data/dashboards/).
## Basic code for InfluxDB 1
Using InfluxDB Arduino client for InfluxDB 1 is almost the same as for InfluxDB 2. The only difference is that InfluxDB 1 uses _database_ as classic name for data storage instead of bucket and the server is unsecured by default.
There is also a different `InfluxDBClient constructor` and `setConnectionParametersV1` function for setting the security params. Everything else remains the same.
```cpp
// InfluxDB server url, e.g. http://192.168.1.48:8086 (don't use localhost, always server name or ip address)
#define INFLUXDB_URL "influxdb-url"
// InfluxDB database name
#define INFLUXDB_DB_NAME "database"
// Single InfluxDB instance
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_DB_NAME);
// Define data point with measurement name 'device_status`
Point pointDevice("device_status");
// Set tags
pointDevice.addTag("device", "ESP8266");
pointDevice.addTag("SSID", WiFi.SSID());
// Add data
pointDevice.addField("rssi", WiFi.RSSI());
pointDevice.addField("uptime", millis());
// Write data
client.writePoint(pointDevice);
```
Complete source code is available in [BasicWrite example](examples/BasicWrite/BasicWrite.ino)
## Connecting to InfluxDB Cloud 2
Instead of setting up a local InfluxDB 2 server, it is possible to quickly [start with InfluxDB Cloud 2](https://docs.influxdata.com/influxdb/cloud/get-started/) with a [Free Plan](https://docs.influxdata.com/influxdb/cloud/account-management/pricing-plans/#free-plan).
InfluxDB Cloud uses secure communication over TLS (https). We need to tell the client to trust this connection. The paragraph bellow describes how to set trusted connection. However, InfluxDB cloud servers have only 3 months validity period. Their CA certificate, included in this library, is valid until 2035. Check [Skipping certification validation](#skipping-certificate-validation) for more details.
Connecting an Arduino client to InfluxDB Cloud server requires a few additional steps comparing to connecting to local server.
Connection parameters are almost the same as above, the only difference is that server URL now points to the InfluxDB Cloud 2, you set up after you've finished creating an InfluxDB Cloud 2 subscription. You will find the correct server URL in `InfluxDB UI -> Load Data -> Client Libraries`.
```cpp
//Include also InfluxCloud 2 CA certificate
#include <InfluxDbCloud.h>
// InfluxDB 2 server or cloud url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries)
#define INFLUXDB_URL "influxdb-url"
// InfluxDB 2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
#define INFLUXDB_TOKEN "token"
// InfluxDB 2 organization name or id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
#define INFLUXDB_ORG "org"
// InfluxDB 2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets)
#define INFLUXDB_BUCKET "bucket"
```
You need to pass an additional parameter to the client constructor, which is a certificate of the server to trust. The constant `InfluxDbCloud2CACert` contains the InfluxDB Cloud 2 CA certificate, which is predefined in this library:
```cpp
// Single InfluxDB instance
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
```
Read more about [secure connection](#secure-connection).
Additionally, time needs to be synced:
```cpp
// Synchronize time with NTP servers and set timezone
// Accurate time is necessary for certificate validation and writing in batches
// For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/
configTzTime(TZ_INFO "pool.ntp.org", "time.nis.gov");
```
Read more about time synchronization in [Configure Time](#configure-time).
Defining data and writing it to the DB is the same as in the case of [BasicWrite](#basic-code):
```cpp
// Define data point with measurement name 'device_status`
Point pointDevice("device_status");
// Set tags
pointDevice.addTag("device", "ESP8266");
pointDevice.addTag("SSID", WiFi.SSID());
// Add data
pointDevice.addField("rssi", WiFi.RSSI());
pointDevice.addField("uptime", millis());
// Write data
client.writePoint(pointDevice);
```
Complete source code is available in [SecureWrite example](examples/SecureWrite/SecureWrite.ino).
## Writing in Batches
InfluxDB client for Arduino can also write data in batches. A batch is simply a set of points that will be sent at once. To create a batch, the client will keep all points until the number of points reaches the batch size and then it will write all points at once to the InfluxDB server. This is often more efficient than writing each point separately.
### Timestamp
If using batch writes, the timestamp should be employed. Timestamp specifies the time when data was gathered and it is used in the form of a number of seconds (milliseconds, etc) from epoch (1.1.1970) UTC.
If points have no timestamp assigned, InfluxDB assigns a timestamp at the time of writing, which could happen much later than the data has been obtained, because the final batch write will happen when the batch is full (or when [flush buffer](#buffer-handling-and-retrying) is forced).
InfluxDB allows sending timestamps in various precisions - nanoseconds, microseconds, milliseconds or seconds. The milliseconds precision is usually enough for using on Arduino. The maximum available precision is microseconds. Setting the timestamp to nanoseconds will just add zeroes for microseconds fraction and will not improve timestamp accuracy.
The client has to be configured with a time precision. The default settings is to not use the timestamp, which means that the server will assign a timestamp when the data is written to the database. The `setWriteOptions` functions allows setting custom `WriteOptions` params and one of them is __write precision__:
``` cpp
// Set write precision to milliseconds. Leave other parameters default.
client.setWriteOptions(WriteOptions().writePrecision(WritePrecision::MS));
```
When a write precision is configured, the client will automatically assign the current time to the timestamp of each written point which doesn't have a timestamp assigned.
If you want to manage timestamp on your own, there are several ways to set the timestamp explicitly.
- `setTime(WritePrecision writePrecision)` - Sets the timestamp to the actual time in the desired precision. The same precision must set in WriteOptions.
- `setTime(unsigned long long timestamp)` - Sets the timestamp to an offset since the epoch. Correct precision must be set InfluxDBClient::setWriteOptions.
- `setTime(String timestamp)` - Sets the timestamp to an offset since the epoch. Correct precision must be set InfluxDBClient::setWriteOptions.
The `getTime()` method allows copying the timestamp between points.
### Configure Time
Dealing with timestamps, and also validating server or CA certificate, requires that the device has correctly set the time. This can be done with one line of code:
```cpp
// Synchronize time with NTP servers and set timezone
// Accurate time is necessary for certificate validation and writing in batches
// For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/
configTzTime("PST8PDT", "pool.ntp.org", "time.nis.gov");
```
The `configTzTime` function starts the time synchronization with NTP servers. The first parameter specifies the timezone information, which is important for distinguishing between UTC and a local timezone and for daylight saving changes.
The last two string parameters are the internet addresses of NTP servers. Check [pool.ntp.org](https://www.pool.ntp.org/zone) for address of some local NTP servers.
Timezone string details are described at [https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html](https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html).
Values for some timezones:
- Central Europe: `CET-1CEST,M3.5.0,M10.5.0/3`
- Eastern: `EST5EDT`
- Japanese: `JST-9`
- Pacific Time: `PST8PDT`
There is also another function for syncing the time, which takes timezone and DST offset. As DST info is set via static offset it will create local time problem when DST change occurs.
It's declaration is following:
```cpp
configTime(long gmtOffset_sec, int daylightOffset_sec, const char* server1, const char* server2 = nullptr, const char* server3 = nullptr);
```
In the example code it would be:
```cpp
// Synchronize time with NTP servers
// Accurate time is necessary for certificate validation and writing in batches
configTime(3600, 3600, "pool.ntp.org", "time.nis.gov");
```
Both `configTzTime` and `configTime` functions are asynchronous. This means that calling the functions just starts the time synchronization. Time is often not synchronized yet upon returning from call.
There is a helper function `timeSync` provided with the this library. The function starts time synchronization by calling the `configTzTime` and waits maximum 20 seconds for time to be synchronized. It prints progress info and final local time to the `Serial` console.
`timeSync` has the same signature as `configTzTime` and it is included with the main header file `InfluxDbClient.h`:
```cpp
// Synchronize time with NTP servers and waits for competition. Prints waiting progress and final synchronized time to the Serial.
// Accurate time is necessary for certificate validation and writing points in batch
// For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/
void timeSync(const char *tzInfo, const char* ntpServer1, const char* ntpServer2 = nullptr, const char* ntpServer3 = nullptr);
```
### Batch Size
Setting batch size depends on data gathering and DB updating strategy.
If data is written in short periods (seconds), the batch size should be set according to your expected write periods and update frequency requirements.
For example, if you would like to see updates (on the dashboard or in processing) each minute and you are measuring a single value (1 point) every 10s (6 points per minute), the batch size should be 6. If it is sufficient to update each hour and you are creating 1 point each minute, your batch size should be 60.
In cases where the data should be written in longer periods and gathered data consists of several points, the batch size should be set to the expected number of points to be gathered.
To set the batch size we use `WriteOptions` object and [setWriteOptions](#write-options) function:
```cpp
// Enable lines batching
client.setWriteOptions(WriteOptions().batchSize(10));
```
Writing the point will add a point to the underlying buffer until the batch size is reached:
```cpp
// Write first point to the buffer
// Buffered write always returns `true`
client.writePoint(point1);
// Write second point to the buffer
client.writePoint(point2);
..
// Write ninth point to the buffer
client.writePoint(point9);
// Writing tenth point will cause flushing buffer and returns actual write result.
if(!client.writePoint(point10)) {
Serial.print("InfluxDB write failed: ");
Serial.println(client.getLastErrorMessage());
}
```
In case cases where the number of points is not always the same, set the batch size to the maximum number of points and use the `flushBuffer()` function to force writing to the database. See [Buffer Handling](#buffer-handling-and-retrying) for more details.
### Large batch size
The maximum batch size depends on the available RAM of the device (~45KB for ESP8266 and ~260KB for ESP32). Larger batch size, >100 for ESP8255, >2000 for ESP32, must be chosen carefully to not crash the app with out of memory error. The Stream write mode must be used, see [Write Modes](#write-modes)
Always determine your typical line length using `client.pointToLineProtocol(point).length()`. For example, ESP32 can handle 2048 lines with an average length of 69. When the length of line or batch size is increased, the device becomes unstable, even there is more than 76k, it cannot send data or even crashes. ESP8266 handles successfully 330 of such lines.
:warning: Thoroughly test your app when using large batch files.
### Write Modes
Client has two modes of writing:
- Buffer (default)
- Stream
Writing is performed the way that client keeps written lines (points) separately and when a batch is completed, it allocates a data buffer for sending to a server via WiFi Client.
This is the fastest way to write data but requires some amount of free memory. Thus a big batch size cannot be used.
Another way of writing is *stream write*.
```cpp
// Enables stream write
client.setStreamWrite(true);
```
In this mode client continuously streams lines from batch to WiFi Client. No buffer allocation. As lines are allocated separately, it avoids problems with max allocable block size. The downside is, that writing is about 50% slower than in the Buffer mode.
## Buffer Handling and Retrying
InfluxDB contains an underlying buffer for handling writing in batches and automatic retrying on server back-pressure and connection failure.
Its size is controlled by the `bufferSize` param of [WriteOptions](#write-options) object:
```cpp
// Increase buffer to allow caching of failed writes
client.setWriteOptions(WriteOptions().bufferSize(50));
```
The recommended size is at least 2 x batch size.
The state of the buffer can be determined via two functions:
- `isBufferEmpty()` - Returns true if buffer is empty
- `isBufferFull()` - Returns true if buffer is full
A full buffer can occur when there is a problem with the internet connection or the InfluxDB server is overloaded. In such cases, points to write remain in the buffer. When more points are added and connection problem remains, the buffer will reach the top and new points will overwrite older points.
Each attempt to write a point will try to send older points in the buffer. So, the `isBufferFull()` function can be used to skip low priority points.
The `flushBuffer()` function can be used to force writing, even if the number of points in the buffer is lower than the batch size. With the help of the `isBufferEmpty()` function a check can be made before a device goes to sleep:
```cpp
// Check whether buffer in not empty
if (!client.isBufferEmpty()) {
// Write all remaining points to db
client.flushBuffer();
}
```
Other functions for dealing with buffer:
- `checkBuffer()` - Checks point buffer status and flushes if the number of points reaches batch size or flush interval runs out. This is the main function for controlling the buffer and it is used internally.
- `resetBuffer()` - Clears the buffer.
Check [SecureBatchWrite example](examples/SecureBatchWrite/SecureBatchWrite.ino) for example code of buffer handling functions.
## Write Options
Writing points can be controlled via `WriteOptions`, which is set in the `setWriteOptions` function:
| Parameter | Default Value | Meaning |
|-----------|---------------|---------|
| writePrecision | `WritePrecision::NoTime` | Timestamp precision of written data |
| batchSize | `1` | Number of points that will be written to the database at once |
| bufferSize | `5` | Maximum number of points in buffer. Buffer contains new data that will be written to the database and also data that failed to be written due to network failure or server overloading |
| flushInterval | `60` | Maximum time(in seconds) data will be held in buffer before points are written to the db |
| retryInterval | `5` | Default retry interval in sec, if not sent by server. Value `0` disables retrying |
| maxRetryInterval | `300` | Maximum retry interval in sec |
| maxRetryAttempts | `3` | Maximum count of retry attempts of failed writes |
## HTTP Options
`HTTPOptions` controls some aspects of HTTP communication and they are set via `setHTTPOptions` function:
| Parameter | Default Value | Meaning |
|-----------|---------------|---------|
| connectionReuse | `false` | Whether HTTP connection should be kept open after initial communication. Usable for frequent writes/queries. |
| httpReadTimeout | `5000` | Timeout (ms) for reading server response |
## Secure Connection
Connecting to a secured server requires configuring the client to trust the server. This is achieved by providing the client with a server certificate, certificate authority certificate or certificate SHA1 fingerprint.
:memo: In ESP32 arduino SDK (1.0.4), `WiFiClientSecure` doesn't support fingerprint to validate the server certificate.
The certificate (in PEM format) or SHA1 fingerprint should be placed in flash memory to save RAM.
Code bellow is an example certificate in PEM format. Valid InfluxDB 2 Cloud CA certificate is included in the library in the constant `InfluxDbCloud2CACert`, located in the `InfluxDBCloud.h`.
You can use a custom server certificate by exporting it, e.g. using a web browser:
```cpp
// Server certificate in PEM format, placed in the program (flash) memory to save RAM
const char ServerCert[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH
B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC
B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv
KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn
OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn
jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw
qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI
rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV
HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq
hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL
ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ
3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK
NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
-----END CERTIFICATE-----
)EOF";
// Alternatively, use a fingerprint of server certificate to set trust. Works only for ESP8266.
const char ServerCert[] PROGMEM = "cabd2a79a1076a31f21d253635cb039d4329a5e8";
```
### InfluxDb 2
There are two ways to set the certificate or fingerprint to trust a server:
- Use full param constructor
```cpp
// InfluxDB client instance with preconfigured InfluxCloud certificate
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, ServerCert);
```
- Use `setConnectionParams` function:
```cpp
// InfluxDB client instance
InfluxDBClient client;
void setup() {
// configure client
client.setConnectionParams(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, ServerCert);
}
```
### InfluxDb 1
Use `setConnectionParamsV1` function:
```cpp
// InfluxDB client instance
InfluxDBClient client;
void setup() {
// configure client
client.setConnectionParamsV1(INFLUXDB_URL, INFLUXDB_DATABASE, INFLUXDB_USER, INFLUXDB_PASSWORD, ServerCert);
}
```
Another important prerequisite to successfully validate a server or CA certificate is to have properly synchronized time. More on this in [Configure Time](#configure-time).
:information_source: Time synchronization is not required for validating server certificate via SHA1 fingerprint.
### Skipping certificate validation
The CA certificate provided with the library is ISRG Root X1. This certificate lasts a very long time, until 2035. It is not necessary to update your device until then when using ISRG Root X1.
If you are using your own certificate, plase keep in mind server certificates have limited validity period, often only a few months. It will be necessary to frequently change trusted certificate in the source code and reflashing the device. A solution could be using OTA update, but you will still need to care about certificate validity and updating it ahead of time to avoid connection failures.
The best way to prevent frequent updates is to use a root certificate like the one provided with the library. If you are unable to use a root certificate from a trusted authority, you may want to use insecure mode instead. This is done with the help of `InfluxDBClient::setInsecure()` method.
You will also save space in flash (and RAM) by leaving certificate param empty when calling constructor or `setConnectionParams` method.
:memo: The `InfluxDBClient::setInsecure()` method must be called before calling any function that will establish connection. The best place to call it is in the `setup` method:
```cpp
// InfluxDB client instance without a server certificate
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN);
void setup() {
// Set insecure connection to skip server certificate validation
client.setInsecure();
}
```
:warning: Using untrusted connection is a security risk.
## Querying
InfluxDB 2 and InfluxDB 1.7+ (with [enabled flux](https://docs.influxdata.com/influxdb/latest/administration/config/#flux-enabled-false)) uses [Flux](https://www.influxdata.com/products/flux/) to process and query data. InfluxDB client for Arduino offers a simple, but powerful, way how to query data with `query` function. It parses response line by line, so it can read a huge responses (thousands data lines), without consuming a lot device memory.
The `query` returns `FluxQueryResult` object, which parses response and provides useful getters for accessing values from result set.
The InfluxDB flux query result set is returned in CSV format. In the example below, the first line contains type information and the second column names, and the rest is data:
```CSV
#datatype,string,long,dateTime:RFC3339,dateTime:RFC3339,dateTime:RFC3339,long,string,string,string,string
,result,table,_start,_stop,_time,_value,SSID,_field,_measurement,device
,_result,0,2020-05-18T15:06:00.475253281Z,2020-05-19T15:06:00.475253281Z,2020-05-19T13:07:13Z,-55,667G,rssi,wifi_status,ESP32
,_result,0,2020-05-18T15:06:00.475253281Z,2020-05-19T15:06:00.475253281Z,2020-05-19T13:07:27Z,-54,667G,rssi,wifi_status,ESP32
,_result,0,2020-05-18T15:06:00.475253281Z,2020-05-19T15:06:00.475253281Z,2020-05-19T13:07:40Z,-54,667G,rssi,wifi_status,ESP32
,_result,0,2020-05-18T15:06:00.475253281Z,2020-05-19T15:06:00.475253281Z,2020-05-19T13:07:54Z,-54,667G,rssi,wifi_status,ESP32
,_result,0,2020-05-18T15:06:00.475253281Z,2020-05-19T15:06:00.475253281Z,2020-05-19T13:08:07Z,-55,667G,rssi,wifi_status,ESP32
,_result,0,2020-05-18T15:06:00.475253281Z,2020-05-19T15:06:00.475253281Z,2020-05-19T13:08:20Z,-56,667G,rssi,wifi_status,ESP32
```
Accessing data using `FluxQueryResult` requires knowing the query result structure, especially the name and the type of the column. The best practice is to tune the query
in the `InfluxDB Data Explorer` and use the final query with this library.
Browsing thought the result set is done by repeatedly calling the `next()` method, until it returns false. Unsuccessful reading is distinguished by a non empty value from the `getError()` method.
As a flux query result can contain several tables, differing by grouping key, use the `hasTableChanged()` method to determine when there is a new table.
Single values are returned using the `getValueByIndex()` or `getValueByName()` methods.
All row values at once are retrieved by the `getValues()` method.
Always call the `close()` method at the of reading.
A value in the flux query result column, retrieved by the `getValueByIndex()` or `getValueByName()` methods, is represented by the `FluxValue` object.
It provides getter methods for supported flux types:
| Flux type | Getter | C type |
| ----- | ------ | --- |
| long | getLong() | long |
| unsignedLong | getUnsignedLong() | unsigned long |
| dateTime:RFC3339, dateTime:RFC3339Nano | getDateTime() | [FluxDateTime](src/query/FluxTypes.h#L100) |
| bool | getBool() | bool |
| double | bool | double |
| string, base64binary, duration | getString() | String |
Calling improper type getter will result in a zero (empty) value.
Check for null (missing) value using the `isNull()` method.
Use the `getRawValue()` method for getting the original string form.
```cpp
// Construct a Flux query
// Query will find RSSI for last 24 hours for each connected WiFi network with this device computed by given selector function
String query = "from(bucket: \"my-bucket\") |> range(start: -24h) |> filter(fn: (r) => r._measurement == \"wifi_status\" and r._field == \"rssi\"";
query += "and r.device == \"ESP32\")";
query += "|> max()";
// Send query to the server and get result
FluxQueryResult result = client.query(query);
// Iterate over rows. Even there is just one row, next() must be called at least once.
while (result.next()) {
// Get typed value for flux result column 'SSID'
String ssid = result.getValueByName("SSID").getString();
Serial.print("SSID '");
Serial.print(ssid);
Serial.print("' with RSSI ");
// Get converted value for flux result column '_value' where there is RSSI value
long value = result.getValueByName("_value").getLong();
Serial.print(value);
// Format date-time for printing
// Format string according to http://www.cplusplus.com/reference/ctime/strftime/
String timeStr = time.format("%F %T");
Serial.print(" at ");
Serial.print(timeStr);
Serial.println();
}
// Check if there was an error
if(result.getError() != "") {
Serial.print("Query result error: ");
Serial.println(result.getError());
}
```
Complete source code is available in [QueryAggregated example](examples/QueryAggregated/QueryAggregated.ino).
### Parametrized Queries
InfluxDB Cloud supports [Parameterized Queries](https://docs.influxdata.com/influxdb/cloud/query-data/parameterized-queries/)
that let you dynamically change values in a query using the InfluxDB API. Parameterized queries make Flux queries more
reusable and can also be used to help prevent injection attacks.
InfluxDB Cloud inserts the params object into the Flux query as a Flux record named `params`. Use dot or bracket
notation to access parameters in the `params` record in your Flux query. Parameterized Flux queries support only `int`
, `float`, and `string` data types. To convert the supported data types into
other [Flux basic data types, use Flux type conversion functions](https://docs.influxdata.com/influxdb/cloud/query-data/parameterized-queries/#supported-parameter-data-types).
Parameterized query example:
> :warning: Parameterized Queries are supported only in InfluxDB Cloud. There is no support in InfluxDB OSS currently.
```cpp
// Prepare query parameters
QueryParams params;
params.add("bucket", INFLUXDB_BUCKET);
params.add("since", "-5m");
params.add("device", DEVICE);
params.add("rssiThreshold", -50);
// Construct a Flux query using parameters
// Parameters are accessed via the 'params' Flux object
// Flux only supports only string, float and int as parameters. Duration can be converted from string.
// Query will find RSSI less than defined threshold
String query = "from(bucket: params.bucket) |> range(start: duration(v: params.since)) \
|> filter(fn: (r) => r._measurement == \"wifi_status\") \
|> filter(fn: (r) => r._field == \"rssi\") \
|> filter(fn: (r) => r.device == params.device) \
|> filter(fn: (r) => r._value < params.rssiThreshold)";
// Print ouput header
// Print composed query
Serial.print("Querying with: ");
Serial.println(query);
// Send query to the server and get result
FluxQueryResult result = client.query(query, params);
//Print header
Serial.printf("%10s %20s %5s\n","Time","SSID","RSSI");
for(int i=0;i<37;i++) {
Serial.print('-');
}
Serial.println();
// Iterate over rows. Even there is just one row, next() must be called at least once.
int c = 0;
while (result.next()) {
// Get converted value for flux result column 'SSID'
String ssid = result.getValueByName("SSID").getString();
// Get converted value for flux result column '_value' where there is RSSI value
long rssi = result.getValueByName("_value").getLong();
// Get converted value for the _time column
FluxDateTime time = result.getValueByName("_time").getDateTime();
// Format date-time for printing
// Format string according to http://www.cplusplus.com/reference/ctime/strftime/
String timeStr = time.format("%F %T");
// Print formatted row
Serial.printf("%20s %10s %5d\n", timeStr.c_str(), ssid.c_str() ,rssi);
c++;
}
if(!c) {
Serial.println(" No data found");
}
// Check if there was an error
if(result.getError() != "") {
Serial.print("Query result error: ");
Serial.println(result.getError());
}
// Close the result
result.close();
```
Complete source code is available in [QueryParams example](examples/QueryParams/QueryParams.ino).
## Original API
### Initialization
```cpp
#define INFLUXDB_HOST "192.168.0.32"
#define INFLUXDB_PORT 1337
#define INFLUXDB_DATABASE "test"
//if used with authentication
#define INFLUXDB_USER "user"
#define INFLUXDB_PASS "password"
// connect to WiFi
Influxdb influx(INFLUXDB_HOST); // port defaults to 8086
// or to use a custom port
Influxdb influx(INFLUXDB_HOST, INFLUXDB_PORT);
// set the target database
influx.setDb(INFLUXDB_DATABASE);
// or use a db with auth
influx.setDbAuth(INFLUXDB_DATABASE, INFLUXDB_USER, INFLUXDB_PASS) // with authentication
// To use the v2.0 InfluxDB
influx.setVersion(2);
influx.setOrg("myOrganization");
influx.setBucket("myBucket");
influx.setToken("myToken");
influx.setPort(8086);
```
### Sending a single measurement
**Using an InfluxData object:**
```cpp
// create a measurement object
InfluxData measurement ("temperature");
measurement.addTag("device", d2);
measurement.addTag("sensor", "dht11");
measurement.addValue("value", 24.0);
// write it into db
influx.write(measurement);
```
**Using raw-data**
```cpp
influx.write("temperature,device=d2,sensor=dht11 value=24.0")
```
### Write multiple data points at once
Batching measurements and send them with a single request will result in a much higher performance.
```cpp
InfluxData measurement1 = readTemperature()
influx.prepare(measurement1)
InfluxData measurement2 = readLight()
influx.prepare(measurement2)
InfluxData measurement3 = readVoltage()
influx.prepare(measurement3)
// writes all prepared measurements with a single request into db.
boolean success = influx.write();
```
## Troubleshooting
All db methods return status. Value `false` means something went wrong. Call `getLastErrorMessage()` to get the error message.
When error message doesn't help to explain the bad behavior, go to the library sources and in the file `src/util/debug.h` uncomment line 33:
```cpp
// Uncomment bellow in case of a problem and rebuild sketch
#define INFLUXDB_CLIENT_DEBUG_ENABLE
```
Then upload your sketch again and see the debug output in the Serial Monitor.
If you couldn't solve a problem by yourself, please, post an issue including the debug output.
## Contributing
If you would like to contribute code you can do through GitHub by forking the repository and sending a pull request into the `master` branch.
## License
The InfluxDB Arduino Client is released under the [MIT License](https://opensource.org/licenses/MIT).

View File

@ -1,98 +0,0 @@
/**
* Basic Write Example code for InfluxDBClient library for Arduino
* Data can be immediately seen in a InfluxDB UI: wifi_status measurement
* Enter WiFi and InfluxDB parameters below
*
* Measures signal level of the actually connected WiFi network
* This example supports only InfluxDB running from unsecure (http://...)
* For secure (https://...) or Influx Cloud 2 use SecureWrite example
**/
#if defined(ESP32)
#include <WiFiMulti.h>
WiFiMulti wifiMulti;
#define DEVICE "ESP32"
#elif defined(ESP8266)
#include <ESP8266WiFiMulti.h>
ESP8266WiFiMulti wifiMulti;
#define DEVICE "ESP8266"
#endif
#include <InfluxDbClient.h>
// WiFi AP SSID
#define WIFI_SSID "ssid"
// WiFi password
#define WIFI_PASSWORD "password"
// InfluxDB server url. Don't use localhost, always server name or ip address.
// E.g. http://192.168.1.48:8086 (In InfluxDB 2 UI -> Load Data -> Client Libraries),
#define INFLUXDB_URL "influxdb-url"
// InfluxDB 2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
#define INFLUXDB_TOKEN "toked-id"
// InfluxDB 2 organization id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
#define INFLUXDB_ORG "org"
// InfluxDB 2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets)
#define INFLUXDB_BUCKET "bucket"
// InfluxDB v1 database name
//#define INFLUXDB_DB_NAME "database"
// InfluxDB client instance
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN);
// InfluxDB client instance for InfluxDB 1
//InfluxDBClient client(INFLUXDB_URL, INFLUXDB_DB_NAME);
// Data point
Point sensor("wifi_status");
void setup() {
Serial.begin(115200);
// Connect WiFi
Serial.println("Connecting to WiFi");
WiFi.mode(WIFI_STA);
wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD);
while (wifiMulti.run() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println();
// Set InfluxDB 1 authentication params
//client.setConnectionParamsV1(INFLUXDB_URL, INFLUXDB_DB_NAME, INFLUXDB_USER, INFLUXDB_PASSWORD);
// Add constant tags - only once
sensor.addTag("device", DEVICE);
sensor.addTag("SSID", WiFi.SSID());
// Check server connection
if (client.validateConnection()) {
Serial.print("Connected to InfluxDB: ");
Serial.println(client.getServerUrl());
} else {
Serial.print("InfluxDB connection failed: ");
Serial.println(client.getLastErrorMessage());
}
}
void loop() {
// Store measured value into point
sensor.clearFields();
// Report RSSI of currently connected network
sensor.addField("rssi", WiFi.RSSI());
// Print what are we exactly writing
Serial.print("Writing: ");
Serial.println(client.pointToLineProtocol(sensor));
// If no Wifi signal, try to reconnect it
if (wifiMulti.run() != WL_CONNECTED) {
Serial.println("Wifi connection lost");
}
// Write point
if (!client.writePoint(sensor)) {
Serial.print("InfluxDB write failed: ");
Serial.println(client.getLastErrorMessage());
}
//Wait 10s
Serial.println("Wait 10s");
delay(10000);
}

View File

@ -1,136 +0,0 @@
/**
* Buckets management Example code for InfluxDBClient library for Arduino
* Enter WiFi and InfluxDB parameters below
*
* This example supports only InfluxDB running from unsecure (http://...)
* For secure (https://...) or Influx Cloud 2 connection check SecureWrite example to
* see how connect using secured connection (https)
**/
#if defined(ESP32)
#include <WiFiMulti.h>
WiFiMulti wifiMulti;
#define DEVICE "ESP32"
#elif defined(ESP8266)
#include <ESP8266WiFiMulti.h>
ESP8266WiFiMulti wifiMulti;
#define DEVICE "ESP8266"
#endif
#include <InfluxDbClient.h>
// WiFi AP SSID
#define WIFI_SSID "ssid"
// WiFi password
#define WIFI_PASSWORD "password"
// InfluxDB server url. Don't use localhost, always server name or ip address.
// E.g. http://192.168.1.48:8086 (In InfluxDB 2 UI -> Load Data -> Client Libraries),
#define INFLUXDB_URL "influxdb-url"
// InfluxDB 2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
// This token must have all buckets permission
#define INFLUXDB_TOKEN "toked-id"
// InfluxDB 2 organization id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
#define INFLUXDB_ORG "org"
// Bucket name that doesn't exist in the db yet
#define INFLUXDB_BUCKET "test-bucket"
void setup() {
Serial.begin(74880);
// Connect WiFi
Serial.println("Connecting to " WIFI_SSID);
WiFi.mode(WIFI_STA);
wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD);
while (wifiMulti.run() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println();
}
// Creates client, bucket, writes data, verifies data and deletes bucket
void testClient() {
// InfluxDB client instance
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN);
// Check server connection
if (client.validateConnection()) {
Serial.print("Connected to InfluxDB: ");
Serial.println(client.getServerUrl());
} else {
Serial.print("InfluxDB connection failed: ");
Serial.println(client.getLastErrorMessage());
return;
}
// Get dedicated client for buckets management
BucketsClient buckets = client.getBucketsClient();
// Verify bucket does not exist, or delete it
if(buckets.checkBucketExists(INFLUXDB_BUCKET)) {
Serial.println("Bucket " INFLUXDB_BUCKET " already exists, deleting" );
// get reference
Bucket b = buckets.findBucket(INFLUXDB_BUCKET);
// Delete bucket
buckets.deleteBucket(b.getID());
}
// create a bucket with retention policy one month. Leave out or set zero to infinity
uint32_t monthSec = 30*24*3600;
Bucket b = buckets.createBucket(INFLUXDB_BUCKET, monthSec);
if(!b) {
// some error occurred
Serial.print("Bucket creating error: ");
Serial.println(buckets.getLastErrorMessage());
return;
}
Serial.print("Created bucket: ");
Serial.println(b.toString());
int numPoints = 10;
// Write some points
for(int i=0;i<numPoints;i++) {
Point point("test");
point.addTag("device_name", DEVICE);
point.addField("temperature", random(-20, 40) * 1.1f);
point.addField("humidity", random(10, 90));
if(!client.writePoint(point)) {
Serial.print("Write error: ");
Serial.println(client.getLastErrorMessage());
}
}
// verify written points
String query= "from(bucket: \"" INFLUXDB_BUCKET "\") |> range(start: -1h) |> pivot(rowKey:[\"_time\"],columnKey: [\"_field\"],valueColumn: \"_value\") |> count(column: \"humidity\")";
FluxQueryResult result = client.query(query);
// We expect one row
if(result.next()) {
// Get count value
FluxValue val = result.getValueByName("humidity");
if(val.getLong() != numPoints) {
Serial.print("Test failure, expected ");
Serial.print(numPoints);
Serial.print(" got ");
Serial.println(val.getLong());
} else {
Serial.println("Test successfull");
}
// Advance to the end
result.next();
} else {
Serial.print("Query error: ");
Serial.println(result.getError());
};
result.close();
buckets.deleteBucket(b.getID());
}
void loop() {
// Lets do an E2E test
// call a client test
testClient();
Serial.println("Stopping");
// Stop here, don't loop
while(1) delay(1);
}

View File

@ -1,163 +0,0 @@
/**
* QueryAggregated Example code for InfluxDBClient library for Arduino.
*
* This example demonstrates querying basic aggregated statistic parameters of WiFi signal level measured and stored in BasicWrite and SecureWrite examples.
*
* Demonstrates connection to any InfluxDB instance accesible via:
* - unsecured http://...
* - secure https://... (appropriate certificate is required)
* - InfluxDB 2 Cloud at https://cloud2.influxdata.com/ (certificate is preconfigured)
*
* Enter WiFi and InfluxDB parameters below
**/
#if defined(ESP32)
#include <WiFiMulti.h>
WiFiMulti wifiMulti;
#define DEVICE "ESP32"
#elif defined(ESP8266)
#include <ESP8266WiFiMulti.h>
ESP8266WiFiMulti wifiMulti;
#define DEVICE "ESP8266"
#endif
#include <InfluxDbClient.h>
#include <InfluxDbCloud.h>
// WiFi AP SSID
#define WIFI_SSID "SSID"
// WiFi password
#define WIFI_PASSWORD "PASSWORD"
// InfluxDB v2 server url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries)
// InfluxDB 1.8+ (v2 compatibility API) server url, e.g. http://192.168.1.48:8086
#define INFLUXDB_URL "server-url"
// InfluxDB v2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
// InfluxDB 1.8+ (v2 compatibility API) use form user:password, eg. admin:adminpass
#define INFLUXDB_TOKEN "server token"
// InfluxDB v2 organization name or id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
// InfluxDB 1.8+ (v2 compatibility API) use any non empty string
#define INFLUXDB_ORG "org name/id"
// InfluxDB v2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets)
// InfluxDB 1.8+ (v2 compatibility API) use database name
#define INFLUXDB_BUCKET "bucket name"
// Set timezone string according to https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html
// Examples:
// Pacific Time: "PST8PDT"
// Eastern: "EST5EDT"
// Japanesse: "JST-9"
// Central Europe: "CET-1CEST,M3.5.0,M10.5.0/3"
#define TZ_INFO "CET-1CEST,M3.5.0,M10.5.0/3"
// InfluxDB client instance with preconfigured InfluxCloud certificate
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
void setup() {
Serial.begin(115200);
// Setup wifi
WiFi.mode(WIFI_STA);
wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to wifi");
while (wifiMulti.run() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println();
// Accurate time is necessary for certificate validation
// For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/
// Syncing progress and the time will be printed to Serial
timeSync(TZ_INFO, "pool.ntp.org", "time.nis.gov");
// Check server connection
if (client.validateConnection()) {
Serial.print("Connected to InfluxDB: ");
Serial.println(client.getServerUrl());
} else {
Serial.print("InfluxDB connection failed: ");
Serial.println(client.getLastErrorMessage());
}
}
void loop() {
// Get max RSSI
printAgregateResult("max");
// Get mean RSSI
printAgregateResult("mean");
// Get min RSSI
printAgregateResult("min");
//Wait 10s
Serial.println("Wait 10s");
delay(10000);
}
// printAgregateResult queries db for aggregated RSSI value computed by given InfluxDB selector function (max, mean, min)
// Prints composed query and the result values.
void printAgregateResult(String selectorFunction) {
// Construct a Flux query
// Query will find RSSI for last hour for each connected WiFi network with this device computed by given selector function
String query = "from(bucket: \"" INFLUXDB_BUCKET "\") |> range(start: -1h) |> filter(fn: (r) => r._measurement == \"wifi_status\" and r._field == \"rssi\"";
query += " and r.device == \"" DEVICE "\")";
query += "|> " + selectorFunction + "()";
// Print ouput header
Serial.print("==== ");
Serial.print(selectorFunction);
Serial.println(" ====");
// Print composed query
Serial.print("Querying with: ");
Serial.println(query);
// Send query to the server and get result
FluxQueryResult result = client.query(query);
// Iterate over rows. Even there is just one row, next() must be called at least once.
while (result.next()) {
// Get converted value for flux result column 'SSID'
String ssid = result.getValueByName("SSID").getString();
Serial.print("SSID '");
Serial.print(ssid);
Serial.print("' with RSSI ");
// Get converted value for flux result column '_value' where there is RSSI value
// RSSI is integer value and so on min and max selected results,
// whereas mean is computed and the result type is double.
if(selectorFunction == "mean") {
double value = result.getValueByName("_value").getDouble();
Serial.print(value, 1);
// computed value has not got a _time column, so omitting getting time here
} else {
long value = result.getValueByName("_value").getLong();
Serial.print(value);
// Get converted value for the _time column
FluxDateTime time = result.getValueByName("_time").getDateTime();
// Format date-time for printing
// Format string according to http://www.cplusplus.com/reference/ctime/strftime/
String timeStr = time.format("%F %T");
Serial.print(" at ");
Serial.print(timeStr);
}
Serial.println();
}
// Check if there was an error
if(result.getError() != "") {
Serial.print("Query result error: ");
Serial.println(result.getError());
}
// Close the result
result.close();
}

View File

@ -1,154 +0,0 @@
/**
* QueryParams Example code for InfluxDBClient library for Arduino.
*
* This example demonstrates querying using parameters inserted into the Flux query. We select WiFi signal level values bellow a certain threshold.
* WiFi signal is measured and stored in BasicWrite and SecureWrite examples.
*
* Demonstrates connection to any InfluxDB instance accesible via:
* - InfluxDB 2 Cloud at https://cloud2.influxdata.com/ (certificate is preconfigured)
*
* Enter WiFi and InfluxDB parameters below
**/
#if defined(ESP32)
#include <WiFiMulti.h>
WiFiMulti wifiMulti;
#define DEVICE "ESP32"
#elif defined(ESP8266)
#include <ESP8266WiFiMulti.h>
ESP8266WiFiMulti wifiMulti;
#define DEVICE "ESP8266"
#endif
#include <InfluxDbClient.h>
#include <InfluxDbCloud.h>
// WiFi AP SSID
#define WIFI_SSID "SSID"
// WiFi password
#define WIFI_PASSWORD "PASSWORD"
// InfluxDB v2 server url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries)
// InfluxDB 1.8+ (v2 compatibility API) server url, e.g. http://192.168.1.48:8086
#define INFLUXDB_URL "server-url"
// InfluxDB v2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
// InfluxDB 1.8+ (v2 compatibility API) use form user:password, eg. admin:adminpass
#define INFLUXDB_TOKEN "server token"
// InfluxDB v2 organization name or id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
// InfluxDB 1.8+ (v2 compatibility API) use any non empty string
#define INFLUXDB_ORG "org name/id"
// InfluxDB v2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets)
// InfluxDB 1.8+ (v2 compatibility API) use database name
#define INFLUXDB_BUCKET "bucket name"
// Set timezone string according to https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html
// Examples:
// Pacific Time: "PST8PDT"
// Eastern: "EST5EDT"
// Japanesse: "JST-9"
// Central Europe: "CET-1CEST,M3.5.0,M10.5.0/3"
#define TZ_INFO "CET-1CEST,M3.5.0,M10.5.0/3"
// InfluxDB client instance with preconfigured InfluxCloud certificate
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
void setup() {
Serial.begin(115200);
// Setup wifi
WiFi.mode(WIFI_STA);
wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to wifi");
while (wifiMulti.run() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println();
// Accurate time is necessary for certificate validation
// For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/
// Syncing progress and the time will be printed to Serial
timeSync(TZ_INFO, "pool.ntp.org", "time.nis.gov");
// Check server connection
if (client.validateConnection()) {
Serial.print("Connected to InfluxDB: ");
Serial.println(client.getServerUrl());
} else {
Serial.print("InfluxDB connection failed: ");
Serial.println(client.getLastErrorMessage());
}
}
// Queries WiFi signal level values bellow a certain threshold using parameters inserted into the Flux query
// Prints composed query and the result values.
void loop() {
// Prepare query parameters
QueryParams params;
params.add("bucket", INFLUXDB_BUCKET);
params.add("since", "-5m");
params.add("device", DEVICE);
params.add("rssiTreshold", -50);
// Construct a Flux query using parameters
// Parameters are accessed via the 'params' Flux object
// Flux only supports only string, float and int as parameters. Duration can be converted from string.
// Query will find RSSI less than defined treshold
String query = "from(bucket: params.bucket) |> range(start: duration(v: params.since)) \
|> filter(fn: (r) => r._measurement == \"wifi_status\") \
|> filter(fn: (r) => r._field == \"rssi\") \
|> filter(fn: (r) => r.device == params.device) \
|> filter(fn: (r) => r._value < params.rssiTreshold)";
// Print ouput header
// Print composed query
Serial.print("Querying with: ");
Serial.println(query);
// Send query to the server and get result
FluxQueryResult result = client.query(query, params);
//Print header
Serial.printf("%10s %20s %5s\n","Time","SSID","RSSI");
for(int i=0;i<37;i++) {
Serial.print('-');
}
Serial.println();
// Iterate over rows. Even there is just one row, next() must be called at least once.
int c = 0;
while (result.next()) {
// Get converted value for flux result column 'SSID'
String ssid = result.getValueByName("SSID").getString();
// Get converted value for flux result column '_value' where there is RSSI value
long rssi = result.getValueByName("_value").getLong();
// Get converted value for the _time column
FluxDateTime time = result.getValueByName("_time").getDateTime();
// Format date-time for printing
// Format string according to http://www.cplusplus.com/reference/ctime/strftime/
String timeStr = time.format("%F %T");
// Print formatted row
Serial.printf("%20s %10s %5d\n", timeStr.c_str(), ssid.c_str() ,rssi);
c++;
}
if(!c) {
Serial.println(" No data found");
}
// Check if there was an error
if(result.getError() != "") {
Serial.print("Query result error: ");
Serial.println(result.getError());
}
// Close the result
result.close();
// Wait 15s
delay(15000);
}

View File

@ -1,148 +0,0 @@
/**
* QueryTable Example code for InfluxDBClient library for Arduino.
*
* This example demonstrates querying recent history of values of WiFi signal level measured and stored in BasicWrite and SecureWrite examples.
*
* Demonstrates connection to any InfluxDB instance accesible via:
* - unsecured http://...
* - secure https://... (appropriate certificate is required)
* - InfluxDB 2 Cloud at https://cloud2.influxdata.com/ (certificate is preconfigured)
*
* Enter WiFi and InfluxDB parameters below
**/
#if defined(ESP32)
#include <WiFiMulti.h>
WiFiMulti wifiMulti;
#define DEVICE "ESP32"
#elif defined(ESP8266)
#include <ESP8266WiFiMulti.h>
ESP8266WiFiMulti wifiMulti;
#define DEVICE "ESP8266"
#endif
#include <InfluxDbClient.h>
#include <InfluxDbCloud.h>
// WiFi AP SSID
#define WIFI_SSID "SSID"
// WiFi password
#define WIFI_PASSWORD "PASSWORD"
// InfluxDB v2 server url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries)
// InfluxDB 1.8+ (v2 compatibility API) server url, e.g. http://192.168.1.48:8086
#define INFLUXDB_URL "server-url"
// InfluxDB v2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
// InfluxDB 1.8+ (v2 compatibility API) use form user:password, eg. admin:adminpass
#define INFLUXDB_TOKEN "server token"
// InfluxDB v2 organization name or id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
// InfluxDB 1.8+ (v2 compatibility API) use any non empty string
#define INFLUXDB_ORG "org name/id"
// InfluxDB v2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets)
// InfluxDB 1.8+ (v2 compatibility API) use database name
#define INFLUXDB_BUCKET "bucket name"
// Set timezone string according to https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html
// Examples:
// Pacific Time: "PST8PDT"
// Eastern: "EST5EDT"
// Japanesse: "JST-9"
// Central Europe: "CET-1CEST,M3.5.0,M10.5.0/3"
#define TZ_INFO "CET-1CEST,M3.5.0,M10.5.0/3"
// InfluxDB client instance with preconfigured InfluxCloud certificate
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
void setup() {
Serial.begin(115200);
// Setup wifi
WiFi.mode(WIFI_STA);
wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to wifi");
while (wifiMulti.run() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println();
// Accurate time is necessary for certificate validation
// For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/
// Syncing progress and the time will be printed to Serial
timeSync(TZ_INFO, "pool.ntp.org", "time.nis.gov");
// Check server connection
if (client.validateConnection()) {
Serial.print("Connected to InfluxDB: ");
Serial.println(client.getServerUrl());
} else {
Serial.print("InfluxDB connection failed: ");
Serial.println(client.getLastErrorMessage());
}
}
void loop() {
// Construct a Flux query
// Query will list RSSI for last 24 hours for each connected WiFi network of this device type
String query = "from(bucket: \"" INFLUXDB_BUCKET "\") |> range(start: -24h) |> filter(fn: (r) => r._measurement == \"wifi_status\" and r._field == \"rssi\"";
query += " and r.device == \"" DEVICE "\")";
Serial.println("==== List results ====");
// Print composed query
Serial.print("Querying with: ");
Serial.println(query);
// Send query to the server and get result
FluxQueryResult result = client.query(query);
// Iterate over rows. Even there is just one row, next() must be called at least once.
while (result.next()) {
// Check for new grouping key
if(result.hasTableChanged()) {
Serial.println("Table:");
Serial.print(" ");
// Print all columns name
for(String &name: result.getColumnsName()) {
Serial.print(name);
Serial.print(",");
}
Serial.println();
Serial.print(" ");
// Print all columns datatype
for(String &tp: result.getColumnsDatatype()) {
Serial.print(tp);
Serial.print(",");
}
Serial.println();
}
Serial.print(" ");
// Print values of the row
for(FluxValue &val: result.getValues()) {
// Check whether the value is null
if(!val.isNull()) {
// Use raw string, unconverted value
Serial.print(val.getRawValue());
} else {
// Print null value substite
Serial.print("<null>");
}
Serial.print(",");
}
Serial.println();
}
// Check if there was an error
if(result.getError().length() > 0) {
Serial.print("Query result error: ");
Serial.println(result.getError());
}
// Close the result
result.close();
//Wait 10s
Serial.println("Wait 10s");
delay(10000);
}

View File

@ -1,167 +0,0 @@
/**
* Secure Write Example code for InfluxDBClient library for Arduino
* Enter WiFi and InfluxDB parameters below
*
* Demonstrates connection to any InfluxDB instance accesible via:
* - unsecured http://...
* - secure https://... (appropriate certificate is required)
* - InfluxDB 2 Cloud at https://cloud2.influxdata.com/ (certificate is preconfigured)
* Measures signal level of all visible WiFi networks including signal level of the actually connected one
* This example demonstrates time handling, how to write measures with different priorities, batching and retry
* Data can be immediately seen in a InfluxDB 2 Cloud UI - measurements wifi_status and wifi_networks
**/
#if defined(ESP32)
#include <WiFiMulti.h>
WiFiMulti wifiMulti;
#define DEVICE "ESP32"
#elif defined(ESP8266)
#include <ESP8266WiFiMulti.h>
ESP8266WiFiMulti wifiMulti;
#define DEVICE "ESP8266"
#define WIFI_AUTH_OPEN ENC_TYPE_NONE
#endif
#include <InfluxDbClient.h>
#include <InfluxDbCloud.h>
// WiFi AP SSID
#define WIFI_SSID "SSID"
// WiFi password
#define WIFI_PASSWORD "PASSWORD"
// InfluxDB v2 server url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries)
#define INFLUXDB_URL "server-url"
// InfluxDB v2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
#define INFLUXDB_TOKEN "server token"
// InfluxDB v2 organization id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
#define INFLUXDB_ORG "org id"
// InfluxDB v2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets)
#define INFLUXDB_BUCKET "bucket name"
// Set timezone string according to https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html
// Examples:
// Pacific Time: "PST8PDT"
// Eastern: "EST5EDT"
// Japanesse: "JST-9"
// Central Europe: "CET-1CEST,M3.5.0,M10.5.0/3"
#define TZ_INFO "CET-1CEST,M3.5.0,M10.5.0/3"
// NTP servers the for time synchronization.
// For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/
#define NTP_SERVER1 "pool.ntp.org"
#define NTP_SERVER2 "time.nis.gov"
#define WRITE_PRECISION WritePrecision::S
#define MAX_BATCH_SIZE 10
#define WRITE_BUFFER_SIZE 30
// InfluxDB client instance with preconfigured InfluxCloud certificate
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
// InfluxDB client instance without preconfigured InfluxCloud certificate for insecure connection
//InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN);
// Data point
Point sensorStatus("wifi_status");
// Number for loops to sync time using NTP
int iterations = 0;
void setup() {
Serial.begin(115200);
// Setup wifi
WiFi.mode(WIFI_STA);
wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to wifi");
while (wifiMulti.run() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println();
// Add tags
sensorStatus.addTag("device", DEVICE);
sensorStatus.addTag("SSID", WiFi.SSID());
// Alternatively, set insecure connection to skip server certificate validation
//client.setInsecure();
// Accurate time is necessary for certificate validation and writing in batches
// Syncing progress and the time will be printed to Serial.
timeSync(TZ_INFO, NTP_SERVER1, NTP_SERVER2);
// Check server connection
if (client.validateConnection()) {
Serial.print("Connected to InfluxDB: ");
Serial.println(client.getServerUrl());
} else {
Serial.print("InfluxDB connection failed: ");
Serial.println(client.getLastErrorMessage());
}
// Enable messages batching and retry buffer
client.setWriteOptions(WriteOptions().writePrecision(WRITE_PRECISION).batchSize(MAX_BATCH_SIZE).bufferSize(WRITE_BUFFER_SIZE));
}
void loop() {
// Sync time for batching once per hour
if (iterations++ >= 360) {
timeSync(TZ_INFO, NTP_SERVER1, NTP_SERVER2);
iterations = 0;
}
// Report networks (low priority data) just in case we successfully wrote the previous batch
if (client.isBufferEmpty()) {
// Report all the detected wifi networks
int networks = WiFi.scanNetworks();
// Set identical time for the whole network scan
time_t tnow = time(nullptr);
for (int i = 0; i < networks; i++) {
Point sensorNetworks("wifi_networks");
sensorNetworks.addTag("device", DEVICE);
sensorNetworks.addTag("SSID", WiFi.SSID(i));
sensorNetworks.addTag("channel", String(WiFi.channel(i)));
sensorNetworks.addTag("open", String(WiFi.encryptionType(i) == WIFI_AUTH_OPEN));
sensorNetworks.addField("rssi", WiFi.RSSI(i));
sensorNetworks.setTime(tnow); //set the time
// Print what are we exactly writing
Serial.print("Writing: ");
Serial.println(client.pointToLineProtocol(sensorNetworks));
// Write point into buffer - low priority measures
client.writePoint(sensorNetworks);
}
} else
Serial.println("Wifi networks reporting skipped due to communication issues");
// Report RSSI of currently connected network
sensorStatus.setTime(time(nullptr));
sensorStatus.addField("rssi", WiFi.RSSI());
// Print what are we exactly writing
Serial.print("Writing: ");
Serial.println(client.pointToLineProtocol(sensorStatus));
// Write point into buffer - high priority measure
client.writePoint(sensorStatus);
// Clear fields for next usage. Tags remain the same.
sensorStatus.clearFields();
// If no Wifi signal, try to reconnect it
if (wifiMulti.run() != WL_CONNECTED) {
Serial.println("Wifi connection lost");
}
// End of the iteration - force write of all the values into InfluxDB as single transaction
Serial.println("Flushing data into InfluxDB");
if (!client.flushBuffer()) {
Serial.print("InfluxDB flush failed: ");
Serial.println(client.getLastErrorMessage());
Serial.print("Full buffer: ");
Serial.println(client.isBufferFull() ? "Yes" : "No");
}
// Wait 10s
Serial.println("Wait 10s");
delay(10000);
}

View File

@ -1,113 +0,0 @@
/**
* Secure Write Example code for InfluxDBClient library for Arduino
* Enter WiFi and InfluxDB parameters below
*
* Demonstrates connection to any InfluxDB instance accesible via:
* - unsecured http://...
* - secure https://... (appropriate certificate is required)
* - InfluxDB 2 Cloud at https://cloud2.influxdata.com/ (certificate is preconfigured)
* Measures signal level of the actually connected WiFi network
* This example demonstrates time handling, secure connection and measurement writing into InfluxDB
* Data can be immediately seen in a InfluxDB 2 Cloud UI - measurement wifi_status
**/
#if defined(ESP32)
#include <WiFiMulti.h>
WiFiMulti wifiMulti;
#define DEVICE "ESP32"
#elif defined(ESP8266)
#include <ESP8266WiFiMulti.h>
ESP8266WiFiMulti wifiMulti;
#define DEVICE "ESP8266"
#endif
#include <InfluxDbClient.h>
#include <InfluxDbCloud.h>
// WiFi AP SSID
#define WIFI_SSID "SSID"
// WiFi password
#define WIFI_PASSWORD "PASSWORD"
// InfluxDB v2 server url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries)
#define INFLUXDB_URL "server-url"
// InfluxDB v2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
#define INFLUXDB_TOKEN "server token"
// InfluxDB v2 organization id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
#define INFLUXDB_ORG "org id"
// InfluxDB v2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets)
#define INFLUXDB_BUCKET "bucket name"
// Set timezone string according to https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html
// Examples:
// Pacific Time: "PST8PDT"
// Eastern: "EST5EDT"
// Japanesse: "JST-9"
// Central Europe: "CET-1CEST,M3.5.0,M10.5.0/3"
#define TZ_INFO "CET-1CEST,M3.5.0,M10.5.0/3"
// InfluxDB client instance with preconfigured InfluxCloud certificate
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
// InfluxDB client instance without preconfigured InfluxCloud certificate for insecure connection
//InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN);
// Data point
Point sensor("wifi_status");
void setup() {
Serial.begin(115200);
// Setup wifi
WiFi.mode(WIFI_STA);
wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to wifi");
while (wifiMulti.run() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println();
// Add tags
sensor.addTag("device", DEVICE);
sensor.addTag("SSID", WiFi.SSID());
// Alternatively, set insecure connection to skip server certificate validation
//client.setInsecure();
// Accurate time is necessary for certificate validation and writing in batches
// For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/
// Syncing progress and the time will be printed to Serial.
timeSync(TZ_INFO, "pool.ntp.org", "time.nis.gov");
// Check server connection
if (client.validateConnection()) {
Serial.print("Connected to InfluxDB: ");
Serial.println(client.getServerUrl());
} else {
Serial.print("InfluxDB connection failed: ");
Serial.println(client.getLastErrorMessage());
}
}
void loop() {
// Store measured value into point
sensor.clearFields();
// Report RSSI of currently connected network
sensor.addField("rssi", WiFi.RSSI());
// Print what are we exactly writing
Serial.print("Writing: ");
Serial.println(client.pointToLineProtocol(sensor));
// If no Wifi signal, try to reconnect it
if (wifiMulti.run() != WL_CONNECTED) {
Serial.println("Wifi connection lost");
}
// Write point
if (!client.writePoint(sensor)) {
Serial.print("InfluxDB write failed: ");
Serial.println(client.getLastErrorMessage());
}
//Wait 10s
Serial.println("Wait 10s");
delay(10000);
}

View File

@ -1,45 +0,0 @@
# Syntax Coloring Map For InfluxDBClient library
# Datatypes (KEYWORD1)
WritePrecision KEYWORD1
Point KEYWORD1
InfluxDBClient KEYWORD1
InfluxData KEYWORD1
Influxdb KEYWORD1
FluxValue KEYWORD1
FluxQueryResult KEYWORD1
FluxDateTime KEYWORD1
# Methods and Functions (KEYWORD2)
addTag KEYWORD2
addField KEYWORD2
setTime KEYWORD2
clearFields KEYWORD2
clearTags KEYWORD2
hasFields KEYWORD2
hasTags KEYWORD2
hasTime KEYWORD2
toLineProtocol KEYWORD2
setWriteOptions KEYWORD2
validateConnection KEYWORD2
writeRecord KEYWORD2
writePoint KEYWORD2
query KEYWORD2
flushBuffer KEYWORD2
isBufferFull KEYWORD2
isBufferEmpty KEYWORD2
checkBuffer KEYWORD2
getLastStatusCode KEYWORD2
resetBuffer KEYWORD2
getLastErrorMessage KEYWORD2
getServerUrl KEYWORD2
setDb KEYWORD2
prepare KEYWORD2
write KEYWORD2
# Constants (LITERAL1)
NoTime LITERAL1
S LITERAL1
MS LITERAL1
US LITERAL1
NS LITERAL1

View File

@ -1,10 +0,0 @@
name=ESP8266 Influxdb
version=3.12.1
author=Tobias Schürg, InfluxData
maintainer=Tobias Schürg, InfluxData
sentence=InfluxDB Client for Arduino.
url=https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino
paragraph=This library allows writing and reading data from InfluxDB server or InfluxDB Cloud. Supports authentication, secure communication over TLS, batching and retrying.
category=Data Storage
architectures=*
includes=InfluxDbClient.h

View File

@ -1,45 +0,0 @@
; CanAirIO Sensorlib
;
; Full guide and details: https://github.com/kike-canaries/canairio_sensorlib
[platformio]
src_dir = ./test/
[env]
framework = arduino
upload_speed = 1500000
monitor_speed = 115200
monitor_filters = time
build_flags =
-D CORE_DEBUG_LEVEL=0
lib_deps =
https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino.git
[esp32_common]
platform = espressif32
board = esp32dev
framework = ${env.framework}
upload_speed = ${env.upload_speed}
monitor_speed = ${env.monitor_speed}
lib_deps = ${env.lib_deps}
build_flags =
${env.build_flags}
[esp8266_common]
platform = espressif8266
framework = ${env.framework}
board = esp12e
monitor_speed = ${env.monitor_speed}
build_flags =
${env.build_flags}
lib_deps =
${env.lib_deps}
[env:esp8266BasicTest]
extends = esp8266_common
[env:esp32BasicTest]
extends = esp32_common

View File

@ -1,244 +0,0 @@
/**
*
* BucketsClient.cpp: InfluxDB Buckets Client
*
* MIT License
*
* Copyright (c) 2020 InfluxData
*
* 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 "BucketsClient.h"
#include "util/helpers.h"
#include "util/debug.h"
static const char *propTemplate PROGMEM = "\"%s\":";
// Finds first id property from JSON response
enum class PropType {
String,
Number
};
static String findProperty(const char *prop,const String &json, PropType type = PropType::String);
static String findProperty(const char *prop,const String &json, PropType type) {
INFLUXDB_CLIENT_DEBUG("[D] Searching for %s in %s\n", prop, json.c_str());
int propLen = strlen_P(propTemplate)+strlen(prop)-2;
char *propSearch = new char[propLen+1];
sprintf_P(propSearch, propTemplate, prop);
int i = json.indexOf(propSearch);
delete [] propSearch;
if(i>-1) {
INFLUXDB_CLIENT_DEBUG("[D] Found at %d\n", i);
switch(type) {
case PropType::String:
i = json.indexOf("\"", i+propLen);
if(i>-1) {
INFLUXDB_CLIENT_DEBUG("[D] Found starting \" at %d\n", i);
int e = json.indexOf("\"", i+1);
if(e>-1) {
INFLUXDB_CLIENT_DEBUG("[D] Found ending \" at %d\n", e);
return json.substring(i+1, e);
}
}
break;
case PropType::Number:
i = i+propLen;
while(json[i] == ' ') {
i++;
}
INFLUXDB_CLIENT_DEBUG("[D] Found beginning of number at %d\n", i);
int e = json.indexOf(",", i+1);
if(e>-1) {
INFLUXDB_CLIENT_DEBUG("[D] Found , at %d\n", e);
return json.substring(i, e);
}
break;
}
}
return "";
}
char *copyChars(const char *str) {
char *ret = new char[strlen(str)+1];
strcpy(ret, str);
return ret;
}
Bucket::Bucket():_data(nullptr) {
}
Bucket::Bucket(const char *id, const char *name, const uint32_t expire) {
_data = std::make_shared<Data>(id, name, expire);
}
Bucket::Bucket(const Bucket &other) {
_data = other._data;
}
Bucket& Bucket::operator=(const Bucket& other) {
if(this != &other) {
_data = other._data;
}
return *this;
}
Bucket::~Bucket() {
}
Bucket::Data::Data(const char *id, const char *name, const uint32_t expire) {
this->id = copyChars(id);
this->name = copyChars(name);
this->expire = expire;
}
Bucket::Data::~Data() {
delete [] id;
delete [] name;
}
const char *toStringTmplt PROGMEM = "Bucket: ID %s, Name %s, expire %u";
String Bucket::toString() const {
int len = strlen_P(toStringTmplt) + (_data?strlen(_data->name):0) + (_data?strlen(_data->id):0) + 10 + 1; //10 is maximum length of string representation of expire
char *buff = new char[len];
sprintf_P(buff, toStringTmplt, getID(), getName(), getExpire());
String ret = buff;
return ret;
}
BucketsClient::BucketsClient() {
_data = nullptr;
}
BucketsClient::BucketsClient(ConnectionInfo *pConnInfo, HTTPService *service) {
_data = std::make_shared<Data>(pConnInfo, service);
}
BucketsClient::BucketsClient(const BucketsClient &other) {
_data = other._data;
}
BucketsClient &BucketsClient::operator=(const BucketsClient &other) {
if(this != &other) {
_data = other._data;
}
return *this;
}
BucketsClient &BucketsClient::operator=(std::nullptr_t) {
_data = nullptr;
return *this;
}
String BucketsClient::getOrgID(const char *org) {
if(!_data) {
return "";
}
if(isValidID(org)) {
return org;
}
String url = _data->pService->getServerAPIURL();
url += "orgs?org=";
url += urlEncode(org);
String id;
INFLUXDB_CLIENT_DEBUG("[D] getOrgID: url %s\n", url.c_str());
_data->pService->doGET(url.c_str(), 200, [&id](HTTPClient *client){
id = findProperty("id",client->getString());
return true;
});
return id;
}
bool BucketsClient::checkBucketExists(const char *bucketName) {
Bucket b = findBucket(bucketName);
return !b.isNull();
}
static const char *CreateBucketTemplate PROGMEM = "{\"name\":\"%s\",\"orgID\":\"%s\",\"retentionRules\":[{\"everySeconds\":%u}]}";
Bucket BucketsClient::createBucket(const char *bucketName, uint32_t expiresSec) {
Bucket b;
if(_data) {
String orgID = getOrgID(_data->pConnInfo->org.c_str());
if(!orgID.length()) {
return b;
}
int expireLen = 0;
uint32_t e = expiresSec;
do {
expireLen++;
e /=10;
} while(e > 0);
int len = strlen_P(CreateBucketTemplate) + strlen(bucketName) + orgID.length() + expireLen+1;
char *body = new char[len];
sprintf_P(body, CreateBucketTemplate, bucketName, orgID.c_str(), expiresSec);
String url = _data->pService->getServerAPIURL();
url += "buckets";
INFLUXDB_CLIENT_DEBUG("[D] CreateBucket: url %s, body %s\n", url.c_str(), body);
_data->pService->doPOST(url.c_str(), body, "application/json", 201, [&b](HTTPClient *client){
String resp = client->getString();
String id = findProperty("id", resp);
String name = findProperty("name", resp);
String expireStr = findProperty("everySeconds", resp, PropType::Number);
uint32_t expire = strtoul(expireStr.c_str(), nullptr, 10);
b = Bucket(id.c_str(), name.c_str(), expire);
return true;
});
delete [] body;
}
return b;
}
bool BucketsClient::deleteBucket(const char *id) {
if(!_data) {
return false;
}
String url = _data->pService->getServerAPIURL();
url += "buckets/";
url += id;
INFLUXDB_CLIENT_DEBUG("[D] deleteBucket: url %s\n", url.c_str());
return _data->pService->doDELETE(url.c_str(), 204, nullptr);
}
Bucket BucketsClient::findBucket(const char *bucketName) {
Bucket b;
if(_data) {
String url = _data->pService->getServerAPIURL();
url += "buckets?name=";
url += urlEncode(bucketName);
INFLUXDB_CLIENT_DEBUG("[D] findBucket: url %s\n", url.c_str());
_data->pService->doGET(url.c_str(), 200, [&b](HTTPClient *client){
String resp = client->getString();
String id = findProperty("id", resp);
if(id.length()) {
String name = findProperty("name", resp);
String expireStr = findProperty("everySeconds", resp, PropType::Number);
uint32_t expire = strtoul(expireStr.c_str(), nullptr, 10);
b = Bucket(id.c_str(), name.c_str(), expire);
}
return true;
});
}
return b;
}

View File

@ -1,122 +0,0 @@
/**
*
* BucketsClient.h: InfluxDB Buckets Client
*
* MIT License
*
* Copyright (c) 2020 InfluxData
*
* 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 _BUCKETS_CLIENT_H_
#define _BUCKETS_CLIENT_H_
#include <HTTPService.h>
#include <memory>
class BucketsClient;
class Test;
/**
* Bucket represents a bucket in the InfluxDB 2 server
**/
class Bucket {
friend class BucketsClient;
friend class Test;
public:
// Create empty, invalid, bucket instance
Bucket();
// Create a bucket instance
Bucket(const char *id, const char *name, const uint32_t expire);
// Copy constructor
Bucket(const Bucket &other);
// Assignment operator
Bucket &operator=(const Bucket &other);
// for testing validity
operator bool() const { return !isNull(); }
// Clean bucket
~Bucket();
// Returns Bucket ID
const char *getID() const { return _data?_data->id:nullptr; }
// Retuns bucket name
const char *getName() const { return _data?_data->name:nullptr; }
// Retention policy in sec, 0 - inifinite
uint32_t getExpire() const { return _data?_data->expire:0; }
// Checks if it is null instance
bool isNull() const { return _data == nullptr; }
// String representation
String toString() const;
private:
class Data {
public:
Data(const char *id, const char *name, const uint32_t expire);
~Data();
char *id;
char *name;
uint32_t expire;
};
std::shared_ptr<Data> _data;
};
class InfluxDBClient;
class E2ETest;
/**
* BucketsClient is a client for managing buckets in the InfluxDB 2 server
* A new bucket can be created, or a bucket can be checked for existence by its name.
* A bucket can be also deleted.
**/
class BucketsClient {
friend class InfluxDBClient;
friend class Test;
friend class E2ETest;
public:
// Copy contructor
BucketsClient(const BucketsClient &other);
// Assignment operator
BucketsClient &operator=(const BucketsClient &other);
// nullptr assignment for clearing
BucketsClient &operator=(std::nullptr_t);
// for testing validity
operator bool() const { return !isNull(); }
// Returns true if a bucket exists
bool checkBucketExists(const char *bucketName);
// Returns a Bucket instance if a bucket is found.
Bucket findBucket(const char *bucketName);
// Creates a bucket with given name and optional retention policy. 0 means infinite.
Bucket createBucket(const char *bucketName, uint32_t expiresSec = 0);
// Delete a bucket with given id. Use findBucket to get a bucket with id.
bool deleteBucket(const char *id);
// Returns last error message
String getLastErrorMessage() { return _data?_data->pConnInfo->lastError:""; }
// check validity
bool isNull() const { return _data == nullptr; }
protected:
BucketsClient();
BucketsClient(ConnectionInfo *pConnInfo, HTTPService *service);
String getOrgID(const char *org);
private:
class Data {
public:
Data(ConnectionInfo *pConnInfo, HTTPService *pService):pConnInfo(pConnInfo),pService(pService) {};
ConnectionInfo *pConnInfo;
HTTPService *pService;
};
std::shared_ptr<Data> _data;
};
#endif

View File

@ -1,220 +0,0 @@
#include "HTTPService.h"
#include "Platform.h"
#include "Version.h"
#include "util/debug.h"
static const char UserAgent[] PROGMEM = "influxdb-client-arduino/" INFLUXDB_CLIENT_VERSION " (" INFLUXDB_CLIENT_PLATFORM " " INFLUXDB_CLIENT_PLATFORM_VERSION ")";
#if defined(ESP8266)
bool checkMFLN(BearSSL::WiFiClientSecure *client, String url);
#endif
// This cannot be put to PROGMEM due to the way how it is used
static const char *RetryAfter = "Retry-After";
const char *TransferEncoding = "Transfer-Encoding";
HTTPService::HTTPService(ConnectionInfo *pConnInfo):_pConnInfo(pConnInfo) {
_apiURL = pConnInfo->serverUrl;
_apiURL += "/api/v2/";
bool https = pConnInfo->serverUrl.startsWith("https");
if(https) {
#if defined(ESP8266)
BearSSL::WiFiClientSecure *wifiClientSec = new BearSSL::WiFiClientSecure;
if (pConnInfo->insecure) {
wifiClientSec->setInsecure();
} else if(pConnInfo->certInfo && strlen_P(pConnInfo->certInfo) > 0) {
if(strlen_P(pConnInfo->certInfo) > 60 ) { //differentiate fingerprint and cert
_cert = new BearSSL::X509List(pConnInfo->certInfo);
wifiClientSec->setTrustAnchors(_cert);
} else {
wifiClientSec->setFingerprint(pConnInfo->certInfo);
}
}
checkMFLN(wifiClientSec, pConnInfo->serverUrl);
#elif defined(ESP32)
WiFiClientSecure *wifiClientSec = new WiFiClientSecure;
if (pConnInfo->insecure) {
#ifndef ARDUINO_ESP32_RELEASE_1_0_4
// This works only in ESP32 SDK 1.0.5 and higher
wifiClientSec->setInsecure();
#endif
} else if(pConnInfo->certInfo && strlen_P(pConnInfo->certInfo) > 0) {
wifiClientSec->setCACert(pConnInfo->certInfo);
}
#endif
_wifiClient = wifiClientSec;
} else {
_wifiClient = new WiFiClient;
}
if(!_httpClient) {
_httpClient = new HTTPClient;
}
_httpClient->setReuse(_httpOptions._connectionReuse);
_httpClient->setUserAgent(FPSTR(UserAgent));
};
HTTPService::~HTTPService() {
if(_httpClient) {
delete _httpClient;
_httpClient = nullptr;
}
if(_wifiClient) {
delete _wifiClient;
_wifiClient = nullptr;
}
#if defined(ESP8266)
if(_cert) {
delete _cert;
_cert = nullptr;
}
#endif
}
void HTTPService::setHTTPOptions(const HTTPOptions & httpOptions) {
_httpOptions = httpOptions;
if(!_httpClient) {
_httpClient = new HTTPClient;
}
_httpClient->setReuse(_httpOptions._connectionReuse);
_httpClient->setTimeout(_httpOptions._httpReadTimeout);
#if defined(ESP32)
_httpClient->setConnectTimeout(_httpOptions._httpReadTimeout);
#endif
}
// parse URL for host and port and call probeMaxFragmentLength
#if defined(ESP8266)
bool checkMFLN(BearSSL::WiFiClientSecure *client, String url) {
int index = url.indexOf(':');
if(index < 0) {
return false;
}
String protocol = url.substring(0, index);
int port = -1;
url.remove(0, (index + 3)); // remove http:// or https://
if (protocol == "http") {
// set default port for 'http'
port = 80;
} else if (protocol == "https") {
// set default port for 'https'
port = 443;
} else {
return false;
}
index = url.indexOf('/');
String host = url.substring(0, index);
url.remove(0, index); // remove host
// check Authorization
index = host.indexOf('@');
if(index >= 0) {
host.remove(0, index + 1); // remove auth part including @
}
// get port
index = host.indexOf(':');
if(index >= 0) {
String portS = host;
host = host.substring(0, index); // hostname
portS.remove(0, (index + 1)); // remove hostname + :
port = portS.toInt(); // get port
}
INFLUXDB_CLIENT_DEBUG("[D] probeMaxFragmentLength to %s:%d\n", host.c_str(), port);
bool mfln = client->probeMaxFragmentLength(host, port, 1024);
INFLUXDB_CLIENT_DEBUG("[D] MFLN:%s\n", mfln ? "yes" : "no");
if (mfln) {
client->setBufferSizes(1024, 1024);
}
return mfln;
}
#endif //ESP8266
bool HTTPService::beforeRequest(const char *url) {
if(!_httpClient->begin(*_wifiClient, url)) {
_pConnInfo->lastError = F("begin failed");
return false;
}
if(_pConnInfo->authToken.length() > 0) {
_httpClient->addHeader(F("Authorization"), "Token " + _pConnInfo->authToken);
}
const char * headerKeys[] = {RetryAfter, TransferEncoding} ;
_httpClient->collectHeaders(headerKeys, 2);
return true;
}
bool HTTPService::doPOST(const char *url, const char *data, const char *contentType, int expectedCode, httpResponseCallback cb) {
INFLUXDB_CLIENT_DEBUG("[D] POST request - %s, data: %dbytes, type %s\n", url, strlen(data), contentType);
if(!beforeRequest(url)) {
return false;
}
if(contentType) {
_httpClient->addHeader(F("Content-Type"), FPSTR(contentType));
}
_lastStatusCode = _httpClient->POST((uint8_t *) data, strlen(data));
return afterRequest(expectedCode, cb);
}
bool HTTPService::doPOST(const char *url, Stream *stream, const char *contentType, int expectedCode, httpResponseCallback cb) {
INFLUXDB_CLIENT_DEBUG("[D] POST request - %s, data: %dbytes, type %s\n", url, stream->available(), contentType);
if(!beforeRequest(url)) {
return false;
}
if(contentType) {
_httpClient->addHeader(F("Content-Type"), FPSTR(contentType));
}
_lastStatusCode = _httpClient->sendRequest("POST", stream, stream->available());
return afterRequest(expectedCode, cb);
}
bool HTTPService::doGET(const char *url, int expectedCode, httpResponseCallback cb) {
INFLUXDB_CLIENT_DEBUG("[D] GET request - %s\n", url);
if(!beforeRequest(url)) {
return false;
}
_lastStatusCode = _httpClient->GET();
return afterRequest(expectedCode, cb, false);
}
bool HTTPService::doDELETE(const char *url, int expectedCode, httpResponseCallback cb) {
INFLUXDB_CLIENT_DEBUG("[D] DELETE - %s\n", url);
if(!beforeRequest(url)) {
return false;
}
_lastStatusCode = _httpClient->sendRequest("DELETE");
return afterRequest(expectedCode, cb, false);
}
bool HTTPService::afterRequest(int expectedStatusCode, httpResponseCallback cb, bool modifyLastConnStatus) {
if(modifyLastConnStatus) {
_lastRequestTime = millis();
INFLUXDB_CLIENT_DEBUG("[D] HTTP status code - %d\n", _lastStatusCode);
_lastRetryAfter = 0;
if(_lastStatusCode >= 429) { //retryable server errors
if(_httpClient->hasHeader(RetryAfter)) {
_lastRetryAfter = _httpClient->header(RetryAfter).toInt();
INFLUXDB_CLIENT_DEBUG("[D] Reply after - %d\n", _lastRetryAfter);
}
}
}
_pConnInfo->lastError = (char *)nullptr;
bool ret = _lastStatusCode == expectedStatusCode;
bool endConnection = true;
if(!ret) {
if(_lastStatusCode > 0) {
_pConnInfo->lastError = _httpClient->getString();
INFLUXDB_CLIENT_DEBUG("[D] Response:\n%s\n", _pConnInfo->lastError.c_str());
} else {
_pConnInfo->lastError = _httpClient->errorToString(_lastStatusCode);
INFLUXDB_CLIENT_DEBUG("[E] Error - %s\n", _pConnInfo->lastError.c_str());
}
} else if(cb){
endConnection = cb(_httpClient);
}
if(endConnection) {
_httpClient->end();
}
return ret;
}

View File

@ -1,136 +0,0 @@
/**
*
* HTTPService.h: HTTP Service
*
* MIT License
*
* Copyright (c) 2020 InfluxData
*
* 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 _HTTP_SERVICE_H_
#define _HTTP_SERVICE_H_
#include <Arduino.h>
#if defined(ESP8266)
# include <WiFiClientSecureBearSSL.h>
# include <ESP8266HTTPClient.h>
#elif defined(ESP32)
# include <HTTPClient.h>
#else
# error "This library currently supports only ESP8266 and ESP32."
#endif
#include "Options.h"
class Test;
typedef std::function<bool(HTTPClient *client)> httpResponseCallback;
extern const char *TransferEncoding;
struct ConnectionInfo {
// Connection info
String serverUrl;
// Write & query targets
String bucket;
String org;
// v2 authetication token
String authToken;
// Version of InfluxDB 1 or 2
uint8_t dbVersion;
// V1 user authetication
String user;
String password;
// Certificate info
const char *certInfo;
// flag if https should ignore cert validation
bool insecure;
// Error message of last failed operation
String lastError;
};
/**
* HTTPService provides HTTP methods for communicating with InfluxDBServer,
* while taking care of Authorization and error handling
**/
class HTTPService {
friend class Test;
private:
// Connection info data
ConnectionInfo *_pConnInfo;
// Server API URL
String _apiURL;
// Last time in ms we made are a request to server
uint32_t _lastRequestTime = 0;
// HTTP status code of last request to server
int _lastStatusCode = 0;
// Underlying HTTPClient instance
HTTPClient *_httpClient = nullptr;
// Underlying connection object
WiFiClient *_wifiClient = nullptr;
#ifdef ESP8266
// Trusted cert chain
BearSSL::X509List *_cert = nullptr;
#endif
// Store retry timeout suggested by server after last request
int _lastRetryAfter = 0;
// HTTP options
HTTPOptions _httpOptions;
protected:
// Sets request params
bool beforeRequest(const char *url);
// Handles response
bool afterRequest(int expectedStatusCode, httpResponseCallback cb, bool modifyLastConnStatus = true);
public:
// Creates HTTPService instance
// serverUrl - url of the InfluxDB 2 server (e.g. http://localhost:8086)
// authToken - InfluxDB 2 authorization token
// certInfo - InfluxDB 2 server trusted certificate (or CA certificate) or certificate SHA1 fingerprint. Should be stored in PROGMEM.
HTTPService(ConnectionInfo *pConnInfo);
// Clean instance on deletion
~HTTPService();
// Sets custom HTTP options. See HTTPOptions doc for more info.
// Must be called before calling any method initiating a connection to server.
// Example:
// service.setHTTPOptions(HTTPOptions().httpReadTimeout(20000)).
void setHTTPOptions(const HTTPOptions &httpOptions);
// Returns current HTTPOption
HTTPOptions &getHTTPOptions() { return _httpOptions; }
// Performs HTTP POST by sending data. On success calls response call back
bool doPOST(const char *url, const char *data, const char *contentType, int expectedCode, httpResponseCallback cb);
// Performs HTTP POST by sending stream. On success calls response call back
bool doPOST(const char *url, Stream *stream, const char *contentType, int expectedCode, httpResponseCallback cb);
// Performs HTTP GET. On success calls response call back
bool doGET(const char *url, int expectedCode, httpResponseCallback cb);
// Performs HTTP DELETE. On success calls response call back
bool doDELETE(const char *url, int expectedCode, httpResponseCallback cb);
// Returns InfluxDBServer API URL
String getServerAPIURL() const { return _apiURL; }
// Returns value of the Retry-After HTTP header from recent call. 0 if it was missing.
int getLastRetryAfter() const { return _lastRetryAfter; }
// Returns HTTP status code of recent call.
int getLastStatusCode() const { return _lastStatusCode; }
// Returns time of recent call successful call.
uint32_t getLastRequestTime() const { return _lastRequestTime; }
// Returns response of last failed call.
String getLastErrorMessage() const { return _pConnInfo->lastError; }
// Returns true if HTTP connection is kept open
bool isConnected() const { return _httpClient && _httpClient->connected(); }
};
#endif //_HTTP_SERVICE_H_

View File

@ -1,39 +0,0 @@
/**
*
* InfluxData.cpp: InfluxDB Client for Arduino
*
* MIT License
*
* Copyright (c) 2018-2020 Tobias Schürg
*
* 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 "InfluxData.h"
#include "util/helpers.h"
void InfluxData::setTimestamp(long int seconds)
{
_timestamp = timeStampToString(seconds,9);
strcat(_timestamp, "000000000");
}
String InfluxData::toString() const {
String t;
return createLineProtocol(t);
}

View File

@ -1,37 +0,0 @@
/**
*
* InfluxData.h: InfluxDB Client for Arduino
*
* MIT License
*
* Copyright (c) 2018-2020 Tobias Schürg
*
* 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 "InfluxDbClient.h"
class InfluxData : public Point {
public:
InfluxData(String measurement) : Point(measurement) {}
void addValue(String key, float value) { addField(key, value); }
void addValueString(String key, String value) { addField(key, value); }
void setTimestamp(long int seconds);
String toString() const;
};

View File

@ -1,157 +0,0 @@
/**
*
* InfluxDb.cpp: InfluxDB Client for Arduino
*
* MIT License
*
* Copyright (c) 2018-2020 Tobias Schürg
*
* 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 "InfluxDb.h"
#include "Arduino.h"
/**
* Construct an InfluxDb instance.
* @param host the InfluxDb host
* @param port the InfluxDb port
*/
Influxdb::Influxdb(String host, uint16_t port) {
if(port == 443) {
// this happens usualy when influxdb is behind fw/proxy. Mostly, when influxdb is switched to https, the port remains the same (8086)
// port number shouldn't be qualificator for secure connection, either scheme or a flag
_connInfo.serverUrl = "https://";
} else {
_connInfo.serverUrl = "http://";
}
_connInfo.serverUrl += host + ":" + String(port);
_connInfo.dbVersion = 1;
}
/**
* Set the database to be used.
* @param db the Influx Database to be written to.
*/
void Influxdb::setDb(String db) {
_connInfo.bucket = db;
}
/**
* Set the database to be used with authentication.
*/
void Influxdb::setDbAuth(String db, String user, String pass) {
_connInfo.bucket = db;
_connInfo.user = user;
_connInfo.password = pass;
}
/**
* Set the Bucket to be used v2.0 ONLY.
* @param bucket the InfluxDB Bucket which must already exist
*/
void Influxdb::setBucket(String bucket) {
_connInfo.bucket = bucket;
}
/**
* Set the influxDB port.
* @param port both v1.x and v3 use 8086
*/
void Influxdb::setPort(uint16_t port){
int b = _connInfo.serverUrl.indexOf(":",5);
if(b > 0) {
_connInfo.serverUrl = _connInfo.serverUrl.substring(0, b+1) + String(port);
}
}
/**
* Set the Organization to be used v2.0 ONLY
* @param org the Name of the organization unit to use which must already exist
*/
void Influxdb::setOrg(String org){
_connInfo.org = org;
}
/**
* Set the authorization token v2.0 ONLY
* @param token the Auth Token from InfluxDBv2 *required*
*/
void Influxdb::setToken(String token){
_connInfo.authToken = token;
}
/**
* Set the version of InfluxDB to write to
* @param version accepts 1 for version 1.x or 2 for version 2.x
*/
void Influxdb::setVersion(uint16_t version){
_connInfo.dbVersion = version;
}
#if defined(ESP8266)
/**
* Set server certificate finger print
* @param fingerPrint server certificate finger print
*/
void Influxdb::setFingerPrint(const char *fingerPrint){
_connInfo.certInfo = fingerPrint;
}
#endif
void Influxdb::begin() {
}
/**
* Prepare a measurement to be sent.
*/
void Influxdb::prepare(InfluxData data) {
++_preparedPoints;
if(_writeOptions._batchSize <= _preparedPoints) {
// for preparation, batchsize must be greater than number of prepared points, or it will send data right away
_writeOptions._batchSize = _preparedPoints+1;
reserveBuffer(2*_writeOptions._batchSize);
}
write(data);
}
/**
* Write all prepared measurements into the db.
*/
boolean Influxdb::write() {
_preparedPoints = 0;
return flushBuffer();
}
/**
* Write a single measurement into the db.
*/
boolean Influxdb::write(InfluxData data) {
return write(pointToLineProtocol(data));
}
/**
* Send raw data to InfluxDb.
*
* @see
* https://github.com/esp8266/Arduino/blob/cc0bfa04d401810ed3f5d7d01be6e88b9011997f/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.h#L44-L55
* for a list of error codes.
*/
boolean Influxdb::write(String data) {
return writeRecord(data);
}

View File

@ -1,59 +0,0 @@
/**
*
* InfluxDb.h: InfluxDB Client for Arduino
*
* MIT License
*
* Copyright (c) 2018-2020 Tobias Schürg
*
* 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 _INFLUXDB_H_
#define _INFLUXDB_H
#include "InfluxData.h"
class Influxdb : public InfluxDBClient {
public:
Influxdb(String host, uint16_t port = 8086);
void setDb(String db);
void setDbAuth(String db, String user, String pass);
void setVersion(uint16_t version);
void setBucket(String bucket);
void setOrg(String org);
void setToken(String token);
void setPort(uint16_t port);
#if defined(ESP8266)
void setFingerPrint(const char *fingerPrint);
#endif
void prepare(InfluxData data);
boolean write();
boolean write(InfluxData data);
boolean write(String data);
private:
uint16_t _preparedPoints;
void begin();
};
#endif

View File

@ -1,778 +0,0 @@
/**
*
* InfluxDBClient.cpp: InfluxDB Client for Arduino
*
* MIT License
*
* Copyright (c) 2020 InfluxData
*
* 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 "InfluxDbClient.h"
#include "Platform.h"
#include "Version.h"
#include "util/debug.h"
static const char TooEarlyMessage[] PROGMEM = "Cannot send request yet because of applied retry strategy. Remaining ";
static String escapeJSONString(const String &value);
static String precisionToString(WritePrecision precision, uint8_t version = 2) {
switch(precision) {
case WritePrecision::US:
return version==1?"u":"us";
case WritePrecision::MS:
return "ms";
case WritePrecision::NS:
return "ns";
case WritePrecision::S:
return "s";
default:
return "";
}
}
InfluxDBClient::InfluxDBClient() {
resetBuffer();
}
InfluxDBClient::InfluxDBClient(const String &serverUrl, const String &db):InfluxDBClient() {
setConnectionParamsV1(serverUrl, db);
}
InfluxDBClient::InfluxDBClient(const String &serverUrl, const String &org, const String &bucket, const String &authToken):InfluxDBClient(serverUrl, org, bucket, authToken, nullptr) {
}
InfluxDBClient::InfluxDBClient(const String &serverUrl, const String &org, const String &bucket, const String &authToken, const char *serverCert):InfluxDBClient() {
setConnectionParams(serverUrl, org, bucket, authToken, serverCert);
}
void InfluxDBClient::setInsecure(bool value){
_connInfo.insecure = value;
}
void InfluxDBClient::setConnectionParams(const String &serverUrl, const String &org, const String &bucket, const String &authToken, const char *certInfo) {
clean();
_connInfo.serverUrl = serverUrl;
_connInfo.bucket = bucket;
_connInfo.org = org;
_connInfo.authToken = authToken;
_connInfo.certInfo = certInfo;
_connInfo.dbVersion = 2;
}
void InfluxDBClient::setConnectionParamsV1(const String &serverUrl, const String &db, const String &user, const String &password, const char *certInfo) {
clean();
_connInfo.serverUrl = serverUrl;
_connInfo.bucket = db;
_connInfo.user = user;
_connInfo.password = password;
_connInfo.certInfo = certInfo;
_connInfo.dbVersion = 1;
}
bool InfluxDBClient::init() {
INFLUXDB_CLIENT_DEBUG("[D] Init\n");
INFLUXDB_CLIENT_DEBUG("[D] Library version: " INFLUXDB_CLIENT_VERSION "\n");
INFLUXDB_CLIENT_DEBUG("[D] Device : " INFLUXDB_CLIENT_PLATFORM "\n");
INFLUXDB_CLIENT_DEBUG("[D] SDK version: " INFLUXDB_CLIENT_PLATFORM_VERSION "\n");
INFLUXDB_CLIENT_DEBUG("[D] Server url: %s\n", _connInfo.serverUrl.c_str());
INFLUXDB_CLIENT_DEBUG("[D] Org: %s\n", _connInfo.org.c_str());
INFLUXDB_CLIENT_DEBUG("[D] Bucket: %s\n", _connInfo.bucket.c_str());
INFLUXDB_CLIENT_DEBUG("[D] Token: %s\n", _connInfo.authToken.c_str());
INFLUXDB_CLIENT_DEBUG("[D] DB version: %d\n", _connInfo.dbVersion);
if(_connInfo.serverUrl.length() == 0 || (_connInfo.dbVersion == 2 && (_connInfo.org.length() == 0 || _connInfo.bucket.length() == 0 || _connInfo.authToken.length() == 0))) {
INFLUXDB_CLIENT_DEBUG("[E] Invalid parameters\n");
_connInfo.lastError = F("Invalid parameters");
return false;
}
if(_connInfo.serverUrl.endsWith("/")) {
_connInfo.serverUrl = _connInfo.serverUrl.substring(0,_connInfo.serverUrl.length()-1);
}
if(!_connInfo.serverUrl.startsWith("http")) {
_connInfo.lastError = F("Invalid URL scheme");
return false;
}
_service = new HTTPService(&_connInfo);
setUrls();
return true;
}
InfluxDBClient::~InfluxDBClient() {
if(_writeBuffer) {
for(int i=0;i<_writeBufferSize;i++) {
delete _writeBuffer[i];
}
delete [] _writeBuffer;
_writeBuffer = nullptr;
_bufferPointer = 0;
_batchPointer = 0;
_bufferCeiling = 0;
}
clean();
}
void InfluxDBClient::clean() {
if(_service) {
delete _service;
_service = nullptr;
}
_buckets = nullptr;
_lastFlushed = millis();
_retryTime = 0;
}
bool InfluxDBClient::setUrls() {
if(!_service && !init()) {
return false;
}
INFLUXDB_CLIENT_DEBUG("[D] setUrls\n");
if( _connInfo.dbVersion == 2) {
_writeUrl = _service->getServerAPIURL();
_writeUrl += "write?org=";
_writeUrl += urlEncode(_connInfo.org.c_str());
_writeUrl += "&bucket=";
_writeUrl += urlEncode(_connInfo.bucket.c_str());
INFLUXDB_CLIENT_DEBUG("[D] writeUrl: %s\n", _writeUrl.c_str());
_queryUrl = _service->getServerAPIURL();;
_queryUrl += "query?org=";
_queryUrl += urlEncode(_connInfo.org.c_str());
INFLUXDB_CLIENT_DEBUG("[D] queryUrl: %s\n", _queryUrl.c_str());
} else {
_writeUrl = _connInfo.serverUrl;
_writeUrl += "/write?db=";
_writeUrl += urlEncode(_connInfo.bucket.c_str());
_queryUrl = _connInfo.serverUrl;
_queryUrl += "/api/v2/query";
if(_connInfo.user.length() > 0 && _connInfo.password.length() > 0) {
String auth = "&u=";
auth += urlEncode(_connInfo.user.c_str());
auth += "&p=";
auth += urlEncode(_connInfo.password.c_str());
_writeUrl += auth;
_queryUrl += "?";
_queryUrl += auth;
}
INFLUXDB_CLIENT_DEBUG("[D] writeUrl: %s\n", _writeUrl.c_str());
INFLUXDB_CLIENT_DEBUG("[D] queryUrl: %s\n", _queryUrl.c_str());
}
if(_writeOptions._writePrecision != WritePrecision::NoTime) {
_writeUrl += "&precision=";
_writeUrl += precisionToString(_writeOptions._writePrecision, _connInfo.dbVersion);
INFLUXDB_CLIENT_DEBUG("[D] writeUrl: %s\n", _writeUrl.c_str());
}
return true;
}
bool InfluxDBClient::setWriteOptions(WritePrecision precision, uint16_t batchSize, uint16_t bufferSize, uint16_t flushInterval, bool preserveConnection) {
if(!_service && !init()) {
return false;
}
if(!setWriteOptions(WriteOptions().writePrecision(precision).batchSize(batchSize).bufferSize(bufferSize).flushInterval(flushInterval))) {
return false;
}
if(!setHTTPOptions(_service->getHTTPOptions().connectionReuse(preserveConnection))) {
return false;
}
return true;
}
bool InfluxDBClient::setWriteOptions(const WriteOptions & writeOptions) {
if(_writeOptions._writePrecision != writeOptions._writePrecision) {
_writeOptions._writePrecision = writeOptions._writePrecision;
if(!setUrls()) {
return false;
}
}
bool writeBufferSizeChanges = false;
if(writeOptions._batchSize > 0 && _writeOptions._batchSize != writeOptions._batchSize) {
_writeOptions._batchSize = writeOptions._batchSize;
writeBufferSizeChanges = true;
}
if(writeOptions._bufferSize > 0 && _writeOptions._bufferSize != writeOptions._bufferSize) {
_writeOptions._bufferSize = writeOptions._bufferSize;
if(_writeOptions._bufferSize < 2*_writeOptions._batchSize) {
_writeOptions._bufferSize = 2*_writeOptions._batchSize;
INFLUXDB_CLIENT_DEBUG("[D] Changing buffer size to %d\n", _writeOptions._bufferSize);
}
writeBufferSizeChanges = true;
}
if(writeBufferSizeChanges) {
resetBuffer();
}
_writeOptions._flushInterval = writeOptions._flushInterval;
_writeOptions._retryInterval = writeOptions._retryInterval;
_writeOptions._maxRetryInterval = writeOptions._maxRetryInterval;
_writeOptions._maxRetryAttempts = writeOptions._maxRetryAttempts;
_writeOptions._defaultTags = writeOptions._defaultTags;
return true;
}
bool InfluxDBClient::setHTTPOptions(const HTTPOptions & httpOptions) {
if(!_service && !init()) {
return false;
}
_service->setHTTPOptions(httpOptions);
return true;
}
BucketsClient InfluxDBClient::getBucketsClient() {
if(!_service && !init()) {
return BucketsClient();
}
if(!_buckets) {
_buckets = BucketsClient(&_connInfo, _service);
}
return _buckets;
}
void InfluxDBClient::resetBuffer() {
if(_writeBuffer) {
for(int i=0;i<_writeBufferSize;i++) {
delete _writeBuffer[i];
}
delete [] _writeBuffer;
}
INFLUXDB_CLIENT_DEBUG("[D] Reset buffer: buffer Size: %d, batch size: %d\n", _writeOptions._bufferSize, _writeOptions._batchSize);
uint16_t a = _writeOptions._bufferSize/_writeOptions._batchSize;
//limit to max(byte)
_writeBufferSize = a>=(1<<8)?(1<<8)-1:a;
if(_writeBufferSize < 2) {
_writeBufferSize = 2;
}
INFLUXDB_CLIENT_DEBUG("[D] Reset buffer: writeBuffSize: %d\n", _writeBufferSize);
_writeBuffer = new Batch*[_writeBufferSize];
for(int i=0;i<_writeBufferSize;i++) {
_writeBuffer[i] = nullptr;
}
_bufferPointer = 0;
_batchPointer = 0;
_bufferCeiling = 0;
}
void InfluxDBClient::reserveBuffer(int size) {
if(size > _writeBufferSize) {
Batch **newBuffer = new Batch*[size];
INFLUXDB_CLIENT_DEBUG("[D] Resizing buffer from %d to %d\n",_writeBufferSize, size);
for(int i=0;i<_bufferCeiling; i++) {
newBuffer[i] = _writeBuffer[i];
}
delete [] _writeBuffer;
_writeBuffer = newBuffer;
_writeBufferSize = size;
}
}
void InfluxDBClient::addZerosToTimestamp(Point &point, int zeroes) {
char *ts = point._timestamp, *s;
point._timestamp = new char[strlen(point._timestamp) + 1 + zeroes];
strcpy(point._timestamp, ts);
s = point._timestamp+strlen(ts);
for(int i=0;i<zeroes;i++) {
*s++ = '0';
}
*s = 0;
delete [] ts;
}
void InfluxDBClient::checkPrecisions(Point & point) {
if(_writeOptions._writePrecision != WritePrecision::NoTime) {
if(!point.hasTime()) {
point.setTime(_writeOptions._writePrecision);
// Check different write precisions
} else if(point._tsWritePrecision != WritePrecision::NoTime && point._tsWritePrecision != _writeOptions._writePrecision) {
int diff = int(point._tsWritePrecision) - int(_writeOptions._writePrecision);
if(diff > 0) { //point has higher precision, cut
point._timestamp[strlen(point._timestamp)-diff*3] = 0;
} else { //point has lower precision, add zeroes
addZerosToTimestamp(point, diff*-3);
}
}
// check someone set WritePrecision on point and not on client. NS precision is ok, cause it is default on server
} else if(point.hasTime() && point._tsWritePrecision != WritePrecision::NoTime && point._tsWritePrecision != WritePrecision::NS) {
int diff = int(WritePrecision::NS) - int(point._tsWritePrecision);
addZerosToTimestamp(point, diff*3);
}
}
bool InfluxDBClient::writePoint(Point & point) {
if (point.hasFields()) {
checkPrecisions(point);
String line = pointToLineProtocol(point);
return writeRecord(line);
}
return false;
}
InfluxDBClient::Batch::Batch(uint16_t size):_size(size) {
buffer = new char*[size];
for(int i=0;i< _size; i++) {
buffer[i] = nullptr;
}
}
InfluxDBClient::Batch::~Batch() {
clear();
delete [] buffer;
buffer = nullptr;
}
void InfluxDBClient::Batch::clear() {
for(int i=0;i< _size; i++) {
free(buffer[i]);
buffer[i] = nullptr;
}
}
bool InfluxDBClient::Batch::append(const char *line) {
if(pointer == _size) {
//overwriting, clean buffer
clear();
pointer = 0;
}
buffer[pointer] = strdup(line);
++pointer;
return isFull();
}
char * InfluxDBClient::Batch::createData() {
int length = 0;
char *buff = nullptr;
for(int c=0; c < pointer; c++) {
length += strlen(buffer[c]);
yield();
}
//create buffer for all lines including new line char and terminating char
if(length) {
buff = new char[length + pointer + 1];
if(buff) {
buff[0] = 0;
for(int c=0; c < pointer; c++) {
strcat(buff+strlen(buff), buffer[c]);
strcat(buff+strlen(buff), "\n");
yield();
}
}
}
return buff;
}
bool InfluxDBClient::writeRecord(const String &record) {
return writeRecord(record.c_str());
}
bool InfluxDBClient::writeRecord(const char *record) {
if(!_writeBuffer[_bufferPointer]) {
_writeBuffer[_bufferPointer] = new Batch(_writeOptions._batchSize);
}
if(isBufferFull() && _batchPointer <= _bufferPointer) {
// When we are overwriting buffer and nothing is written, batchPointer must point to the oldest point
_batchPointer = _bufferPointer+1;
if(_batchPointer == _writeBufferSize) {
_batchPointer = 0;
}
}
if(_writeBuffer[_bufferPointer]->append(record)) { //we reached batch size
_bufferPointer++;
if(_bufferPointer == _writeBufferSize) { // writeBuffer is full
_bufferPointer = 0;
INFLUXDB_CLIENT_DEBUG("[W] Reached write buffer size, old points will be overwritten\n");
}
if(_bufferCeiling < _writeBufferSize) {
_bufferCeiling++;
}
}
INFLUXDB_CLIENT_DEBUG("[D] writeRecord: bufferPointer: %d, batchPointer: %d, _bufferCeiling: %d\n", _bufferPointer, _batchPointer, _bufferCeiling);
return checkBuffer();
}
bool InfluxDBClient::checkBuffer() {
// in case we (over)reach batchSize with non full buffer
bool bufferReachedBatchsize = _writeBuffer[_batchPointer] && _writeBuffer[_batchPointer]->isFull();
// or flush interval timed out
bool flushTimeout = _writeOptions._flushInterval > 0 && ((millis() - _lastFlushed)/1000) >= _writeOptions._flushInterval;
INFLUXDB_CLIENT_DEBUG("[D] Flushing buffer: is oversized %s, is timeout %s, is buffer full %s\n",
bool2string(bufferReachedBatchsize),bool2string(flushTimeout), bool2string(isBufferFull()));
if(bufferReachedBatchsize || flushTimeout || isBufferFull() ) {
return flushBufferInternal(!flushTimeout);
}
return true;
}
bool InfluxDBClient::flushBuffer() {
return flushBufferInternal(false);
}
uint32_t InfluxDBClient::getRemainingRetryTime() {
uint32_t rem = 0;
if(_retryTime > 0) {
int32_t diff = _retryTime - (millis()-_service->getLastRequestTime())/1000;
rem = diff<0?0:(uint32_t)diff;
}
return rem;
}
bool InfluxDBClient::flushBufferInternal(bool flashOnlyFull) {
uint32_t rwt = getRemainingRetryTime();
if(rwt > 0) {
INFLUXDB_CLIENT_DEBUG("[W] Cannot write yet, pause %ds, %ds yet\n", _retryTime, rwt);
// retry after period didn't run out yet
_connInfo.lastError = FPSTR(TooEarlyMessage);
_connInfo.lastError += String(rwt);
_connInfo.lastError += "s";
return false;
}
char *data;
bool success = true;
// send all batches, It could happen there was long network outage and buffer is full
while(_writeBuffer[_batchPointer] && (!flashOnlyFull || _writeBuffer[_batchPointer]->isFull())) {
if(!_writeBuffer[_batchPointer]->isFull() && _writeBuffer[_batchPointer]->retryCount == 0 ) { //do not increase pointer in case of retrying
// points will be written so increase _bufferPointer as it happen when buffer is flushed when is full
if(++_bufferPointer == _writeBufferSize) {
_bufferPointer = 0;
}
}
INFLUXDB_CLIENT_DEBUG("[D] Writing batch, batchpointer: %d, size %d\n", _batchPointer, _writeBuffer[_batchPointer]->pointer);
if(!_writeBuffer[_batchPointer]->isEmpty()) {
int statusCode = 0;
if(_streamWrite) {
statusCode = postData(_writeBuffer[_batchPointer]);
} else {
data = _writeBuffer[_batchPointer]->createData();
statusCode = postData(data);
delete [] data;
}
// retry on unsuccessfull connection or retryable status codes
bool retry = (statusCode < 0 || statusCode >= 429) && _writeOptions._maxRetryAttempts > 0;
success = statusCode >= 200 && statusCode < 300;
// advance even on message failure x e <300;429)
if(success || !retry) {
_lastFlushed = millis();
dropCurrentBatch();
} else if(retry) {
_writeBuffer[_batchPointer]->retryCount++;
if(statusCode > 0) { //apply retry strategy only in case of HTTP errors
if(_writeBuffer[_batchPointer]->retryCount > _writeOptions._maxRetryAttempts) {
INFLUXDB_CLIENT_DEBUG("[D] Reached max retry count, dropping batch\n");
dropCurrentBatch();
}
if(!_retryTime) {
_retryTime = _writeOptions._retryInterval;
if(_writeBuffer[_batchPointer]) {
for(int i=1;i<_writeBuffer[_batchPointer]->retryCount;i++) {
_retryTime *= _writeOptions._retryInterval;
}
if(_retryTime > _writeOptions._maxRetryInterval) {
_retryTime = _writeOptions._maxRetryInterval;
}
}
}
}
INFLUXDB_CLIENT_DEBUG("[D] Leaving data in buffer for retry, retryInterval: %d\n",_retryTime);
// in case of retryable failure break loop
break;
}
}
yield();
}
//Have we emptied the buffer?
INFLUXDB_CLIENT_DEBUG("[D] Success: %d, _bufferPointer: %d, _batchPointer: %d, _writeBuffer[_bufferPointer]_%p\n",success,_bufferPointer,_batchPointer, _writeBuffer[_bufferPointer]);
if(_batchPointer == _bufferPointer && !_writeBuffer[_bufferPointer]) {
_bufferPointer = 0;
_batchPointer = 0;
_bufferCeiling = 0;
INFLUXDB_CLIENT_DEBUG("[D] Buffer empty\n");
}
return success;
}
void InfluxDBClient::dropCurrentBatch() {
delete _writeBuffer[_batchPointer];
_writeBuffer[_batchPointer] = nullptr;
_batchPointer++;
//did we got over top?
if(_batchPointer == _writeBufferSize) {
// restart _batchPointer in ring buffer from start
_batchPointer = 0;
// we reached buffer size, that means buffer was full and now lower ceiling
_bufferCeiling = _bufferPointer;
}
INFLUXDB_CLIENT_DEBUG("[D] Dropped batch, batchpointer: %d\n", _batchPointer);
}
String InfluxDBClient::pointToLineProtocol(const Point& point) {
return point.createLineProtocol(_writeOptions._defaultTags);
}
bool InfluxDBClient::validateConnection() {
if(!_service && !init()) {
return false;
}
// on version 1.x /ping will by default return status code 204, without verbose
String url = _connInfo.serverUrl + (_connInfo.dbVersion==2?"/health":"/ping?verbose=true");
if(_connInfo.dbVersion==1 && _connInfo.user.length() > 0 && _connInfo.password.length() > 0) {
url += "&u=";
url += urlEncode(_connInfo.user.c_str());
url += "&p=";
url += urlEncode(_connInfo.password.c_str());
}
INFLUXDB_CLIENT_DEBUG("[D] Validating connection to %s\n", url.c_str());
bool ret = _service->doGET(url.c_str(), 200, nullptr);
if(!ret) {
INFLUXDB_CLIENT_DEBUG("[D] error %d: %s\n", _service->getLastStatusCode(), _service->getLastErrorMessage().c_str());
}
return ret;
}
int InfluxDBClient::postData(const char *data) {
if(!_service && !init()) {
return 0;
}
if(data) {
INFLUXDB_CLIENT_DEBUG("[D] Writing to %s\n", _writeUrl.c_str());
INFLUXDB_CLIENT_DEBUG("[D] Sending:\n%s\n", data);
if(!_service->doPOST(_writeUrl.c_str(), data, PSTR("text/plain"), 204, nullptr)) {
INFLUXDB_CLIENT_DEBUG("[D] error %d: %s\n", _service->getLastStatusCode(), _service->getLastErrorMessage().c_str());
}
_retryTime = _service->getLastRetryAfter();
return _service->getLastStatusCode();
}
return 0;
}
int InfluxDBClient::postData(Batch *batch) {
if(!_service && !init()) {
return 0;
}
BatchStreamer *bs = new BatchStreamer(batch);
INFLUXDB_CLIENT_DEBUG("[D] Writing to %s\n", _writeUrl.c_str());
INFLUXDB_CLIENT_DEBUG("[D] Sending:\n");
if(!_service->doPOST(_writeUrl.c_str(), bs, PSTR("text/plain"), 204, nullptr)) {
INFLUXDB_CLIENT_DEBUG("[D] error %d: %s\n", _service->getLastStatusCode(), _service->getLastErrorMessage().c_str());
}
delete bs;
_retryTime = _service->getLastRetryAfter();
return _service->getLastStatusCode();
}
void InfluxDBClient::setStreamWrite(bool enable) {
_streamWrite = enable;
}
static const char QueryDialect[] PROGMEM = "\
\"dialect\": {\
\"annotations\": [\
\"datatype\"\
],\
\"dateTimeFormat\": \"RFC3339\",\
\"header\": true,\
\"delimiter\": \",\",\
\"commentPrefix\": \"#\"\
}";
static const char Params[] PROGMEM = ",\
\"params\": {";
FluxQueryResult InfluxDBClient::query(const String &fluxQuery) {
return query(fluxQuery, QueryParams());
}
FluxQueryResult InfluxDBClient::query(const String &fluxQuery, QueryParams params) {
uint32_t rwt = getRemainingRetryTime();
if(rwt > 0) {
INFLUXDB_CLIENT_DEBUG("[W] Cannot query yet, pause %ds, %ds yet\n", _retryTime, rwt);
// retry after period didn't run out yet
String mess = FPSTR(TooEarlyMessage);
mess += String(rwt);
mess += "s";
return FluxQueryResult(mess);
}
if(!_service && !init()) {
return FluxQueryResult(_connInfo.lastError);
}
INFLUXDB_CLIENT_DEBUG("[D] Query to %s\n", _queryUrl.c_str());
INFLUXDB_CLIENT_DEBUG("[D] JSON query:\n%s\n", fluxQuery.c_str());
String queryEsc = escapeJSONString(fluxQuery);
String body;
body.reserve(150 + queryEsc.length() + params.size()*30);
body = F("{\"type\":\"flux\",\"query\":\"");
body += queryEsc;
body += "\",";
body += FPSTR(QueryDialect);
if(params.size()) {
body += FPSTR(Params);
body += params.jsonString(0);
for(int i=1;i<params.size();i++) {
body +=",";
char *js = params.jsonString(i);
body += js;
delete [] js;
}
body += '}';
}
body += '}';
CsvReader *reader = nullptr;
_retryTime = 0;
INFLUXDB_CLIENT_DEBUG("[D] Query: %s\n", body.c_str());
if(_service->doPOST(_queryUrl.c_str(), body.c_str(), PSTR("application/json"), 200, [&](HTTPClient *httpClient){
bool chunked = false;
if(httpClient->hasHeader(TransferEncoding)) {
String header = httpClient->header(TransferEncoding);
chunked = header.equalsIgnoreCase("chunked");
}
INFLUXDB_CLIENT_DEBUG("[D] chunked: %s\n", bool2string(chunked));
HttpStreamScanner *scanner = new HttpStreamScanner(httpClient, chunked);
reader = new CsvReader(scanner);
return false;
})) {
return FluxQueryResult(reader);
} else {
_retryTime = _service->getLastRetryAfter();
return FluxQueryResult(_service->getLastErrorMessage());
}
}
static String escapeJSONString(const String &value) {
String ret;
int d = 0;
int i,from = 0;
while((i = value.indexOf('"',from)) > -1) {
d++;
if(i == (int)value.length()-1) {
break;
}
from = i+1;
}
ret.reserve(value.length()+d); //most probably we will escape just double quotes
for (char c: value)
{
switch (c)
{
case '"': ret += "\\\""; break;
case '\\': ret += "\\\\"; break;
case '\b': ret += "\\b"; break;
case '\f': ret += "\\f"; break;
case '\n': ret += "\\n"; break;
case '\r': ret += "\\r"; break;
case '\t': ret += "\\t"; break;
default:
if (c <= '\x1f') {
ret += "\\u";
char buf[3 + 8 * sizeof(unsigned int)];
sprintf(buf, "\\u%04u", c);
ret += buf;
} else {
ret += c;
}
}
}
return ret;
}
InfluxDBClient::BatchStreamer::BatchStreamer(InfluxDBClient::Batch *batch) {
_batch = batch;
_read = 0;
_length = 0;
_pointer = 0;
_linePointer = 0;
for(uint16_t i=0;i<_batch->pointer;i++) {
_length += strlen(_batch->buffer[i])+1;
}
}
int InfluxDBClient::BatchStreamer::available() {
return _length-_read;
}
int InfluxDBClient::BatchStreamer::availableForWrite() {
return 0;
}
#if defined(ESP8266)
int InfluxDBClient::BatchStreamer::read(uint8_t* buffer, size_t len) {
INFLUXDB_CLIENT_DEBUG("BatchStream::read %d\n", len);
return readBytes((char *)buffer, len);
}
#endif
size_t InfluxDBClient::BatchStreamer::readBytes(char* buffer, size_t len) {
INFLUXDB_CLIENT_DEBUG("BatchStream::readBytes %d\n", len);
unsigned int r=0;
for(unsigned int i=0;i<len;i++) {
if(available()) {
buffer[i] = read();
r++;
} else {
break;
}
}
return r;
}
int InfluxDBClient::BatchStreamer::read() {
int r = peek();
if(r > 0) {
++_read;
++_linePointer;
if(!_batch->buffer[_pointer][_linePointer-1]) {
++_pointer;
_linePointer = 0;
}
}
return r;
}
int InfluxDBClient::BatchStreamer::peek() {
if(_pointer == _batch->pointer) {
//This should not happen
return -1;
}
int r;
if(!_batch->buffer[_pointer][_linePointer]) {
r = '\n';
} else {
r = _batch->buffer[_pointer][_linePointer];
}
return r;
}
size_t InfluxDBClient::BatchStreamer::write(uint8_t) {
return 0;
}

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