/*
Margay Library
Licensed: GNU GPL v3
Written by:
Bobby Schulz
Andy Wickert
*/
#include <Margay.h>
#include <Arduino.h>
// CRC-8/SMBUS (polynomial 0x07, init 0x00) over Page 0 bytes 0x00-0x1D, as
// NW-Provision writes it (NW-Device-Specification Page 0 Block 3).
static uint8_t crc8(const uint8_t* data, uint8_t len) {
uint8_t crc = 0x00;
for (uint8_t i = 0; i < len; i++) {
crc ^= data[i];
for (uint8_t b = 0; b < 8; b++) crc = (crc & 0x80) ? (crc << 1) ^ 0x07 : (crc << 1);
}
return crc;
}
Margay::Margay(board model_, build specs_) {
if (model_ == 2 || model_ == 3) {
SD_CS = 4;
AuxLED = 20;
RedLED = 13;
GreenLED = 15;
BlueLED = 14;
VRef_Pin = 3;
BatSense_Pin = 2;
VSwitch_Pin = 12;
SD_CD = 1;
Ext3v3Ctrl = 22;
I2C_SW = 21;
PG = 18;
TX = 11;
RX = 10;
ExtInt = 11; //Legacy inclusion
RTCInt = 2;
LogInt = 28;
WDHold = 23;
BatSwitch = 19;
//The watchdog's period, from R10 on the TPL5010's DELAY pin, by the
//datasheet's Equation 1 (SNAS651A, Table 1, T > 1000 s). R10 is a 1 %
//resistor and the shortest period it allows is what a ceiling must respect:
//a logging interval plus a cycle must stay inside it. Page 1 register 0x30
//overrides this per board.
// v3.0: 130 kΩ (Project-Margay 755ffd9, 2022), 3943 s nominal, 3854 to 4033 s;
// the grid holds 3600 s.
// v2.x: 100 kΩ, 2160 s nominal, 2110 to 2209 s; the grid holds 1800 s.
if (model_ == 3) {
wdtSeconds = 3853;
} else {
wdtSeconds = 2110;
}
_batteryDivider = 2.0;
if (specs_ == BUILD_A) {
_numAdrOb = 1; //Only check for clock presence
}
else if (specs_ == BUILD_B) {
_numAdrOb = 2; //Tell system to search additional ADRs
_i2cAdrOb[1] = 0x69; //Use 0x69 on board ADC (MCP3421A1)
}
else if (specs_ == BUILD_C) {
_numAdrOb = 2; //Tell system to search additional ADRs
_i2cAdrOb[1] = 0x6B; //Use 0x6B on board ADC (MCP3421A3)
}
} else if (model_ == 1) {
SD_CS = 4;
AuxLED = 20;
RedLED = 13;
GreenLED = 15;
BlueLED = 14;
VRef_Pin = 2;
BatSense_Pin = 0;
VSwitch_Pin = 12;
SD_CD = 1;
Ext3v3Ctrl = 19;
I2C_SW = 21;
PG = 18;
TX = 11;
RX = 10;
extIntPin = 11;
RTCInt = 10;
LogInt = 2;
WDHold = 255; //Null pins
BatSwitch = 255; //Null pins
wdtSeconds = 0; //No watchdog on this model, so no ceiling to check against
_batteryDivider = 2.0;
if (specs_ == BUILD_A) {
_numAdrOb = 1; //Only check for clock presence
}
else if (specs_ == BUILD_B) {
_numAdrOb = 2; //Tell system to search additional ADRs
_i2cAdrOb[1] = 0x69; //Use 0x69 on board ADC (MCP3421A1)
}
else if (specs_ == BUILD_C) {
_numAdrOb = 2; //Tell system to search additional ADRs
_i2cAdrOb[1] = 0x6B; //Use 0x6B on board ADC (MCP3421A3)
}
else if (specs_ == BUILD_D) {
_numAdrOb = 2; //Tell system to search additional ADRs
_i2cAdrOb[1] = 0x6A; //Use 0x6A on board ADC (MCP3421A2)
}
} else {
SD_CS = 4;
AuxLED = 19;
RedLED = 13;
GreenLED = 15;
BlueLED = 14;
VRef_Pin = 2;
BatSense_Pin = 0;
VSwitch_Pin = 3;
SD_CD = 1;
Ext3v3Ctrl = 12;
I2C_SW = 255;
PG = 18;
extIntPin = 11;
RTCInt = 10;
LogInt = 2;
_batteryDivider = 9.0;
if (specs_ == BUILD_A) { //Setup sub builds
_numAdrOb = 1; //Only check for clock presence
}
else if (specs_ == BUILD_B) {
_numAdrOb = 2; //Tell system to search additional ADRs
_i2cAdrOb[1] = 0x69; //Use 0x69 on board ADC (MCP3421A1)
}
else if (specs_ == BUILD_C) {
_numAdrOb = 2; //Tell system to search additional ADRs
_i2cAdrOb[1] = 0x6B; //Use 0x6B on board ADC (MCP3421A3)
}
}
_model = model_; //Store model info locally
_specs = specs_; //Store build info locally
}
bool Margay::beginBoard(uint8_t* vals, uint8_t numVals) {
powerOB(ON); //Turn on on-board power
powerAux(ON); //Turn on external auxiliary power
if (WDHold != 255) pinMode(WDHold, OUTPUT);
pinMode(AuxLED, OUTPUT);
digitalWrite(AuxLED, LOW); //Turn built in LED on
pinMode(VSwitch_Pin, OUTPUT); //Setup switch control as output
acceptAddresses(vals, numVals); //The watched sensors' addresses
_rtc.begin(); //Initialize RTC
_rtc.clearAlarm(); //
if (_numAdrOb > 1) initADC(18); // Only BUILD_B/C/D have an on-board ADC
Serial.begin(38400); //Before the first thing that may print: the BME280 result below
if (_model >= MODEL_2v0 && !bme280.begin(0x77)) { //Initialize onboard temp/pressure/RH sensor (BME280)
Serial.println("BME280 init: FAIL");
_onBoardError = true;
_bmeError = true;
raise(NW_MSG_BME_MISSING);
}
ADCSRA = 0b10000111; //Configure on board ADC for low speed, and enable
Serial.print("Lib = ");
Serial.println(libVersion);
Serial.print("Model = ");
Serial.print(_model);
Serial.print(" Build = ");
Serial.println(_specs);
bool schema1 = readIdentity(); //Serial number and hardware version from Page 0 (Schema 1), else the Schema 0 bytes
//Schema 0: the model number the sketch declared
if (!schema1) snprintf(_hwVersion, sizeof(_hwVersion), "%u", (unsigned)_model);
if (schema1 && !_pages.page1Blank()) { //Page 1: this board's calibration, written by NW-Provision; the constants otherwise
//Block 0, battery. The thermistor's Steinhart-Hart coefficients used to sit
//at 0x22-0x31 and are gone: they were Vishay's published set for a 10k NTC,
//identical on every board and compiled in below, and the part itself is
//fitted only below model 2.0.
_batteryDivider = _pages.get16(0x20) / 1000.0;
batVoltageError = _pages.get16(0x22) / 100.0;
batPercentageWarning = _pages.page[0x24];
//Block 2, timing. Zero leaves the model's compiled period in place, so a
//blank field does not remove the schedule's ceiling.
uint16_t wdt = _pages.get16(0x30);
if (wdt) wdtSeconds = wdt;
Serial.println("Calibration from Page 1");
}
serialTimeSet(); //A YYMMDDHHMMSS string waiting on Serial sets the clock; then the timestamp
attachLoggerInterrupts(_model >= 2); //LED pins, SD chip select, file times, the alarm and the button (PCINT from v2.0)
I2Ctest();
clockTest();
SDtest();
batTest();
powerTest();
// Only print out environmental variables if BME280 is on board
if (_model >= MODEL_2v0) bme280Readings();
printReadyToLog(); //"Ready to Log" on Serial; the LED verdict waits for the first row, in run()
//Pending Andy's decision on whether a logger keeps serving its own Report
//register (QUEUE.md, item 1 step 3). The messages above are what the LED and
//the Note column read; this chain is the served byte, and reports only the
//first fault it meets.
//The logger's own report at boot, for its first status row: the first fault the
//self-tests found, else LoggingStarted (unit, kind 16).
if (_sdCardMissing) _pages.latchFault(0x01);
else if (_sdTestFailed) _pages.latchFault(0x05);
else if (_clockError) _pages.latchFault(0x21);
else if (_bmeError) _pages.latchFault(0x41);
else if (_sensorError) _pages.latchFault(0x61);
else if (_batError) _pages.latchFault(0x84);
_pages.latchNotice(0xF0);
raise(NW_MSG_LOG_STARTED);
_bootReport = _pages.report();
_pages.acknowledge();
_newLog = true; //Set flag to begin new log file
attachExtInt(); //The external-interrupt counter, if setExtInt() named a pin
LED_Color(OFF);
return !(_onBoardError || _sensorError || _timeError || _sdCardMissing); //Okapi's convention: true = nothing wrong
}
//TEMPORARY thresholds (Andy, 2026-10-28), until Page 1's battery block decides
//them: the fit's percentage, red below 20, purple below 50, blue above. Below
//3.4 V the reading is not a pack the board runs from (USB alone reads 3.29 V,
//Margay_Library#34), so no judgement is made.
static const float MARGAY_BAT_UNJUDGED_V = 3.4;
static const float MARGAY_BAT_LOW_PCT = 20;
static const float MARGAY_BAT_MID_PCT = 50;
uint32_t Margay::batteryColour() {
if (_batVoltage == NW_ERROR || _batVoltage < MARGAY_BAT_UNJUDGED_V) return BLUE;
if (_batPercent < MARGAY_BAT_LOW_PCT) return RED;
if (_batPercent < MARGAY_BAT_MID_PCT) return PURPLE;
return BLUE;
}
uint32_t Margay::chirpColour() {
return batteryColour();
}
uint32_t Margay::rowBlipColour() {
return batteryColour();
}
void Margay::batTest() {
float batVoltage = getBatVoltage();
float batPercentage = getBatPercentage();
// Set error flag if below min voltage
if (batVoltage < batVoltageError) _batError = true;
// Set warning flag if below set percentage
if (batPercentage < batPercentageWarning) {
_batWarning = true;
_pages.latchNotice(0x90);
} //BatteryWarning
Serial.print("Bat = ");
Serial.print(batVoltage);
Serial.print("V\t");
Serial.print(batPercentage);
Serial.println("%");
}
void Margay::initADC(uint8_t desiredResolution) {
// Serial.print("ADC should be on"); // DEBUG
adc.begin(_i2cAdrOb[1]); //Initialize external ADC
adc.setResolution(desiredResolution);
}
void Margay::powerTest() {
// BME280 at 0x77 is on the AUX rail on Model >= 2v0; skip on older boards
if (_model < MODEL_2v0) {
Serial.println(F("Power: SKIP (not supported on this board)"));
return;
}
Serial.print("Power: ");
bool initialStateExternalI2C = digitalRead(I2C_SW);
switchExternalI2C(OFF); // BME280 is on the internal I2C bus
powerAux(OFF); // cut AUX rail
delay(10); // allow capacitors to discharge
Wire.beginTransmission(0x77);
int error = Wire.endTransmission();
powerAux(ON);
// Adafruit_BME280::begin() issues a soft-reset then delays >=300ms for
// calibration — the sensor is fully ready when begin() returns, so no
// additional settling delay is needed before bme280Readings() is called.
bme280.begin(0x77);
farmGateI2C(initialStateExternalI2C); // restore I2C bus to its prior state
if (error == 0) {
Serial.println("FAIL"); // BME280 still responded — AUX rail not cut
_onBoardError = true;
} else {
Serial.println("PASS");
}
}
void Margay::bme280Readings() {
Serial.print("Temp = ");
Serial.print(bme280.getTemperature());
Serial.println("C");
Serial.print("Pressure = ");
Serial.print(bme280.getPressure());
Serial.println(" mBar");
Serial.print("RH = ");
Serial.print(bme280.getHumidity());
Serial.println("%");
}
float Margay::getTemp(temp_source sensor) {
// Get Temp from RTC
if (sensor == RTC_temp_sensor) {
float rtcTemp = _rtc.getTemp();
return rtcTemp;
} else {
// Obvious temperature error value that no sensor would give
return -1234;
}
}
float Margay::getBatVoltage() {
// Maybe not necessary: seems to be set this way anyway
// Enable ADC, set clock divider to max to deal with high impedance input
ADCSRA = 0b10000111;
delay(10); //Allow for >1 clock cycle to set values
float vAux = 3.3; // Voltage reference for ATMega1284p ADC
float batADC10bit = analogRead(BatSense_Pin); //Get (divided) battery ADC val
//VRef is having issues: often approx 0.9 <-- This was from the hardware component; fixed now
// Therefore, instead we will just use the 3V3 regulator as our basis
// Find compensation value with VRef due to larger uncertainty with vcc
float comp = (1.8 / 3.3) * 1023. / analogRead(VRef_Pin);
// Override comp calculation since many v0.0 models do not have ref equipped
if (_model == 0) comp = 1.0;
// Should divide by 1023. instead of 1024: 0-1023
//batVoltage = batVoltage*BatteryDivider*comp*(vcc/1024.0);
// Compensate for voltage divider and ref voltage error
float batVoltage = batADC10bit / 1023. * vAux * _batteryDivider;
return batVoltage;
}
float Margay::getBatPercentage() {
return batPercentFromVoltage(getBatVoltage());
}
float Margay::batPercentFromVoltage(float batVoltage) {
if (nCells == 0) {
Serial.println(F("getBatPercentage: NCells must be > 0"));
return -1;
}
// NOTE: Fit developed for Duracell AA, should work well for most alkalines,
// but no guarantee given on accuracy
// From 30% to 100% capacity, should be accurate to within 1%
// (for data taken at 25C)
float batA = -1.9809;
float batB = 6.2931;
float batC = -4.0063;
float cellVoltage = batVoltage / nCells; //Divide to get per-cell voltage
// Return percentage of remaining battery energy
float percentage = ((batA * pow(cellVoltage, 2) + batB * cellVoltage + batC) * 2 - 1) * 100.0;
if (percentage < 0) return 0; //Do not allow return of non-sensical values
// Is this appropriate? Float voltage could be higher than specified
// and still be correct
if (percentage > 100) return 100;
return percentage;
}
// The data file's header row: the on-board columns (old loggers lack the
// BME280), then the sketch's Header, then Note. Note is always the last
// column and carries no comma after it: every sensor ends its fields with a
// comma for the next, so this ends the row.
size_t Margay::printDataHeader(Print& out) {
//The logger's own columns: the timestamp and the on-board sensors. The data
//file's header row is this, then each watched sensor's, then Note. See
//LIBRARY-DESIGN.md section 14.
size_t n = 0;
n += out.print("Time [UTC], PresOB [mBar], RH_OB [%], TempOB [C], ");
n += out.print("Temp RTC [C], Bat [V], ");
return n;
}
size_t Margay::printDataRow(Print& out) {
//The values readOnBoard() left, in printDataHeader()'s order. This takes no
//reading: a row written to the card and to the monitor must not read the
//sensors twice, and the two rows would otherwise differ.
size_t n = 0;
n += out.print(_logTimeDate);
n += out.print(',');
n += bme280.printDataRow(out);
n += out.print(_rtcTemp);
n += out.print(',');
n += out.print(_batVoltage);
n += out.print(',');
return n;
}
void Margay::readOnBoard() {
// Get onboard temp, RTC temp, and battery voltage, reference voltage
// float VRef = analogRead(VRef_Pin);
float vcc = 3.3; //(1.8/VRef)*3.3; //Compensate for vcc using VRef
// Serial.println(vcc); //DEBUG!
// delay(10);
// Get battery voltage, including voltage divider in math
float batVoltage = getBatVoltage();
// Temp[3] = Clock.getTemperature(); //Get temperature from RTC //FIX!
float rtcTemp = _rtc.getTemp(); //Get Temp from RTC
getTime(); //FIX!
_rtcTemp = rtcTemp;
_batVoltage = batVoltage;
_batPercent = batPercentFromVoltage(batVoltage); //TEMPORARY: for the chirp's and the blip's colour; no second read
}
float Margay::getVoltage() { //Get voltage from Ax pin
// Voltage reads from the on-board ADC, but to read the Ax pin at the
// same time as external sensors, need access to the ADC. However, we
// do not want to change the state of the I2C bus communication by
// taking a voltage reading. So we have logic here to make the switch.
// First check whether external I2C connections are on by testing pin
// I2C_SW (HIGH is on). When the external I2C connection is on, the
// internal I2C connection is cut off.
bool initialStateExternalI2C = digitalRead(I2C_SW);
// initialize a variable to hold the voltage reading.
float val = 0;
switchExternalI2C(OFF);
if (_numAdrOb > 1) { // Only BUILD_B/C/D have an on-board ADC
initADC(18);
val = adc.getVoltage();
}
// make sure I2C Bus is returned to initial state
farmGateI2C(initialStateExternalI2C);
return val;
}
// Reads new data and writes data to SD
void Margay::addDataPoint() {
//The streaming row: this board's bus dance around the base class's reading
//and writing. The String overload above does the same for a sketch's update().
if (_model >= MODEL_2v0) bme280.begin(0x77); //FIX??
bool initialStateExternalI2C = digitalRead(I2C_SW);
switchExternalI2C(ON);
readSensors();
farmGateI2C(initialStateExternalI2C);
if (logRow() != 0) {
_pages.latchNotice(0xF2); //RowNotWritten, the served byte
raise(NW_MSG_ROW_NOT_WRITTEN);
}
fillPages();
reportRows();
}
uint8_t Margay::chipFaults() {
uint8_t f = 0;
if (_sdCardMissing || _sdTestFailed) f |= 0x01;
if (_clockError) f |= 0x02;
if (_bmeError) f |= 0x04;
if (_sensorError) f |= 0x08;
if (_batError) f |= 0x10;
return f;
}
void Margay::fillPages() {
_pages.beginReading();
float v = getBatVoltage();
_pages.put8(0x48, (uint8_t)constrain(getBatPercentage(), 0, 100));
_pages.put16(0x49, (uint16_t)(v * 100.0 + 0.5));
if (_model >= MODEL_2v0 && !_bmeError) {
_pages.put16(0x50, (uint16_t)(int16_t)(bme280.getTemperature() * 100.0));
_pages.put16(0x52, (uint16_t)(bme280.getHumidity() * 100.0));
_pages.put32(0x54, (uint32_t)(bme280.getPressure() * 100.0));
}
_pages.put32(0x58, clockUnix()); //Clock: Unix seconds
_pages.put16(0x5C, (uint16_t)(int16_t)(_rtc.getTemp() * 100.0));
_pages.put16(0x60, _fileNum);
_pages.put32(0x62, _logInterval);
_pages.put16(0x66, getExtIntCount(false));
_pages.endReading(chipFaults());
}
static const char* const margayChips[] = { "SDCard", "Clock", "BME280", "SensorBus", "Battery" };
static const char* const margayWords[] = { "LoggingStarted", "NewLogFile", "RowNotWritten" }; //unit kinds 16-18
static const char* const margayChipWords[] = { "BatteryWarning", "ClockSet" }; //kind 16 on Battery (0x90) and on Clock (0x30): one word each
size_t Margay::printStatus(Print& out, bool boot) {
const NW_Report& r = boot ? _bootReport : _pages.report();
//Kind 16 means a different thing on the unit, the battery and the clock: choose the word table by chip
const char* const* words = margayWords;
uint8_t n = 3;
if (r.chip() == 4) {
words = margayChipWords;
n = 1;
} else if (r.chip() == 1) {
words = margayChipWords + 1;
n = 1;
}
return _pages.printSnapshot(out, margayChips, 5, libVersion, &r, words, n, MARGAY_LIBRARY_COMMIT, "", SKETCH_COMMIT); //A logger: its library is its firmware; the sketch stands where a library would
}
void Margay::powerAux(bool state) {
pinMode(Ext3v3Ctrl, OUTPUT); //Setup outputs for robustness
if (state) powerOB(ON); //Turn on on-board power if required
if (_model >= MODEL_2v0) { //use positive logic for Model v2.0 and newer
digitalWrite(Ext3v3Ctrl, state); //Switch 3v3 Aux power
} else digitalWrite(Ext3v3Ctrl, !state); //Switch 3v3 Aux power
}
void Margay::powerOB(bool state) {
if (BatSwitch == 255) return; // No battery switch on this board model
pinMode(BatSwitch, OUTPUT);
digitalWrite(BatSwitch, state); //Set bat switch for onboard 3v3/main power
}
//Low Power functions
void Margay::sleepNow() { // here we put the arduino to sleep
/* Now is the time to set the sleep mode. In the Atmega8 datasheet
* http://www.atmel.com/dyn/resources/prod_documents/doc2486.pdf on page 35
* there is a list of sleep modes which explains which clocks and
* wake up sources are available in which sleep mode.
*
* In the avr/sleep.h file, the call names of these sleep modes
* are to be found:
*
* The 5 different modes are:
* SLEEP_MODE_IDLE -the least power savings
* SLEEP_MODE_ADC
* SLEEP_MODE_PWR_SAVE
* SLEEP_MODE_STANDBY
* SLEEP_MODE_PWR_DOWN -the most power savings
*
* For now, we want as much power savings as possible, so we
* choose the according
* sleep mode: SLEEP_MODE_PWR_DOWN
*
*/
turnOffSDcard();
digitalWrite(VSwitch_Pin, LOW); //DEBUG!
keep_ADCSRA = ADCSRA;
set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
cbi(ADCSRA, ADEN);
sleep_enable();
sleep_bod_disable();
sei();
sleep_cpu();
sleep_disable();
turnOnSDcard();
ADCSRA = 135; //DEBUG!
}
void Margay::turnOffSDcard() {
delay(6);
// NOTE: these are SCL (D16/PC0), SDA (D17/PC1), RX0 (D8/PD0), TX0 (D9/PD1)
// — not SD card pins. They are released here to prevent current leakage
// during sleep, but logically belong in sleepNow(). Deferred: moving them
// changes the order of operations relative to power cutoff and SPCR = 0.
pinMode(16, INPUT);
pinMode(17, INPUT);
pinMode(8, INPUT);
pinMode(9, INPUT);
delay(6);
powerAux(OFF); //turn off external 3v3 rail
powerOB(OFF); //Turn off battery connection to sense divider
delay(1);
digitalWrite(SD_CS, LOW);
delay(20);
SPCR = 0;
power_spi_disable();
delay(10);
}
void Margay::turnOnSDcard() {
powerOB(ON); //Turn on battery connection to sense divider
powerAux(ON); //turn on external 3v3 rail
delay(6); // let the card settle
power_spi_enable(); // enable the SPI clock
SPCR = keep_SPCR; // enable SPI peripheral
delay(10);
_sd.begin(SD_CS, SD_SCK_MHZ(8));
}