Commit 34496cfe authored by Eric Duminil's avatar Eric Duminil
Browse files

Merge branch 'experimental/update_libs' into develop

parents 67301e9e 67095fcf
Pipeline #5759 passed with stage
in 2 minutes and 1 second
......@@ -6,6 +6,10 @@
#include "sensor_console.h"
#include <Wire.h>
// The SCD30 from Sensirion is a high quality Nondispersive Infrared (NDIR) based CO₂ sensor capable of detecting 400 to 10000ppm with an accuracy of ±(30ppm+3%).
// https://github.com/sparkfun/SparkFun_SCD30_Arduino_Library
#include "src/lib/SparkFun_SCD30_Arduino_Library/src/SparkFun_SCD30_Arduino_Library.h" // From: http://librarymanager/All#SparkFun_SCD30
namespace config {
// UPPERCASE values should be defined in config.h
uint16_t measurement_timestep = MEASUREMENT_TIMESTEP; // [s] Value between 2 and 1800 (range for SCD30 sensor).
......
#ifndef CO2_SENSOR_H_
#define CO2_SENSOR_H_
// The SCD30 from Sensirion is a high quality Nondispersive Infrared (NDIR) based CO₂ sensor capable of detecting 400 to 10000ppm with an accuracy of ±(30ppm+3%).
// https://github.com/sparkfun/SparkFun_SCD30_Arduino_Library
#include "src/lib/SparkFun_SCD30_Arduino_Library/src/SparkFun_SCD30_Arduino_Library.h" // From: http://librarymanager/All#SparkFun_SCD30
#include <stdint.h> // For uint16_t
namespace config {
extern uint16_t measurement_timestep; // [s] Value between 2 and 1800 (range for SCD30 sensor)
......@@ -13,7 +11,6 @@ namespace config {
}
namespace sensor {
extern SCD30 scd30;
extern uint16_t co2;
extern float temperature;
extern float humidity;
......
......@@ -2,7 +2,7 @@
#include "sensor_console.h"
#include "config.h"
#include <WiFiUdp.h> // required for NTP
#include "src/lib/NTPClient-master/NTPClient.h" // NTP
#include "src/lib/NTPClient/NTPClient.h" // NTP
namespace config {
const char *ntp_server = NTP_SERVER;
......
......@@ -2253,10 +2253,11 @@ void Adafruit_NeoPixel::show(void) {
}
// END of NRF52 implementation
#elif defined(__SAMD21E17A__) || defined(__SAMD21G18A__) || \
defined(__SAMD21E18A__) || \
defined(__SAMD21J18A__) // Arduino Zero, Gemma/Trinket M0, SODAQ Autonomo
// and others
#elif defined(__SAMD21E17A__) || defined(__SAMD21G18A__) || \
defined(__SAMD21E18A__) || defined(__SAMD21J18A__) || \
defined (__SAMD11C14A__)
// Arduino Zero, Gemma/Trinket M0, SODAQ Autonomo
// and others
// Tried this with a timer/counter, couldn't quite get adequate
// resolution. So yay, you get a load of goofball NOPs...
......
name=Adafruit NeoPixel
version=1.10.3
version=1.10.4
author=Adafruit
maintainer=Adafruit <info@adafruit.com>
sentence=Arduino library for controlling single-wire-based LED pixels and strip.
......
language: c
sudo: false
before_install:
- source <(curl -SLs https://raw.githubusercontent.com/adafruit/travis-ci-arduino/master/install.sh)
script:
- build_platform esp8266
notifications:
email:
on_success: change
on_failure: change
......@@ -25,7 +25,7 @@ NTPClient::NTPClient(UDP& udp) {
this->_udp = &udp;
}
NTPClient::NTPClient(UDP& udp, int timeOffset) {
NTPClient::NTPClient(UDP& udp, long timeOffset) {
this->_udp = &udp;
this->_timeOffset = timeOffset;
}
......@@ -35,24 +35,45 @@ NTPClient::NTPClient(UDP& udp, const char* poolServerName) {
this->_poolServerName = poolServerName;
}
NTPClient::NTPClient(UDP& udp, const char* poolServerName, int timeOffset) {
NTPClient::NTPClient(UDP& udp, IPAddress poolServerIP) {
this->_udp = &udp;
this->_poolServerIP = poolServerIP;
this->_poolServerName = NULL;
}
NTPClient::NTPClient(UDP& udp, const char* poolServerName, long timeOffset) {
this->_udp = &udp;
this->_timeOffset = timeOffset;
this->_poolServerName = poolServerName;
}
NTPClient::NTPClient(UDP& udp, const char* poolServerName, int timeOffset, unsigned long updateInterval) {
NTPClient::NTPClient(UDP& udp, IPAddress poolServerIP, long timeOffset){
this->_udp = &udp;
this->_timeOffset = timeOffset;
this->_poolServerIP = poolServerIP;
this->_poolServerName = NULL;
}
NTPClient::NTPClient(UDP& udp, const char* poolServerName, long timeOffset, unsigned long updateInterval) {
this->_udp = &udp;
this->_timeOffset = timeOffset;
this->_poolServerName = poolServerName;
this->_updateInterval = updateInterval;
}
NTPClient::NTPClient(UDP& udp, IPAddress poolServerIP, long timeOffset, unsigned long updateInterval) {
this->_udp = &udp;
this->_timeOffset = timeOffset;
this->_poolServerIP = poolServerIP;
this->_poolServerName = NULL;
this->_updateInterval = updateInterval;
}
void NTPClient::begin() {
this->begin(NTP_DEFAULT_LOCAL_PORT);
}
void NTPClient::begin(int port) {
void NTPClient::begin(unsigned int port) {
this->_port = port;
this->_udp->begin(this->_port);
......@@ -60,37 +81,15 @@ void NTPClient::begin(int port) {
this->_udpSetup = true;
}
bool NTPClient::isValid(byte * ntpPacket)
{
//Perform a few validity checks on the packet
if((ntpPacket[0] & 0b11000000) == 0b11000000) //Check for LI=UNSYNC
return false;
if((ntpPacket[0] & 0b00111000) >> 3 < 0b100) //Check for Version >= 4
return false;
if((ntpPacket[0] & 0b00000111) != 0b100) //Check for Mode == Server
return false;
if((ntpPacket[1] < 1) || (ntpPacket[1] > 15)) //Check for valid Stratum
return false;
if( ntpPacket[16] == 0 && ntpPacket[17] == 0 &&
ntpPacket[18] == 0 && ntpPacket[19] == 0 &&
ntpPacket[20] == 0 && ntpPacket[21] == 0 &&
ntpPacket[22] == 0 && ntpPacket[22] == 0) //Check for ReferenceTimestamp != 0
return false;
return true;
}
bool NTPClient::forceUpdate() {
#ifdef DEBUG_NTPClient
Serial.println("Update from NTP Server");
#endif
// flush any existing packets
while(this->_udp->parsePacket() != 0)
this->_udp->flush();
this->sendNTPPacket();
// Wait till data is there or timeout...
......@@ -99,20 +98,14 @@ bool NTPClient::forceUpdate() {
do {
delay ( 10 );
cb = this->_udp->parsePacket();
if(cb > 0)
{
this->_udp->read(this->_packetBuffer, NTP_PACKET_SIZE);
if(!this->isValid(this->_packetBuffer))
cb = 0;
}
if (timeout > 100) return false; // timeout after 1000 ms
timeout++;
} while (cb == 0);
this->_lastUpdate = millis() - (10 * (timeout + 1)); // Account for delay in reading the time
this->_udp->read(this->_packetBuffer, NTP_PACKET_SIZE);
unsigned long highWord = word(this->_packetBuffer[40], this->_packetBuffer[41]);
unsigned long lowWord = word(this->_packetBuffer[42], this->_packetBuffer[43]);
// combine the four bytes (two words) into a long integer
......@@ -121,73 +114,53 @@ bool NTPClient::forceUpdate() {
this->_currentEpoc = secsSince1900 - SEVENZYYEARS;
return true;
return true; // return true after successful update
}
bool NTPClient::update() {
if ((millis() - this->_lastUpdate >= this->_updateInterval) // Update after _updateInterval
|| this->_lastUpdate == 0) { // Update if there was no update yet.
if (!this->_udpSetup) this->begin(); // setup the UDP client if needed
if (!this->_udpSetup || this->_port != NTP_DEFAULT_LOCAL_PORT) this->begin(this->_port); // setup the UDP client if needed
return this->forceUpdate();
}
return true;
return false; // return false if update does not occur
}
bool NTPClient::isTimeSet() const {
return (this->_lastUpdate != 0); // returns true if the time has been set, else false
}
unsigned long NTPClient::getEpochTime() {
unsigned long NTPClient::getEpochTime() const {
return this->_timeOffset + // User offset
this->_currentEpoc + // Epoc returned by the NTP server
this->_currentEpoc + // Epoch returned by the NTP server
((millis() - this->_lastUpdate) / 1000); // Time since last update
}
int NTPClient::getDay() {
int NTPClient::getDay() const {
return (((this->getEpochTime() / 86400L) + 4 ) % 7); //0 is Sunday
}
int NTPClient::getHours() {
int NTPClient::getHours() const {
return ((this->getEpochTime() % 86400L) / 3600);
}
int NTPClient::getMinutes() {
int NTPClient::getMinutes() const {
return ((this->getEpochTime() % 3600) / 60);
}
int NTPClient::getSeconds() {
int NTPClient::getSeconds() const {
return (this->getEpochTime() % 60);
}
void NTPClient::getFormattedTime(char *formatted_time, unsigned long secs) {
unsigned long rawTime = secs ? secs : this->getEpochTime();
unsigned int hours = (rawTime % 86400L) / 3600;
unsigned int minutes = (rawTime % 3600) / 60;
unsigned int seconds = rawTime % 60;
snprintf(formatted_time, 9, "%02d:%02d:%02d", hours, minutes, seconds);
}
String NTPClient::getFormattedTime() const {
unsigned long rawTime = this->getEpochTime();
unsigned long hours = (rawTime % 86400L) / 3600;
String hoursStr = hours < 10 ? "0" + String(hours) : String(hours);
// Based on https://github.com/PaulStoffregen/Time/blob/master/Time.cpp
void NTPClient::getFormattedDate(char *formatted_date, unsigned long secs) {
unsigned long rawTime = (secs ? secs : this->getEpochTime()) / 86400L; // in days
unsigned long days = 0, year = 1970;
uint8_t month;
static const uint8_t monthDays[]={31,28,31,30,31,30,31,31,30,31,30,31};
unsigned long minutes = (rawTime % 3600) / 60;
String minuteStr = minutes < 10 ? "0" + String(minutes) : String(minutes);
while((days += (LEAP_YEAR(year) ? 366 : 365)) <= rawTime)
year++;
rawTime -= days - (LEAP_YEAR(year) ? 366 : 365); // now it is days in this year, starting at 0
days=0;
for (month=0; month<12; month++) {
uint8_t monthLength;
if (month==1) { // february
monthLength = LEAP_YEAR(year) ? 29 : 28;
} else {
monthLength = monthDays[month];
}
if (rawTime < monthLength) break;
rawTime -= monthLength;
}
month++; // jan is month 1
rawTime++; // first day is day 1
unsigned long seconds = rawTime % 60;
String secondStr = seconds < 10 ? "0" + String(seconds) : String(seconds);
char formatted_time[9];
this->getFormattedTime(formatted_time, secs);
snprintf(formatted_date, 23, "%4lu-%02d-%02lu %s%+03d", year, month, rawTime, formatted_time, this->_timeOffset / 3600);
return hoursStr + ":" + minuteStr + ":" + secondStr;
}
void NTPClient::end() {
......@@ -204,28 +177,84 @@ void NTPClient::setUpdateInterval(unsigned long updateInterval) {
this->_updateInterval = updateInterval;
}
void NTPClient::setPoolServerName(const char* poolServerName) {
this->_poolServerName = poolServerName;
}
void NTPClient::sendNTPPacket() {
// set all bytes in the buffer to 0
memset(this->_packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
this->_packetBuffer[0] = 0b11100011; // LI, Version, Mode
this->_packetBuffer[1] = 0; // Stratum, or type of clock
this->_packetBuffer[2] = 6; // Polling Interval
this->_packetBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
this->_packetBuffer[12] = 0x49;
this->_packetBuffer[12] = 49;
this->_packetBuffer[13] = 0x4E;
this->_packetBuffer[14] = 0x49;
this->_packetBuffer[15] = 0x52;
this->_packetBuffer[14] = 49;
this->_packetBuffer[15] = 52;
// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
this->_udp->beginPacket(this->_poolServerName, 123); //NTP requests are to port 123
if (this->_poolServerName) {
this->_udp->beginPacket(this->_poolServerName, 123);
} else {
this->_udp->beginPacket(this->_poolServerIP, 123);
}
this->_udp->write(this->_packetBuffer, NTP_PACKET_SIZE);
this->_udp->endPacket();
}
void NTPClient::setRandomPort(unsigned int minValue, unsigned int maxValue) {
randomSeed(analogRead(0));
this->_port = random(minValue, maxValue);
}
/*** Custom code for ampel-firmware ***/
void NTPClient::getFormattedTime(char *formatted_time, unsigned long secs) {
unsigned long rawTime = secs ? secs : this->getEpochTime();
unsigned int hours = (rawTime % 86400L) / 3600;
unsigned int minutes = (rawTime % 3600) / 60;
unsigned int seconds = rawTime % 60;
snprintf(formatted_time, 9, "%02d:%02d:%02d", hours, minutes, seconds);
}
#define LEAP_YEAR(Y) ( (Y>0) && !(Y%4) && ( (Y%100) || !(Y%400) ) )
// Based on https://github.com/PaulStoffregen/Time/blob/master/Time.cpp
void NTPClient::getFormattedDate(char *formatted_date, unsigned long secs) {
unsigned long rawTime = (secs ? secs : this->getEpochTime()) / 86400L; // in days
unsigned long days = 0;
unsigned int year = 1970;
uint8_t month;
static const uint8_t monthDays[]={31,28,31,30,31,30,31,31,30,31,30,31};
while((days += (LEAP_YEAR(year) ? 366 : 365)) <= rawTime)
year++;
rawTime -= days - (LEAP_YEAR(year) ? 366 : 365); // now it is days in this year, starting at 0
days=0;
for (month=0; month<12; month++) {
uint8_t monthLength;
if (month==1) { // february
monthLength = LEAP_YEAR(year) ? 29 : 28;
} else {
monthLength = monthDays[month];
}
if (rawTime < monthLength) break;
rawTime -= monthLength;
}
month++; // jan is month 1
rawTime++; // first day is day 1
char formatted_time[9];
this->getFormattedTime(formatted_time, secs);
snprintf(formatted_date, 23, "%4d-%02d-%02lu %s%+03ld", year, month, rawTime, formatted_time, (this->_timeOffset / 3600) % 100);
}
void NTPClient::setEpochTime(unsigned long secs) {
this->_currentEpoc = secs;
}
/**************************************************************/
\ No newline at end of file
......@@ -7,8 +7,6 @@
#define SEVENZYYEARS 2208988800UL
#define NTP_PACKET_SIZE 48
#define NTP_DEFAULT_LOCAL_PORT 1337
#define LEAP_YEAR(Y) ( (Y>0) && !(Y%4) && ( (Y%100) || !(Y%400) ) )
class NTPClient {
private:
......@@ -16,8 +14,9 @@ class NTPClient {
bool _udpSetup = false;
const char* _poolServerName = "pool.ntp.org"; // Default time server
int _port = NTP_DEFAULT_LOCAL_PORT;
int _timeOffset = 0;
IPAddress _poolServerIP;
unsigned int _port = NTP_DEFAULT_LOCAL_PORT;
long _timeOffset = 0;
unsigned long _updateInterval = 60000; // In ms
......@@ -27,14 +26,28 @@ class NTPClient {
byte _packetBuffer[NTP_PACKET_SIZE];
void sendNTPPacket();
bool isValid(byte * ntpPacket);
public:
NTPClient(UDP& udp);
NTPClient(UDP& udp, int timeOffset);
NTPClient(UDP& udp, long timeOffset);
NTPClient(UDP& udp, const char* poolServerName);
NTPClient(UDP& udp, const char* poolServerName, int timeOffset);
NTPClient(UDP& udp, const char* poolServerName, int timeOffset, unsigned long updateInterval);
NTPClient(UDP& udp, const char* poolServerName, long timeOffset);
NTPClient(UDP& udp, const char* poolServerName, long timeOffset, unsigned long updateInterval);
NTPClient(UDP& udp, IPAddress poolServerIP);
NTPClient(UDP& udp, IPAddress poolServerIP, long timeOffset);
NTPClient(UDP& udp, IPAddress poolServerIP, long timeOffset, unsigned long updateInterval);
/**
* Set time server name
*
* @param poolServerName
*/
void setPoolServerName(const char* poolServerName);
/**
* Set random local port
*/
void setRandomPort(unsigned int minValue = 49152, unsigned int maxValue = 65535);
/**
* Starts the underlying UDP client with the default local port
......@@ -44,7 +57,7 @@ class NTPClient {
/**
* Starts the underlying UDP client with the specified local port
*/
void begin(int port);
void begin(unsigned int port);
/**
* This should be called in the main loop of your application. By default an update from the NTP Server is only
......@@ -61,10 +74,17 @@ class NTPClient {
*/
bool forceUpdate();
int getDay();
int getHours();
int getMinutes();
int getSeconds();
/**
* This allows to check if the NTPClient successfully received a NTP packet and set the time.
*
* @return true if time has been set, else false
*/
bool isTimeSet() const;
int getDay() const;
int getHours() const;
int getMinutes() const;
int getSeconds() const;
/**
* Changes the time offset. Useful for changing timezones dynamically
......@@ -78,28 +98,37 @@ class NTPClient {
void setUpdateInterval(unsigned long updateInterval);
/**
* @return secs argument (or 0 for current time) formatted like `hh:mm:ss`
*/
void getFormattedTime(char *formatted_time, unsigned long secs = 0);
* @return time formatted like `hh:mm:ss`
*/
String getFormattedTime() const;
/**
* @return time in seconds since Jan. 1, 1970
*/
unsigned long getEpochTime();
/**
* @return secs argument (or 0 for current date) formatted to ISO 8601
* like `2004-02-12T15:19:21+00:00`
*/
void getFormattedDate(char *formatted_date, unsigned long secs = 0);
unsigned long getEpochTime() const;
/**
* Stops the underlying UDP client
*/
void end();
/*** Custom code for ampel-firmware ***/
/**
* @return secs argument (or 0 for current time) formatted like `hh:mm:ss`
*/
void getFormattedTime(char *formatted_time, unsigned long secs = 0);
/**
* @return secs argument (or 0 for current date) formatted to ISO 8601
* like `2004-02-12T15:19:21+00:00`
*/
void getFormattedDate(char *formatted_date, unsigned long secs = 0);
/**
* Replace the NTP-fetched time with seconds since Jan. 1, 1970
*/
void setEpochTime(unsigned long secs);
/**************************************************************/
};
# NTPClient
[![Build Status](https://travis-ci.org/arduino-libraries/NTPClient.svg?branch=master)](https://travis-ci.org/arduino-libraries/NTPClient)
[![Check Arduino status](https://github.com/arduino-libraries/NTPClient/actions/workflows/check-arduino.yml/badge.svg)](https://github.com/arduino-libraries/NTPClient/actions/workflows/check-arduino.yml)
[![Compile Examples status](https://github.com/arduino-libraries/NTPClient/actions/workflows/compile-examples.yml/badge.svg)](https://github.com/arduino-libraries/NTPClient/actions/workflows/compile-examples.yml)
[![Spell Check status](https://github.com/arduino-libraries/NTPClient/actions/workflows/spell-check.yml/badge.svg)](https://github.com/arduino-libraries/NTPClient/actions/workflows/spell-check.yml)
Connect to a NTP server, here is how:
......@@ -22,7 +24,7 @@ WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
// You can specify the time server pool and the offset, (in seconds)
// additionaly you can specify the update interval (in milliseconds).
// additionally you can specify the update interval (in milliseconds).
// NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 3600, 60000);
void setup(){
......@@ -45,3 +47,6 @@ void loop() {
delay(1000);
}
```
## Function documentation
`getEpochTime` returns the Unix epoch, which are the seconds elapsed since 00:00:00 UTC on 1 January 1970 (leap seconds are ignored, every day is treated as having 86400 seconds). **Attention**: If you have set a time offset this time offset will be added to your epoch timestamp.
......@@ -12,9 +12,13 @@ begin KEYWORD2
end KEYWORD2
update KEYWORD2
forceUpdate KEYWORD2
isTimeSet KEYWORD2
getDay KEYWORD2
getHours KEYWORD2
getMinutes KEYWORD2
getSeconds KEYWORD2
getFormattedTime KEYWORD2
getEpochTime KEYWORD2
setTimeOffset KEYWORD2
setUpdateInterval KEYWORD2
setPoolServerName KEYWORD2
name=NTPClient
version=3.1.0
version=3.2.0
author=Fabrice Weinberg
maintainer=Fabrice Weinberg <fabrice@weinberg.me>
sentence=An NTPClient to connect to a time server
......
......@@ -14,25 +14,34 @@ SCD30 KEYWORD1
SCD30 KEYWORD2
begin KEYWORD2
isConnected KEYWORD2
enableDebugging KEYWORD2
beginMeasuring KEYWORD2
StopMeasurement KEYWORD2
setAmbientPressure KEYWORD2
getSettingValue KEYWORD2
getForcedRecalibration KEYWORD2
getMeasurementInterval KEYWORD2
getTemperatureOffset KEYWORD2
getAltitudeCompensation KEYWORD2
getFirmwareVersion KEYWORD2
getCO2 KEYWORD2
getHumidity KEYWORD2
getTemperature KEYWORD2
getMeasurementInterval KEYWORD2
setMeasurementInterval KEYWORD2
setAmbientPressure KEYWORD2
getAltitudeCompensation KEYWORD2
setAltitudeCompensation KEYWORD2
getAutoSelfCalibration KEYWORD2
setAutoSelfCalibration KEYWORD2
getForcedRecalibration KEYWORD2
setForcedRecalibrationFactor KEYWORD2
getTemperatureOffset KEYWORD2
setTemperatureOffset KEYWORD2
getAutoSelfCalibration KEYWORD2
dataAvailable KEYWORD2
readMeasurement KEYWORD2
reset KEYWORD2
......
name=SparkFun SCD30 Arduino Library
version=1.0.13
version=1.0.17
author=SparkFun Electronics
maintainer=SparkFun Electronics <sparkfun.com>
sentence=Library for the Sensirion SCD30 CO2 Sensor
......
......@@ -7,9 +7,9 @@
Written by Nathan Seidle @ SparkFun Electronics, May 22nd, 2018
Updated February 1st 2021 to include some of the features of paulvha's version of the library
(while maintaining backward-compatibility):
https://github.com/paulvha/scd30
Thank you Paul!
(while maintaining backward-compatibility):
https://github.com/paulvha/scd30
Thank you Paul!
The SCD30 measures CO2 with accuracy of +/- 30ppm.
......@@ -32,14 +32,14 @@ SCD30::SCD30(void)
// Constructor
}
//Initialize the Serial port
// Initialize the Serial port
#ifdef USE_TEENSY3_I2C_LIB
bool SCD30::begin(i2c_t3 &wirePort, bool autoCalibrate, bool measBegin)
#else
bool SCD30::begin(TwoWire &wirePort, bool autoCalibrate, bool measBegin)
#endif
{
_i2cPort = &wirePort; //Grab which port the user wants us to use
_i2cPort = &wirePort; // Grab which port the user wants us to use
/* Especially during obtaining the ACK BIT after a byte sent the SCD30 is using clock stretching (but NOT only there)!
* The need for clock stretching is described in the Sensirion_CO2_Sensors_SCD30_Interface_Description.pdf
......@@ -58,128 +58,153 @@ bool SCD30::begin(TwoWire &wirePort, bool autoCalibrate, bool measBegin)
_i2cPort->setClockStretchLimit(200000);
#endif
uint16_t fwVer;
if (getFirmwareVersion(&fwVer) == false) // Read the firmware version. Return false if the CRC check fails.
if (isConnected() == false)
return (false);
if (_printDebug == true)
{
_debugPort->print(F("SCD30 begin: got firmware version 0x"));
_debugPort->println(fwVer, HEX);
}
if (measBegin == false) // Exit now if measBegin is false
return (true);
//Check for device to respond correctly
if (beginMeasuring() == true) //Start continuous measurements
// Check for device to respond correctly
if (beginMeasuring() == true) // Start continuous measurements
{
setMeasurementInterval(2); //2 seconds between measurements
setAutoSelfCalibration(autoCalibrate); //Enable auto-self-calibration
setMeasurementInterval(2); // 2 seconds between measurements
setAutoSelfCalibration(autoCalibrate); // Enable auto-self-calibration
return (true);
}
return (false); //Something went wrong
return (false); // Something went wrong
}
// Returns true if device responds to a firmware request
bool SCD30::isConnected()
{
uint16_t fwVer;
if (getFirmwareVersion(&fwVer) == false) // Read the firmware version. Return false if the CRC check fails.
return (false);
if (_printDebug == true)
{
_debugPort->print(F("Firmware version 0x"));
_debugPort->println(fwVer, HEX);
}
return (true);
}
//Calling this function with nothing sets the debug port to Serial
//You can also call it with other streams like Serial1, SerialUSB, etc.
// Calling this function with nothing sets the debug port to Serial
// You can also call it with other streams like Serial1, SerialUSB, etc.
void SCD30::enableDebugging(Stream &debugPort)
{
_debugPort = &debugPort;
_printDebug = true;
_debugPort = &debugPort;
_printDebug = true;
}
//Returns the latest available CO2 level
//If the current level has already been reported, trigger a new read
// Returns the latest available CO2 level
// If the current level has already been reported, trigger a new read
uint16_t SCD30::getCO2(void)
{
if (co2HasBeenReported == true) //Trigger a new read
readMeasurement(); //Pull in new co2, humidity, and temp into global vars
if (co2HasBeenReported == true) // Trigger a new read
{
if (readMeasurement() == false) // Pull in new co2, humidity, and temp into global vars
co2 = 0; // Failed to read sensor
}
co2HasBeenReported = true;
return (uint16_t)co2; //Cut off decimal as co2 is 0 to 10,000
return (uint16_t)co2; // Cut off decimal as co2 is 0 to 10,000
}
//Returns the latest available humidity
//If the current level has already been reported, trigger a new read
// Returns the latest available humidity
// If the current level has already been reported, trigger a new read
float SCD30::getHumidity(void)
{
if (humidityHasBeenReported == true) //Trigger a new read
readMeasurement(); //Pull in new co2, humidity, and temp into global vars
if (humidityHasBeenReported == true) // Trigger a new read
if (readMeasurement() == false) // Pull in new co2, humidity, and temp into global vars
humidity = 0; // Failed to read sensor
humidityHasBeenReported = true;
return humidity;
}
//Returns the latest available temperature
//If the current level has already been reported, trigger a new read
// Returns the latest available temperature
// If the current level has already been reported, trigger a new read
float SCD30::getTemperature(void)
{
if (temperatureHasBeenReported == true) //Trigger a new read
readMeasurement(); //Pull in new co2, humidity, and temp into global vars
if (temperatureHasBeenReported == true) // Trigger a new read
if (readMeasurement() == false) // Pull in new co2, humidity, and temp into global vars
temperature = 0; // Failed to read sensor
temperatureHasBeenReported = true;
return temperature;
}
//Enables or disables the ASC
// Enables or disables the ASC
bool SCD30::setAutoSelfCalibration(bool enable)
{
if (enable)
return sendCommand(COMMAND_AUTOMATIC_SELF_CALIBRATION, 1); //Activate continuous ASC
return sendCommand(COMMAND_AUTOMATIC_SELF_CALIBRATION, 1); // Activate continuous ASC
else
return sendCommand(COMMAND_AUTOMATIC_SELF_CALIBRATION, 0); //Deactivate continuous ASC
return sendCommand(COMMAND_AUTOMATIC_SELF_CALIBRATION, 0); // Deactivate continuous ASC
}
//Set the forced recalibration factor. See 1.3.7.
//The reference CO2 concentration has to be within the range 400 ppm ≤ cref(CO2) ≤ 2000 ppm.
// Set the forced recalibration factor. See 1.3.7.
// The reference CO2 concentration has to be within the range 400 ppm ≤ cref(CO2) ≤ 2000 ppm.
bool SCD30::setForcedRecalibrationFactor(uint16_t concentration)
{
if (concentration < 400 || concentration > 2000)
{
return false; //Error check.
return false; // Error check.
}
return sendCommand(COMMAND_SET_FORCED_RECALIBRATION_FACTOR, concentration);
}
//Get the temperature offset. See 1.3.8.
// Get the temperature offset. See 1.3.8.
float SCD30::getTemperatureOffset(void)
{
uint16_t response = readRegister(COMMAND_SET_TEMPERATURE_OFFSET);
return (((float)response) / 100.0);
}
//Set the temperature offset. See 1.3.8.
bool SCD30::setTemperatureOffset(float tempOffset)
{
union
{
int16_t signed16;
uint16_t unsigned16;
} signedUnsigned; // Avoid any ambiguity casting int16_t to uint16_t
signedUnsigned.signed16 = tempOffset * 100;
return sendCommand(COMMAND_SET_TEMPERATURE_OFFSET, signedUnsigned.unsigned16);
signedUnsigned.signed16 = response;
return (((float)signedUnsigned.signed16) / 100.0);
}
//Get the altitude compenstation. See 1.3.9.
// Set the temperature offset to remove module heating from temp reading
bool SCD30::setTemperatureOffset(float tempOffset)
{
// Temp offset is only positive. See: https://github.com/sparkfun/SparkFun_SCD30_Arduino_Library/issues/27#issuecomment-971986826
//"The SCD30 offset temperature is obtained by subtracting the reference temperature from the SCD30 output temperature"
// https://www.sensirion.com/fileadmin/user_upload/customers/sensirion/Dokumente/9.5_CO2/Sensirion_CO2_Sensors_SCD30_Low_Power_Mode.pdf
if (tempOffset < 0.0)
return (false);
uint16_t value = tempOffset * 100;
return sendCommand(COMMAND_SET_TEMPERATURE_OFFSET, value);
}
// Get the altitude compenstation. See 1.3.9.
uint16_t SCD30::getAltitudeCompensation(void)
{
return readRegister(COMMAND_SET_ALTITUDE_COMPENSATION);
}
//Set the altitude compenstation. See 1.3.9.
// Set the altitude compenstation. See 1.3.9.
bool SCD30::setAltitudeCompensation(uint16_t altitude)
{
return sendCommand(COMMAND_SET_ALTITUDE_COMPENSATION, altitude);
}
//Set the pressure compenstation. This is passed during measurement startup.
//mbar can be 700 to 1200
// Set the pressure compenstation. This is passed during measurement startup.
// mbar can be 700 to 1200
bool SCD30::setAmbientPressure(uint16_t pressure_mbar)
{
if (pressure_mbar < 700 || pressure_mbar > 1200)
......@@ -192,33 +217,34 @@ bool SCD30::setAmbientPressure(uint16_t pressure_mbar)
// SCD30 soft reset
void SCD30::reset()
{
sendCommand(COMMAND_RESET);
sendCommand(COMMAND_RESET);
}
// Get the current ASC setting
bool SCD30::getAutoSelfCalibration()
{
uint16_t response = readRegister(COMMAND_AUTOMATIC_SELF_CALIBRATION);
if (response == 1) {
if (response == 1)
{
return true;
}
else {
return false;
else
{
return false;
}
}
//Begins continuous measurements
//Continuous measurement status is saved in non-volatile memory. When the sensor
//is powered down while continuous measurement mode is active SCD30 will measure
//continuously after repowering without sending the measurement command.
//Returns true if successful
// Begins continuous measurements
// Continuous measurement status is saved in non-volatile memory. When the sensor
// is powered down while continuous measurement mode is active SCD30 will measure
// continuously after repowering without sending the measurement command.
// Returns true if successful
bool SCD30::beginMeasuring(uint16_t pressureOffset)
{
return (sendCommand(COMMAND_CONTINUOUS_MEASUREMENT, pressureOffset));
}
//Overload - no pressureOffset
// Overload - no pressureOffset
bool SCD30::beginMeasuring(void)
{
return (beginMeasuring(0));
......@@ -227,17 +253,26 @@ bool SCD30::beginMeasuring(void)
// Stop continuous measurement
bool SCD30::StopMeasurement(void)
{
return(sendCommand(COMMAND_STOP_MEAS));
return (sendCommand(COMMAND_STOP_MEAS));
}
//Sets interval between measurements
//2 seconds to 1800 seconds (30 minutes)
// Sets interval between measurements
// 2 seconds to 1800 seconds (30 minutes)
bool SCD30::setMeasurementInterval(uint16_t interval)
{
return sendCommand(COMMAND_SET_MEASUREMENT_INTERVAL, interval);
}
//Returns true when data is available
// Gets interval between measurements
// 2 seconds to 1800 seconds (30 minutes)
uint16_t SCD30::getMeasurementInterval(void)
{
uint16_t interval = 0;
getSettingValue(COMMAND_SET_MEASUREMENT_INTERVAL, &interval);
return (interval);
}
// Returns true when data is available
bool SCD30::dataAvailable()
{
uint16_t response = readRegister(COMMAND_GET_DATA_READY);
......@@ -247,24 +282,27 @@ bool SCD30::dataAvailable()
return (false);
}
//Get 18 bytes from SCD30
//Updates global variables with floats
//Returns true if success
// Get 18 bytes from SCD30
// Updates global variables with floats
// Returns true if success
bool SCD30::readMeasurement()
{
//Verify we have data from the sensor
// Verify we have data from the sensor
if (dataAvailable() == false)
return (false);
ByteToFl tempCO2; tempCO2.value = 0;
ByteToFl tempHumidity; tempHumidity.value = 0;
ByteToFl tempTemperature; tempTemperature.value = 0;
ByteToFl tempCO2;
tempCO2.value = 0;
ByteToFl tempHumidity;
tempHumidity.value = 0;
ByteToFl tempTemperature;
tempTemperature.value = 0;
_i2cPort->beginTransmission(SCD30_ADDRESS);
_i2cPort->write(COMMAND_READ_MEASUREMENT >> 8); //MSB
_i2cPort->write(COMMAND_READ_MEASUREMENT & 0xFF); //LSB
_i2cPort->write(COMMAND_READ_MEASUREMENT >> 8); // MSB
_i2cPort->write(COMMAND_READ_MEASUREMENT & 0xFF); // LSB
if (_i2cPort->endTransmission() != 0)
return (0); //Sensor did not ACK
return (0); // Sensor did not ACK
delay(3);
......@@ -283,25 +321,25 @@ bool SCD30::readMeasurement()
case 1:
case 3:
case 4:
tempCO2.array[x < 3 ? 3-x : 4-x] = incoming;
tempCO2.array[x < 3 ? 3 - x : 4 - x] = incoming;
bytesToCrc[x % 3] = incoming;
break;
case 6:
case 7:
case 9:
case 10:
tempTemperature.array[x < 9 ? 9-x : 10-x] = incoming;
tempTemperature.array[x < 9 ? 9 - x : 10 - x] = incoming;
bytesToCrc[x % 3] = incoming;
break;
case 12:
case 13:
case 15:
case 16:
tempHumidity.array[x < 15 ? 15-x : 16-x] = incoming;
tempHumidity.array[x < 15 ? 15 - x : 16 - x] = incoming;
bytesToCrc[x % 3] = incoming;
break;
default:
//Validate CRC
// Validate CRC
uint8_t foundCrc = computeCRC8(bytesToCrc, 2);
if (foundCrc != incoming)
{
......@@ -337,28 +375,28 @@ bool SCD30::readMeasurement()
_debugPort->println(F("readMeasurement: encountered error reading SCD30 data."));
return false;
}
//Now copy the uint32s into their associated floats
// Now copy the uint32s into their associated floats
co2 = tempCO2.value;
temperature = tempTemperature.value;
humidity = tempHumidity.value;
//Mark our global variables as fresh
// Mark our global variables as fresh
co2HasBeenReported = false;
humidityHasBeenReported = false;
temperatureHasBeenReported = false;
return (true); //Success! New data available in globals.
return (true); // Success! New data available in globals.
}
//Gets a setting by reading the appropriate register.
//Returns true if the CRC is valid.
// Gets a setting by reading the appropriate register.
// Returns true if the CRC is valid.
bool SCD30::getSettingValue(uint16_t registerAddress, uint16_t *val)
{
_i2cPort->beginTransmission(SCD30_ADDRESS);
_i2cPort->write(registerAddress >> 8); //MSB
_i2cPort->write(registerAddress & 0xFF); //LSB
_i2cPort->write(registerAddress >> 8); // MSB
_i2cPort->write(registerAddress & 0xFF); // LSB
if (_i2cPort->endTransmission() != 0)
return (false); //Sensor did not ACK
return (false); // Sensor did not ACK
delay(3);
......@@ -384,14 +422,14 @@ bool SCD30::getSettingValue(uint16_t registerAddress, uint16_t *val)
return (false);
}
//Gets two bytes from SCD30
// Gets two bytes from SCD30
uint16_t SCD30::readRegister(uint16_t registerAddress)
{
_i2cPort->beginTransmission(SCD30_ADDRESS);
_i2cPort->write(registerAddress >> 8); //MSB
_i2cPort->write(registerAddress & 0xFF); //LSB
_i2cPort->write(registerAddress >> 8); // MSB
_i2cPort->write(registerAddress & 0xFF); // LSB
if (_i2cPort->endTransmission() != 0)
return (0); //Sensor did not ACK
return (0); // Sensor did not ACK
delay(3);
......@@ -402,49 +440,49 @@ uint16_t SCD30::readRegister(uint16_t registerAddress)
uint8_t lsb = _i2cPort->read();
return ((uint16_t)msb << 8 | lsb);
}
return (0); //Sensor did not respond
return (0); // Sensor did not respond
}
//Sends a command along with arguments and CRC
// Sends a command along with arguments and CRC
bool SCD30::sendCommand(uint16_t command, uint16_t arguments)
{
uint8_t data[2];
data[0] = arguments >> 8;
data[1] = arguments & 0xFF;
uint8_t crc = computeCRC8(data, 2); //Calc CRC on the arguments only, not the command
uint8_t crc = computeCRC8(data, 2); // Calc CRC on the arguments only, not the command
_i2cPort->beginTransmission(SCD30_ADDRESS);
_i2cPort->write(command >> 8); //MSB
_i2cPort->write(command & 0xFF); //LSB
_i2cPort->write(arguments >> 8); //MSB
_i2cPort->write(arguments & 0xFF); //LSB
_i2cPort->write(command >> 8); // MSB
_i2cPort->write(command & 0xFF); // LSB
_i2cPort->write(arguments >> 8); // MSB
_i2cPort->write(arguments & 0xFF); // LSB
_i2cPort->write(crc);
if (_i2cPort->endTransmission() != 0)
return (false); //Sensor did not ACK
return (false); // Sensor did not ACK
return (true);
}
//Sends just a command, no arguments, no CRC
// Sends just a command, no arguments, no CRC
bool SCD30::sendCommand(uint16_t command)
{
_i2cPort->beginTransmission(SCD30_ADDRESS);
_i2cPort->write(command >> 8); //MSB
_i2cPort->write(command & 0xFF); //LSB
_i2cPort->write(command >> 8); // MSB
_i2cPort->write(command & 0xFF); // LSB
if (_i2cPort->endTransmission() != 0)
return (false); //Sensor did not ACK
return (false); // Sensor did not ACK
return (true);
}
//Given an array and a number of bytes, this calculate CRC8 for those bytes
//CRC is only calc'd on the data portion (two bytes) of the four bytes being sent
//From: http://www.sunshine2k.de/articles/coding/crc/understanding_crc.html
//Tested with: http://www.sunshine2k.de/coding/javascript/crc/crc_js.html
//x^8+x^5+x^4+1 = 0x31
// Given an array and a number of bytes, this calculate CRC8 for those bytes
// CRC is only calc'd on the data portion (two bytes) of the four bytes being sent
// From: http://www.sunshine2k.de/articles/coding/crc/understanding_crc.html
// Tested with: http://www.sunshine2k.de/coding/javascript/crc/crc_js.html
// x^8+x^5+x^4+1 = 0x31
uint8_t SCD30::computeCRC8(uint8_t data[], uint8_t len)
{
uint8_t crc = 0xFF; //Init with 0xFF
uint8_t crc = 0xFF; // Init with 0xFF
for (uint8_t x = 0; x < len; x++)
{
......@@ -459,5 +497,5 @@ uint8_t SCD30::computeCRC8(uint8_t data[], uint8_t len)
}
}
return crc; //No output reflection
return crc; // No output reflection
}
......@@ -40,10 +40,10 @@
#include <Wire.h>
#endif
//The default I2C address for the SCD30 is 0x61.
// The default I2C address for the SCD30 is 0x61.
#define SCD30_ADDRESS 0x61
//Available commands
// Available commands
#define COMMAND_CONTINUOUS_MEASUREMENT 0x0010
#define COMMAND_SET_MEASUREMENT_INTERVAL 0x4600
......@@ -70,38 +70,43 @@ public:
bool begin(bool autoCalibrate) { return begin(Wire, autoCalibrate); }
#ifdef USE_TEENSY3_I2C_LIB
bool begin(i2c_t3 &wirePort = Wire, bool autoCalibrate = false, bool measBegin = true); //By default use Wire port
bool begin(i2c_t3 &wirePort = Wire, bool autoCalibrate = false, bool measBegin = true); // By default use Wire port
#else
bool begin(TwoWire &wirePort = Wire, bool autoCalibrate = false, bool measBegin = true); //By default use Wire port
bool begin(TwoWire &wirePort = Wire, bool autoCalibrate = false, bool measBegin = true); // By default use Wire port
#endif
void enableDebugging(Stream &debugPort = Serial); //Turn on debug printing. If user doesn't specify then Serial will be used.
bool isConnected();
void enableDebugging(Stream &debugPort = Serial); // Turn on debug printing. If user doesn't specify then Serial will be used.
bool beginMeasuring(uint16_t pressureOffset);
bool beginMeasuring(void);
bool StopMeasurement(void); // paulvha
// based on paulvha
bool setAmbientPressure(uint16_t pressure_mbar);
bool getSettingValue(uint16_t registerAddress, uint16_t *val);
bool getForcedRecalibration(uint16_t *val) { return (getSettingValue(COMMAND_SET_FORCED_RECALIBRATION_FACTOR, val)); }
bool getMeasurementInterval(uint16_t *val) { return (getSettingValue(COMMAND_SET_MEASUREMENT_INTERVAL, val)); }
bool getTemperatureOffset(uint16_t *val) { return (getSettingValue(COMMAND_SET_TEMPERATURE_OFFSET, val)); }
bool getAltitudeCompensation(uint16_t *val) { return (getSettingValue(COMMAND_SET_ALTITUDE_COMPENSATION, val)); }
bool getFirmwareVersion(uint16_t *val) { return (getSettingValue(COMMAND_READ_FW_VER, val)); }
uint16_t getCO2(void);
float getHumidity(void);
float getTemperature(void);
float getTemperatureOffset(void);
uint16_t getAltitudeCompensation(void);
uint16_t getMeasurementInterval(void);
bool getMeasurementInterval(uint16_t *val) { return (getSettingValue(COMMAND_SET_MEASUREMENT_INTERVAL, val)); }
bool setMeasurementInterval(uint16_t interval);
bool setAmbientPressure(uint16_t pressure_mbar);
uint16_t getAltitudeCompensation(void);
bool getAltitudeCompensation(uint16_t *val) { return (getSettingValue(COMMAND_SET_ALTITUDE_COMPENSATION, val)); }
bool setAltitudeCompensation(uint16_t altitude);
bool getAutoSelfCalibration(void);
bool setAutoSelfCalibration(bool enable);
bool getForcedRecalibration(uint16_t *val) { return (getSettingValue(COMMAND_SET_FORCED_RECALIBRATION_FACTOR, val)); }
bool setForcedRecalibrationFactor(uint16_t concentration);
float getTemperatureOffset(void);
bool getTemperatureOffset(uint16_t *val) { return (getSettingValue(COMMAND_SET_TEMPERATURE_OFFSET, val)); }
bool setTemperatureOffset(float tempOffset);
bool getAutoSelfCalibration(void);
bool dataAvailable();
bool readMeasurement();
......@@ -116,25 +121,25 @@ public:
uint8_t computeCRC8(uint8_t data[], uint8_t len);
private:
//Variables
// Variables
#ifdef USE_TEENSY3_I2C_LIB
i2c_t3 *_i2cPort; //The generic connection to user's chosen I2C hardware
i2c_t3 *_i2cPort; // The generic connection to user's chosen I2C hardware
#else
TwoWire *_i2cPort; //The generic connection to user's chosen I2C hardware
TwoWire *_i2cPort; // The generic connection to user's chosen I2C hardware
#endif
//Global main datums
// Global main datums
float co2 = 0;
float temperature = 0;
float humidity = 0;
//These track the staleness of the current data
//This allows us to avoid calling readMeasurement() every time individual datums are requested
// These track the staleness of the current data
// This allows us to avoid calling readMeasurement() every time individual datums are requested
bool co2HasBeenReported = true;
bool humidityHasBeenReported = true;
bool temperatureHasBeenReported = true;
//Debug
Stream *_debugPort; //The stream to send debug messages to if enabled. Usually Serial.
boolean _printDebug = false; //Flag to print debugging variables
// Debug
Stream *_debugPort; // The stream to send debug messages to if enabled. Usually Serial.
boolean _printDebug = false; // Flag to print debugging variables
};
#endif
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment