4 Commits

Author SHA1 Message Date
Obbart 7e7d0a1c59 Second ADC debugging in process 2026-04-21 16:11:07 +02:00
Emanuele Trabattoni dce6b0fd4f working on second adc 2026-04-17 13:24:43 +02:00
Emanuele Trabattoni bea29dc8f5 ADC ok with interrupt or drdy 2026-04-17 12:21:35 +02:00
Emanuele Trabattoni 1b8ba88b05 ADC working ok in sync with system 2026-04-17 11:01:41 +02:00
10 changed files with 852 additions and 772 deletions
+210 -175
View File
@@ -14,31 +14,64 @@
#include "Arduino.h"
#include "ADS1256.h"
#include "SPI.h"
#include <DebugLog.h>
#define convertSigned24BitToLong(value) ((value) & (1l << 23) ? (value) - 0x1000000 : value)
void IRAM_ATTR drdyCallback(void *arg)
{
auto cls = (ADS1256 *)arg;
if (!arg)
return;
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
if (digitalRead(cls->getDRDYpin())) // impose wait on low
{
xSemaphoreTakeFromISR(cls->getDRDYsemaphoreLow(), &xHigherPriorityTaskWoken);
xSemaphoreGiveFromISR(cls->getDRDYsemaphoreHigh(), &xHigherPriorityTaskWoken);
}
else // impose wait on high
{
xSemaphoreTakeFromISR(cls->getDRDYsemaphoreHigh(), &xHigherPriorityTaskWoken);
xSemaphoreGiveFromISR(cls->getDRDYsemaphoreLow(), &xHigherPriorityTaskWoken);
}
if (xHigherPriorityTaskWoken)
portYIELD_FROM_ISR();
}
// Constructor
ADS1256::ADS1256(const int8_t DRDY_pin, const int8_t RESET_pin, const int8_t SYNC_pin, const int8_t CS_pin, float VREF, SPIClass *spi) : _spi(spi),
_DRDY_pin(DRDY_pin), _RESET_pin(RESET_pin), _SYNC_pin(SYNC_pin), _CS_pin(CS_pin), _VREF(VREF), _PGA(0)
m_DRDY_pin(DRDY_pin), m_RESET_pin(RESET_pin), m_SYNC_pin(SYNC_pin), m_CS_pin(CS_pin), m_VREF(VREF), m_PGA(0)
{
pinMode(_DRDY_pin, INPUT);
pinMode(m_DRDY_pin, INPUT);
if (RESET_pin != PIN_UNUSED)
{
pinMode(_RESET_pin, OUTPUT);
pinMode(m_RESET_pin, OUTPUT);
}
if (SYNC_pin != PIN_UNUSED)
{
pinMode(_SYNC_pin, OUTPUT);
pinMode(m_SYNC_pin, OUTPUT);
}
if (CS_pin != PIN_UNUSED)
{
pinMode(_CS_pin, OUTPUT);
pinMode(m_CS_pin, OUTPUT);
}
updateConversionParameter();
// m_drdyHigh = xSemaphoreCreateBinary();
// m_drdyLow = xSemaphoreCreateBinary();
// if (!m_drdyHigh || !m_drdyLow) {
// LOG_ERROR("ADC Unable to create interrupt semaphores");
// return;
// }
// xSemaphoreGive(m_drdyHigh);
// xSemaphoreGive(m_drdyLow);
//attachInterruptArg(DRDY_pin, drdyCallback, (void *)this, CHANGE);
}
// Initialization
@@ -48,96 +81,94 @@ void ADS1256::InitializeADC()
CS_LOW();
// We do a manual chip reset on the ADS1256 - Datasheet Page 27/ RESET
if(_RESET_pin != PIN_UNUSED)
if (m_RESET_pin != PIN_UNUSED)
{
digitalWrite(_RESET_pin, LOW);
digitalWrite(m_RESET_pin, LOW);
delay(200);
digitalWrite(_RESET_pin, HIGH); //RESET is set to high
digitalWrite(m_RESET_pin, HIGH); // RESET is set to high
delay(1000);
}
// Sync pin is also treated if it is defined
if(_SYNC_pin != PIN_UNUSED)
if (m_SYNC_pin != PIN_UNUSED)
{
digitalWrite(_SYNC_pin, HIGH); //RESET is set to high
digitalWrite(m_SYNC_pin, HIGH); // RESET is set to high
}
#ifndef ADS1256_SPI_ALREADY_STARTED //Guard macro to allow external initialization of the SPI
_spi->begin();
#endif
// Applying arbitrary default values to speed up the starting procedure if the user just want to get quick readouts
// We both pass values to the variables and then send those values to the corresponding registers
delay(200);
_STATUS = 0b00110110; //BUFEN and ACAL enabled, Order is MSB, rest is read only
writeRegister(STATUS_REG, _STATUS);
m_STATUS = 0b00110110; // BUFEN and ACAL enabled, Order is MSB, rest is read only
writeRegister(STATUS_REG, m_STATUS);
delay(200);
_MUX = 0b00000001; //MUX AIN0+AIN1
writeRegister(MUX_REG, _MUX);
m_MUX = DIFF_0_1; // MUX AIN0+AIN1
writeRegister(MUX_REG, m_MUX);
delay(200);
_ADCON = 0b00000000; //ADCON - CLK: OFF, SDCS: OFF, PGA = 0 (+/- 5 V)
writeRegister(ADCON_REG, _ADCON);
m_ADCON = WAKEUP; // ADCON - CLK: OFF, SDCS: OFF, PGA = 0 (+/- 5 V)
writeRegister(ADCON_REG, m_ADCON);
delay(200);
updateConversionParameter();
_DRATE = 0b10000010; //100SPS
writeRegister(DRATE_REG, _DRATE);
m_DRATE = DRATE_100SPS; // 100SPS
writeRegister(DRATE_REG, m_DRATE);
delay(200);
sendDirectCommand(0b11110000); //Offset and self-gain calibration
sendDirectCommand(SELFCAL); // Offset and self-gain calibration
delay(200);
_isAcquisitionRunning = false; //MCU will be waiting to start a continuous acquisition
m_isAcquisitionRunning = false; // MCU will be waiting to start a continuous acquisition
}
void ADS1256::waitForLowDRDY()
{
while (digitalRead(_DRDY_pin) == HIGH) {}
while(digitalRead(m_DRDY_pin) == HIGH) {vTaskDelay(1);};
// xSemaphoreTake(m_drdyLow, pdMS_TO_TICKS(10));
// xSemaphoreGive(m_drdyLow);
}
void ADS1256::waitForHighDRDY()
{
#if F_CPU >= 48000000 //Fast MCUs need this protection to wait until DRDY goes high after a conversion
while (digitalRead(_DRDY_pin) == LOW) {}
#endif
while(digitalRead(m_DRDY_pin) == LOW) {vTaskDelay(1);};
// xSemaphoreTake(m_drdyHigh, pdMS_TO_TICKS(10));
// xSemaphoreGive(m_drdyHigh);
}
void ADS1256::stopConversion() // Sending SDATAC to stop the continuous conversion
{
waitForLowDRDY(); // SDATAC should be called after DRDY goes LOW (p35. Figure 33)
_spi->transfer(0b00001111); //Send SDATAC to the ADC
_spi->transfer(SDATAC); // Send SDATAC to the ADC
CS_HIGH(); // We finished the command sequence, so we switch it back to HIGH
_spi->endTransaction();
_isAcquisitionRunning = false; //Reset to false, so the MCU will be able to start a new conversion
m_isAcquisitionRunning = false; // Reset to false, so the MCU will be able to start a new conversion
}
void ADS1256::setDRATE(uint8_t drate) // Setting DRATE (sampling frequency)
{
writeRegister(DRATE_REG, drate);
_DRATE = drate;
m_DRATE = drate;
delay(200);
}
void ADS1256::setMUX(uint8_t mux) // Setting MUX (input channel)
{
writeRegister(MUX_REG, mux);
_MUX = mux;
m_MUX = mux;
delay(200);
}
void ADS1256::setPGA(uint8_t pga) // Setting PGA (input voltage range)
{
_PGA = pga;
_ADCON = readRegister(ADCON_REG); //Read the most recent value of the register
m_PGA = pga;
m_ADCON = readRegister(ADCON_REG); // Read the most recent value of the register
_ADCON = (_ADCON & 0b11111000) | (_PGA & 0b00000111); // Clearing and then setting bits 2-0 based on pga
m_ADCON = (m_ADCON & 0b11111000) | (m_PGA & 0b00000111); // Clearing and then setting bits 2-0 based on pga
writeRegister(ADCON_REG, _ADCON);
writeRegister(ADCON_REG, m_ADCON);
delay(200);
updateConversionParameter(); // Update the multiplier according top the new PGA value
@@ -153,95 +184,101 @@ uint8_t ADS1256::getPGA() //Reading PGA from the ADCON register
void ADS1256::setCLKOUT(uint8_t clkout) // Setting CLKOUT
{
_ADCON = readRegister(ADCON_REG); //Read the most recent value of the register
m_ADCON = readRegister(ADCON_REG); // Read the most recent value of the register
// Values: 0, 1, 2, 3
if (clkout == 0)
{
// 00
bitWrite(_ADCON, 6, 0);
bitWrite(_ADCON, 5, 0);
bitWrite(m_ADCON, 6, 0);
bitWrite(m_ADCON, 5, 0);
}
else if (clkout == 1)
{
// 01 (default)
bitWrite(_ADCON, 6, 0);
bitWrite(_ADCON, 5, 1);
bitWrite(m_ADCON, 6, 0);
bitWrite(m_ADCON, 5, 1);
}
else if (clkout == 2)
{
// 10
bitWrite(_ADCON, 6, 1);
bitWrite(_ADCON, 5, 0);
bitWrite(m_ADCON, 6, 1);
bitWrite(m_ADCON, 5, 0);
}
else if (clkout == 3)
{
// 11
bitWrite(_ADCON, 6, 1);
bitWrite(_ADCON, 5, 1);
bitWrite(m_ADCON, 6, 1);
bitWrite(m_ADCON, 5, 1);
}
else
{
}
else{}
writeRegister(ADCON_REG, _ADCON);
writeRegister(ADCON_REG, m_ADCON);
delay(100);
}
void ADS1256::setSDCS(uint8_t sdcs) // Setting SDCS
{
_ADCON = readRegister(ADCON_REG); //Read the most recent value of the register
m_ADCON = readRegister(ADCON_REG); // Read the most recent value of the register
// Values: 0, 1, 2, 3
if (sdcs == 0)
{
// 00 (default)
bitWrite(_ADCON, 4, 0);
bitWrite(_ADCON, 3, 0);
bitWrite(m_ADCON, 4, 0);
bitWrite(m_ADCON, 3, 0);
}
else if (sdcs == 1)
{
// 01
bitWrite(_ADCON, 4, 0);
bitWrite(_ADCON, 3, 1);
bitWrite(m_ADCON, 4, 0);
bitWrite(m_ADCON, 3, 1);
}
else if (sdcs == 2)
{
// 10
bitWrite(_ADCON, 4, 1);
bitWrite(_ADCON, 3, 0);
bitWrite(m_ADCON, 4, 1);
bitWrite(m_ADCON, 3, 0);
}
else if (sdcs == 3)
{
// 11
bitWrite(_ADCON, 4, 1);
bitWrite(_ADCON, 3, 1);
bitWrite(m_ADCON, 4, 1);
bitWrite(m_ADCON, 3, 1);
}
else
{
}
else{}
writeRegister(ADCON_REG, _ADCON);
writeRegister(ADCON_REG, m_ADCON);
delay(100);
}
void ADS1256::setByteOrder(uint8_t byteOrder) // Setting byte order (MSB/LSB)
{
_STATUS = readRegister(STATUS_REG); //Read the most recent value of the register
m_STATUS = readRegister(STATUS_REG); // Read the most recent value of the register
if (byteOrder == 0)
{
// Byte order is MSB (default)
bitWrite(_STATUS, 3, 0);
bitWrite(m_STATUS, 3, 0);
// Set value of _STATUS at the third bit to 0
}
else if (byteOrder == 1)
{
// Byte order is LSB
bitWrite(_STATUS, 3, 1);
bitWrite(m_STATUS, 3, 1);
// Set value of _STATUS at the third bit to 1
}
else{}
else
{
}
writeRegister(STATUS_REG, _STATUS);
writeRegister(STATUS_REG, m_STATUS);
delay(100);
}
@@ -254,23 +291,25 @@ uint8_t ADS1256::getByteOrder() //Getting byte order (MSB/LSB)
void ADS1256::setAutoCal(uint8_t acal) // Setting ACAL (Automatic SYSCAL)
{
_STATUS = readRegister(STATUS_REG); //Read the most recent value of the register
m_STATUS = readRegister(STATUS_REG); // Read the most recent value of the register
if (acal == 0)
{
// Auto-calibration is disabled (default)
bitWrite(_STATUS, 2, 0);
bitWrite(m_STATUS, 2, 0);
//_STATUS |= B00000000;
}
else if (acal == 1)
{
// Auto-calibration is enabled
bitWrite(_STATUS, 2, 1);
bitWrite(m_STATUS, 2, 1);
//_STATUS |= B00000100;
}
else{}
else
{
}
writeRegister(STATUS_REG, _STATUS);
writeRegister(STATUS_REG, m_STATUS);
delay(100);
}
@@ -283,23 +322,25 @@ uint8_t ADS1256::getAutoCal() //Getting ACAL (Automatic SYSCAL)
void ADS1256::setBuffer(uint8_t bufen) // Setting input buffer (Input impedance)
{
_STATUS = readRegister(STATUS_REG); //Read the most recent value of the register
m_STATUS = readRegister(STATUS_REG); // Read the most recent value of the register
if (bufen == 0)
{
// Analog input buffer is disabled (default)
//_STATUS |= B00000000;
bitWrite(_STATUS, 1, 0);
bitWrite(m_STATUS, 1, 0);
}
else if (bufen == 1)
{
// Analog input buffer is enabled (recommended)
//_STATUS |= B00000010;
bitWrite(_STATUS, 1, 1);
bitWrite(m_STATUS, 1, 1);
}
else
{
}
else{}
writeRegister(STATUS_REG, _STATUS);
writeRegister(STATUS_REG, m_STATUS);
delay(100);
}
@@ -312,7 +353,7 @@ uint8_t ADS1256::getBuffer() //Getting input buffer (Input impedance)
void ADS1256::setGPIO(uint8_t dir0, uint8_t dir1, uint8_t dir2, uint8_t dir3) // Setting GPIO
{
_GPIO = readRegister(IO_REG); //Read the most recent value of the register
m_GPIO = readRegister(IO_REG); // Read the most recent value of the register
// Default: 11100000 - DEC: 224 - Ref: p32 I/O section
// Sets D3-D0 as input or output
@@ -327,7 +368,7 @@ void ADS1256::setGPIO(uint8_t dir0, uint8_t dir1, uint8_t dir2, uint8_t dir3) //
{
GPIO_bit7 = 0; // D3 is output
}
bitWrite(_GPIO, 7, GPIO_bit7);
bitWrite(m_GPIO, 7, GPIO_bit7);
//-----------------------------------------------------
// Bit6: DIR2
if (dir2 == 1)
@@ -338,7 +379,7 @@ void ADS1256::setGPIO(uint8_t dir0, uint8_t dir1, uint8_t dir2, uint8_t dir3) //
{
GPIO_bit6 = 0; // D2 is output
}
bitWrite(_GPIO, 6, GPIO_bit6);
bitWrite(m_GPIO, 6, GPIO_bit6);
//-----------------------------------------------------
// Bit5: DIR1
if (dir1 == 1)
@@ -349,7 +390,7 @@ void ADS1256::setGPIO(uint8_t dir0, uint8_t dir1, uint8_t dir2, uint8_t dir3) //
{
GPIO_bit5 = 0; // D1 is output
}
bitWrite(_GPIO, 5, GPIO_bit5);
bitWrite(m_GPIO, 5, GPIO_bit5);
//-----------------------------------------------------
// Bit4: DIR0
if (dir0 == 1)
@@ -360,16 +401,16 @@ void ADS1256::setGPIO(uint8_t dir0, uint8_t dir1, uint8_t dir2, uint8_t dir3) //
{
GPIO_bit4 = 0; // D0 is output (default)
}
bitWrite(_GPIO, 4, GPIO_bit4);
bitWrite(m_GPIO, 4, GPIO_bit4);
//-----------------------------------------------------
writeRegister(IO_REG, _GPIO);
writeRegister(IO_REG, m_GPIO);
delay(100);
}
void ADS1256::writeGPIO(uint8_t dir0value, uint8_t dir1value, uint8_t dir2value, uint8_t dir3value) // Writing GPIO
{
_GPIO = readRegister(IO_REG);
m_GPIO = readRegister(IO_REG);
// Sets D3-D0 output values
// It is important that first one must use setGPIO, then writeGPIO
@@ -385,7 +426,7 @@ void ADS1256::writeGPIO(uint8_t dir0value, uint8_t dir1value, uint8_t dir2value,
{
GPIO_bit3 = 0;
}
bitWrite(_GPIO, 3, GPIO_bit3);
bitWrite(m_GPIO, 3, GPIO_bit3);
//-----------------------------------------------------
// Bit2: DIR2
if (dir2value == 1)
@@ -396,7 +437,7 @@ void ADS1256::writeGPIO(uint8_t dir0value, uint8_t dir1value, uint8_t dir2value,
{
GPIO_bit2 = 0;
}
bitWrite(_GPIO, 2, GPIO_bit2);
bitWrite(m_GPIO, 2, GPIO_bit2);
//-----------------------------------------------------
// Bit1: DIR1
if (dir1value == 1)
@@ -407,7 +448,7 @@ void ADS1256::writeGPIO(uint8_t dir0value, uint8_t dir1value, uint8_t dir2value,
{
GPIO_bit1 = 0;
}
bitWrite(_GPIO, 1, GPIO_bit1);
bitWrite(m_GPIO, 1, GPIO_bit1);
//-----------------------------------------------------
// Bit0: DIR0
if (dir0value == 1)
@@ -418,10 +459,10 @@ void ADS1256::writeGPIO(uint8_t dir0value, uint8_t dir1value, uint8_t dir2value,
{
GPIO_bit0 = 0;
}
bitWrite(_GPIO, 0, GPIO_bit0);
bitWrite(m_GPIO, 0, GPIO_bit0);
//-----------------------------------------------------
writeRegister(IO_REG, _GPIO);
writeRegister(IO_REG, m_GPIO);
delay(100);
}
@@ -429,13 +470,13 @@ uint8_t ADS1256::readGPIO(uint8_t gpioPin) //Reading GPIO
{
uint8_t GPIO_bit3, GPIO_bit2, GPIO_bit1, GPIO_bit0, GPIO_return;
_GPIO = readRegister(IO_REG); //Read the GPIO register
m_GPIO = readRegister(IO_REG); // Read the GPIO register
// Save each bit values in a variable
GPIO_bit3 = bitRead(_GPIO, 3);
GPIO_bit2 = bitRead(_GPIO, 2);
GPIO_bit1 = bitRead(_GPIO, 1);
GPIO_bit0 = bitRead(_GPIO, 0);
GPIO_bit3 = bitRead(m_GPIO, 3);
GPIO_bit2 = bitRead(m_GPIO, 2);
GPIO_bit1 = bitRead(m_GPIO, 1);
GPIO_bit0 = bitRead(m_GPIO, 0);
delay(100);
@@ -459,13 +500,12 @@ uint8_t ADS1256::readGPIO(uint8_t gpioPin) //Reading GPIO
}
return GPIO_return;
}
void ADS1256::sendDirectCommand(uint8_t directCommand)
{
// Direct commands can be found in the datasheet Page 34, Table 24.
_spi->beginTransaction(SPISettings(1920000, MSBFIRST, SPI_MODE1));
_spi->beginTransaction(SPISettings(SPI_FREQ, MSBFIRST, SPI_MODE1));
CS_LOW(); // REF: P34: "CS must stay low during the entire command sequence"
delayMicroseconds(5);
@@ -476,24 +516,23 @@ void ADS1256::sendDirectCommand(uint8_t directCommand)
_spi->endTransaction();
}
float ADS1256::convertToVoltage(int32_t rawData) // Converting the 24-bit data into a voltage value
{
return(conversionParameter * rawData);
return (m_conversionParameter * rawData);
}
void ADS1256::writeRegister(uint8_t registerAddress, uint8_t registerValueToWrite)
{
waitForLowDRDY();
_spi->beginTransaction(SPISettings(1920000, MSBFIRST, SPI_MODE1));
_spi->beginTransaction(SPISettings(SPI_FREQ, MSBFIRST, SPI_MODE1));
// SPI_MODE1 = output edge: rising, data capture: falling; clock polarity: 0, clock phase: 1.
CS_LOW(); // CS must stay LOW during the entire sequence [Ref: P34, T24]
delayMicroseconds(5); // see t6 in the datasheet
_spi->transfer(0x50 | registerAddress); // 0x50 = 01010000 = WREG
_spi->transfer(WREG | registerAddress); // 0x50 = 01010000 = WREG
_spi->transfer(0x00); // 2nd (empty) command byte
@@ -502,25 +541,24 @@ void ADS1256::writeRegister(uint8_t registerAddress, uint8_t registerValueToWrit
CS_HIGH();
_spi->endTransaction();
delay(100);
}
long ADS1256::readRegister(uint8_t registerAddress) // Reading a register
{
waitForLowDRDY();
_spi->beginTransaction(SPISettings(1920000, MSBFIRST, SPI_MODE1));
_spi->beginTransaction(SPISettings(SPI_FREQ, MSBFIRST, SPI_MODE1));
// SPI_MODE1 = output edge: rising, data capture: falling; clock polarity: 0, clock phase: 1.
CS_LOW(); // CS must stay LOW during the entire sequence [Ref: P34, T24]
_spi->transfer(0x10 | registerAddress); //0x10 = 0001000 = RREG - OR together the two numbers (command + address)
_spi->transfer(RREG | registerAddress); // 0x10 = 0001000 = RREG - OR together the two numbers (command + address)
_spi->transfer(0x00); // 2nd (empty) command byte
delayMicroseconds(5); // see t6 in the datasheet
uint8_t regValue = _spi->transfer(0xFF); //read out the register value
uint8_t regValue = _spi->transfer(0x00); // read out the register value
CS_HIGH();
_spi->endTransaction();
@@ -528,38 +566,37 @@ long ADS1256::readRegister(uint8_t registerAddress) //Reading a register
return regValue;
}
long ADS1256::readSingle() // Reading a single value ONCE using the RDATA command
{
_spi->beginTransaction(SPISettings(1920000, MSBFIRST, SPI_MODE1));
_spi->beginTransaction(SPISettings(SPI_FREQ, MSBFIRST, SPI_MODE1));
CS_LOW(); // REF: P34: "CS must stay low during the entire command sequence"
waitForLowDRDY();
_spi->transfer(0b00000001); //Issue RDATA (0000 0001) command
_spi->transfer(RDATA); // Issue RDATA (0000 0001) command
delayMicroseconds(7); // Wait t6 time (~6.51 us) REF: P34, FIG:30.
_outputBuffer[0] = _spi->transfer(0); // MSB
_outputBuffer[1] = _spi->transfer(0); // Mid-byte
_outputBuffer[2] = _spi->transfer(0); // LSB
m_outputBuffer[0] = _spi->transfer(0); // MSB
m_outputBuffer[1] = _spi->transfer(0); // Mid-byte
m_outputBuffer[2] = _spi->transfer(0); // LSB
// Shifting and combining the above three items into a single, 24-bit number
_outputValue = ((long)_outputBuffer[0]<<16) | ((long)_outputBuffer[1]<<8) | (_outputBuffer[2]);
_outputValue = convertSigned24BitToLong(_outputValue);
m_outputValue = ((long)m_outputBuffer[0] << 16) | ((long)m_outputBuffer[1] << 8) | (m_outputBuffer[2]);
m_outputValue = convertSigned24BitToLong(m_outputValue);
CS_HIGH(); // We finished the command sequence, so we set CS to HIGH
_spi->endTransaction();
return(_outputValue);
return (m_outputValue);
}
long ADS1256::readSingleContinuous() // Reads the recently selected input channel using RDATAC
{
if(_isAcquisitionRunning == false)
if (m_isAcquisitionRunning == false)
{
_isAcquisitionRunning = true;
_spi->beginTransaction(SPISettings(1920000, MSBFIRST, SPI_MODE1));
m_isAcquisitionRunning = true;
_spi->beginTransaction(SPISettings(SPI_FREQ, MSBFIRST, SPI_MODE1));
CS_LOW(); // REF: P34: "CS must stay low during the entire command sequence"
waitForLowDRDY();
_spi->transfer(0b00000011); //Issue RDATAC (0000 0011)
_spi->transfer(RDATAC); // Issue RDATAC (0000 0011)
delayMicroseconds(7); // Wait t6 time (~6.51 us) REF: P34, FIG:30.
}
else
@@ -567,42 +604,41 @@ long ADS1256::readSingleContinuous() //Reads the recently selected input channel
waitForLowDRDY();
}
_outputBuffer[0] = _spi->transfer(0); // MSB
_outputBuffer[1] = _spi->transfer(0); // Mid-byte
_outputBuffer[2] = _spi->transfer(0); // LSB
m_outputBuffer[0] = _spi->transfer(0); // MSB
m_outputBuffer[1] = _spi->transfer(0); // Mid-byte
m_outputBuffer[2] = _spi->transfer(0); // LSB
_outputValue = ((long)_outputBuffer[0]<<16) | ((long)_outputBuffer[1]<<8) | (_outputBuffer[2]);
_outputValue = convertSigned24BitToLong(_outputValue);
m_outputValue = ((long)m_outputBuffer[0] << 16) | ((long)m_outputBuffer[1] << 8) | (m_outputBuffer[2]);
m_outputValue = convertSigned24BitToLong(m_outputValue);
waitForHighDRDY();
return _outputValue;
return m_outputValue;
}
long ADS1256::cycleSingle()
{
if(_isAcquisitionRunning == false)
if (m_isAcquisitionRunning == false)
{
_isAcquisitionRunning = true;
_cycle = 0;
_spi->beginTransaction(SPISettings(1920000, MSBFIRST, SPI_MODE1));
m_isAcquisitionRunning = true;
m_cycle = 0;
_spi->beginTransaction(SPISettings(SPI_FREQ, MSBFIRST, SPI_MODE1));
CS_LOW(); // CS must stay LOW during the entire sequence [Ref: P34, T24]
_spi->transfer(0x50 | 1); // 0x50 = WREG //1 = MUX
_spi->transfer(WREG | MUX_REG); // 0x50 = WREG //1 = MUX
_spi->transfer(0x00);
_spi->transfer(SING_0); // AIN0+AINCOM
CS_HIGH();
delay(50);
CS_LOW(); //CS must stay LOW during the entire sequence [Ref: P34, T24]
delayMicroseconds(250);
}
else
{}
if(_cycle < 8)
{
_outputValue = 0;
}
if (m_cycle < 8)
{
m_outputValue = 0;
waitForLowDRDY();
// Step 1. - Updating MUX
switch (_cycle)
switch (m_cycle)
{
// Channels are written manually
case 0: // Channel 2
@@ -638,60 +674,59 @@ long ADS1256::cycleSingle()
break;
}
// Step 2.
_spi->transfer(0b11111100); //SYNC
_spi->transfer(SYNC); // SYNC
delayMicroseconds(4); // t11 delay 24*tau = 3.125 us //delay should be larger, so we delay by 4 us
_spi->transfer(0b11111111); //WAKEUP
_spi->transfer(WAKEUP); // WAKEUP
// Step 3.
// Issue RDATA (0000 0001) command
_spi->transfer(0b00000001);
_spi->transfer(RDATA);
delayMicroseconds(7); // Wait t6 time (~6.51 us) REF: P34, FIG:30.
_outputBuffer[0] = _spi->transfer(0x0F); // MSB
_outputBuffer[1] = _spi->transfer(0x0F); // Mid-byte
_outputBuffer[2] = _spi->transfer(0x0F); // LSB
m_outputBuffer[0] = _spi->transfer(0); // MSB
m_outputBuffer[1] = _spi->transfer(0); // Mid-byte
m_outputBuffer[2] = _spi->transfer(0); // LSB
_outputValue = ((long)_outputBuffer[0]<<16) | ((long)_outputBuffer[1]<<8) | (_outputBuffer[2]);
_outputValue = convertSigned24BitToLong(_outputValue);
m_outputValue = ((long)m_outputBuffer[0] << 16) | ((long)m_outputBuffer[1] << 8) | (m_outputBuffer[2]);
m_outputValue = convertSigned24BitToLong(m_outputValue);
_cycle++; //Increase cycle - This will move to the next MUX input channel
if(_cycle == 8)
m_cycle++; // Increase cycle - This will move to the next MUX input channel
if (m_cycle == 8)
{
_cycle = 0; //Reset to 0 - Restart conversion from the 1st input channel
m_cycle = 0; // Reset to 0 - Restart conversion from the 1st input channel
}
}
return _outputValue;
return m_outputValue;
}
long ADS1256::cycleDifferential()
{
if(_isAcquisitionRunning == false)
if (m_isAcquisitionRunning == false)
{
_cycle = 0;
_isAcquisitionRunning = true;
_spi->beginTransaction(SPISettings(1920000, MSBFIRST, SPI_MODE1));
m_cycle = 0;
m_isAcquisitionRunning = true;
_spi->beginTransaction(SPISettings(SPI_FREQ, MSBFIRST, SPI_MODE1));
// Set the AIN0+AIN1 as inputs manually
CS_LOW(); // CS must stay LOW during the entire sequence [Ref: P34, T24]
_spi->transfer(0x50 | 1); // 0x50 = WREG //1 = MUX
_spi->transfer(WREG | MUX_REG); // 0x50 = WREG //1 = MUX
_spi->transfer(0x00);
_spi->transfer(DIFF_0_1); // AIN0+AIN1
CS_HIGH();
delay(50);
CS_LOW(); //CS must stay LOW during the entire sequence [Ref: P34, T24]
delayMicroseconds(250);
}
else
{}
if(_cycle < 4)
{
_outputValue = 0;
}
if (m_cycle < 4)
{
m_outputValue = 0;
// DRDY has to go low
waitForLowDRDY();
// Step 1. - Updating MUX
switch (_cycle)
switch (m_cycle)
{
case 0: // Channel 2
updateMUX(DIFF_2_3); // AIN2+AIN3
@@ -710,57 +745,57 @@ long ADS1256::cycleDifferential()
break;
}
_spi->transfer(0b11111100); //SYNC
_spi->transfer(SYNC); // SYNC
delayMicroseconds(4); // t11 delay 24*tau = 3.125 us //delay should be larger, so we delay by 4 us
_spi->transfer(0b11111111); //WAKEUP
_spi->transfer(WAKEUP); // WAKEUP
// Step 3.
_spi->transfer(0b00000001); //Issue RDATA (0000 0001) command
_spi->transfer(RDATA); // Issue RDATA (0000 0001) command
delayMicroseconds(7); // Wait t6 time (~6.51 us) REF: P34, FIG:30.
_outputBuffer[0] = _spi->transfer(0); // MSB
_outputBuffer[1] = _spi->transfer(0); // Mid-byte
_outputBuffer[2] = _spi->transfer(0); // LSB
m_outputBuffer[0] = _spi->transfer(0); // MSB
m_outputBuffer[1] = _spi->transfer(0); // Mid-byte
m_outputBuffer[2] = _spi->transfer(0); // LSB
_outputValue = ((long)_outputBuffer[0]<<16) | ((long)_outputBuffer[1]<<8) | (_outputBuffer[2]);
_outputValue = convertSigned24BitToLong(_outputValue);
m_outputValue = ((long)m_outputBuffer[0] << 16) | ((long)m_outputBuffer[1] << 8) | (m_outputBuffer[2]);
m_outputValue = convertSigned24BitToLong(m_outputValue);
_cycle++;
if(_cycle == 4)
m_cycle++;
if (m_cycle == 4)
{
_cycle = 0;
m_cycle = 0;
// After the 4th cycle, we reset to zero so the next iteration reads the 1st MUX again
}
}
return _outputValue;
return m_outputValue;
}
void ADS1256::updateConversionParameter()
{
conversionParameter = ((2.0 * _VREF) / 8388608.0) / (pow(2, _PGA)); //Calculate the "bit to Volts" multiplier
m_conversionParameter = ((2.0 * m_VREF) / 8388608.0) / (pow(2, m_PGA)); // Calculate the "bit to Volts" multiplier
// 8388608 = 2^{23} - 1, REF: p23, Table 16.
}
void ADS1256::updateMUX(uint8_t muxValue)
{
_spi->transfer(0x50 | MUX_REG); //Write to the MUX register (0x50 is the WREG command)
_spi->transfer(WREG | MUX_REG); // Write to the MUX register (0x50 is the WREG command)
_spi->transfer(0x00);
_spi->transfer(muxValue); // Write the new MUX value
}
inline void ADS1256::CS_LOW()
{
if (_CS_pin != PIN_UNUSED) //Sets CS LOW if it is not an unused pin
if (m_CS_pin != PIN_UNUSED) // Sets CS LOW if it is not an unused pin
{
digitalWrite(_CS_pin, LOW);
digitalWrite(m_CS_pin, LOW);
}
}
inline void ADS1256::CS_HIGH()
{
if (_CS_pin != PIN_UNUSED) //Sets CS HIGH if it is not an unused pin
if (m_CS_pin != PIN_UNUSED) // Sets CS HIGH if it is not an unused pin
{
digitalWrite(_CS_pin, HIGH);
digitalWrite(m_CS_pin, HIGH);
}
}
+46 -20
View File
@@ -14,6 +14,10 @@
#define _ADS1256_h
#include <SPI.h>
#include <Arduino.h>
// SPI Frequency
#define SPI_FREQ 1920000
// Differential inputs
#define DIFF_0_1 0b00000001 // A0 + A1 as differential input
@@ -96,7 +100,6 @@
#define RESET 0b11111110
//----------------------------------------------------------------
class ADS1256
{
public:
@@ -104,6 +107,11 @@ static constexpr int8_t PIN_UNUSED = -1;
// Constructor
ADS1256(const int8_t DRDY_pin, const int8_t RESET_pin, const int8_t SYNC_pin, const int8_t CS_pin, float VREF, SPIClass *spi = &SPI);
~ADS1256()
{
vSemaphoreDelete(m_drdyHigh);
vSemaphoreDelete(m_drdyLow);
}
// Initializing function
void InitializeADC();
@@ -151,8 +159,23 @@ static constexpr int8_t PIN_UNUSED = -1;
// Stop AD
void stopConversion();
private:
// functions for callback
inline uint8_t getDRDYpin()
{
return m_DRDY_pin;
}
SemaphoreHandle_t getDRDYsemaphoreHigh()
{
return m_drdyHigh;
}
SemaphoreHandle_t getDRDYsemaphoreLow()
{
return m_drdyLow;
}
private:
SPIClass *_spi; // Pointer to an SPIClass object
void waitForLowDRDY(); // Block until DRDY is low
@@ -163,27 +186,30 @@ inline void CS_HIGH();
void updateConversionParameter(); // Refresh the conversion parameter based on the PGA
float _VREF = 0; //Value of the reference voltage
float conversionParameter = 0; //PGA-dependent multiplier
float m_VREF = 0; // Value of the reference voltage
float m_conversionParameter = 0; // PGA-dependent multiplier
// Pins
int8_t _DRDY_pin; //Pin assigned for DRDY
int8_t _RESET_pin; //Pin assigned for RESET
int8_t _SYNC_pin; //Pin assigned for SYNC
int8_t _CS_pin; //Pin assigned for CS
int8_t m_DRDY_pin; // Pin assigned for DRDY
int8_t m_RESET_pin; // Pin assigned for RESET
int8_t m_SYNC_pin; // Pin assigned for SYNC
int8_t m_CS_pin; // Pin assigned for CS
// Register values
byte _DRATE; //Value of the DRATE register
byte _ADCON; //Value of the ADCON register
byte _MUX; //Value of the MUX register
byte _PGA; //Value of the PGA (within ADCON)
byte _GPIO; //Value of the GPIO register
byte _STATUS; //Value of the status register
byte _GPIOvalue; //GPIO value
byte _ByteOrder; //Byte order
uint8_t m_DRATE; // Value of the DRATE register
uint8_t m_ADCON; // Value of the ADCON register
uint8_t m_MUX; // Value of the MUX register
uint8_t m_PGA; // Value of the PGA (within ADCON)
uint8_t m_GPIO; // Value of the GPIO register
uint8_t m_STATUS; // Value of the status register
uint8_t m_GPIOvalue; // GPIO value
uint8_t m_ByteOrder; // Byte order
byte _outputBuffer[3]; //3-byte (24-bit) buffer for the fast acquisition - Single-channel, continuous
long _outputValue; //Combined value of the _outputBuffer[3]
bool _isAcquisitionRunning; //bool that keeps track of the acquisition (running or not)
uint8_t _cycle; //Tracks the cycles as the MUX is cycling through the input channels
uint8_t m_outputBuffer[3]; // 3-byte (24-bit) buffer for the fast acquisition - Single-channel, continuous
int32_t m_outputValue; // Combined value of the m_outputBuffer[3]
bool m_isAcquisitionRunning; // bool that keeps track of the acquisition (running or not)
uint8_t m_cycle; // Tracks the cycles as the MUX is cycling through the input channels
SemaphoreHandle_t m_drdyHigh;
SemaphoreHandle_t m_drdyLow;
};
#endif
+4 -8
View File
@@ -20,7 +20,6 @@ lib_deps =
hideakitai/PCA95x5@^0.1.3
me-no-dev/AsyncTCP@^3.3.2
me-no-dev/ESPAsyncWebServer@^3.6.0
adafruit/Adafruit NeoPixel@^1.15.4
upload_protocol = esptool
upload_port = /dev/ttyACM1
upload_speed = 921600
@@ -28,15 +27,14 @@ monitor_port = /dev/ttyACM0
monitor_speed = 921600
build_type = release
build_flags =
-DCORE_DEBUG_LEVEL=5
-DCORE_DEBUG_LEVEL=3
-DARDUINO_USB_CDC_ON_BOOT=0
-DARDUINO_USB_MODE=0
-DCONFIG_ASYNC_TCP_MAX_ACK_TIME=5000
-DCONFIG_ASYNC_TCP_PRIORITY=21
-DCONFIG_ASYNC_TCP_QUEUE_SIZE=64
-DCONFIG_ASYNC_TCP_QUEUE_SIZE=128
-DCONFIG_ASYNC_TCP_RUNNING_CORE=1
-DCONFIG_ASYNC_TCP_STACK_SIZE=4096
-fstack-protector-all
-DCONFIG_ASYNC_TCP_STACK_SIZE=8192
[env:esp32-s3-devkitc1-n16r8-debug]
board = ${env:esp32-s3-devkitc1-n16r8.board}
@@ -46,7 +44,6 @@ platform = ${env:esp32-s3-devkitc1-n16r8.platform}
framework = ${env:esp32-s3-devkitc1-n16r8.framework}
lib_deps =
${env:esp32-s3-devkitc1-n16r8.lib_deps}
adafruit/Adafruit NeoPixel@^1.15.4
upload_protocol = esptool
upload_port = /dev/ttyACM1
upload_speed = 921600
@@ -59,7 +56,7 @@ build_flags =
-O0
-g3
-ggdb3
-DCORE_DEBUG_LEVEL=5
-DCORE_DEBUG_LEVEL=3
-DARDUINO_USB_CDC_ON_BOOT=0
-DARDUINO_USB_MODE=0
-DCONFIG_ASYNC_TCP_MAX_ACK_TIME=5000
@@ -67,4 +64,3 @@ build_flags =
-DCONFIG_ASYNC_TCP_QUEUE_SIZE=128
-DCONFIG_ASYNC_TCP_RUNNING_CORE=1
-DCONFIG_ASYNC_TCP_STACK_SIZE=8192
-fstack-protector-all
+13 -15
View File
@@ -48,30 +48,28 @@ void ignitionBoxStatusFiltered::update(const ignitionBoxStatus &new_status)
m_count++;
// simple moving average calculation
m_last.timestamp = new_status.timestamp; // keep timestamp of latest status
m_last.coils12.n_events = new_status.coils12.n_events; // sum events instead of averaging
m_last.coils12.n_missed_firing = new_status.coils12.n_missed_firing; // sum missed firings instead of averaging
m_last.coils12.spark_status = new_status.coils12.spark_status; // take latest spark status
m_last.coils12.sstart_status = new_status.coils12.sstart_status; // take latest soft start status
m_last.coils12.spark_delay = new_status.coils12.spark_delay; // incremental average calculation
m_last.coils12.peak_p_in = new_status.coils12.peak_p_in; // incremental average calculation
m_last.coils12.peak_n_in = new_status.coils12.peak_n_in; // incremental average calculation
m_last.coils12.peak_p_out = new_status.coils12.peak_p_out; // incremental average calculation
m_last.coils12.peak_n_out = new_status.coils12.peak_n_out; // incremental average calculation
filter(m_last.coils12.spark_delay, new_status.coils12.spark_delay, m_max_count); // incremental average calculation
filter(m_last.coils12.peak_p_in, new_status.coils12.peak_p_in, m_max_count); // incremental average calculation
filter(m_last.coils12.peak_n_in, new_status.coils12.peak_n_in, m_max_count); // incremental average calculation
filter(m_last.coils12.peak_p_out, new_status.coils12.peak_p_out, m_max_count); // incremental average calculation
filter(m_last.coils12.peak_n_out, new_status.coils12.peak_n_out, m_max_count); // incremental average calculation
m_last.coils34.n_events = new_status.coils34.n_events; // sum events instead of averaging
m_last.coils34.n_missed_firing = new_status.coils34.n_missed_firing; // sum missed firings instead of averaging
m_last.coils34.spark_status = new_status.coils34.spark_status; // take latest spark status
m_last.coils34.sstart_status = new_status.coils34.sstart_status; // take latest soft start status
m_last.coils34.spark_delay = new_status.coils34.spark_delay; // incremental average calculation
m_last.coils34.peak_p_in = new_status.coils34.peak_p_in; // incremental average calculation
m_last.coils34.peak_n_in = new_status.coils34.peak_n_in; // incremental average calculation
m_last.coils34.peak_p_out = new_status.coils34.peak_p_out; // incremental average calculation
m_last.coils34.peak_n_out = new_status.coils34.peak_n_out; // incremental average calculation
m_last.eng_rpm = new_status.eng_rpm; // incremental average calculation
m_last.adc_read_time = m_last.adc_read_time; // incremental average calculation
m_last.n_queue_errors = new_status.n_queue_errors; // take last of queue errors since it's a cumulative count of errors in the queue, not an average value
filter(m_last.coils34.spark_delay, new_status.coils34.spark_delay, m_max_count); // incremental average calculation
filter(m_last.coils34.peak_p_in, new_status.coils34.peak_p_in, m_max_count); // incremental average calculation
filter(m_last.coils34.peak_n_in, new_status.coils34.peak_n_in, m_max_count); // incremental average calculation
filter(m_last.coils34.peak_p_out, new_status.coils34.peak_p_out, m_max_count); // incremental average calculation
filter(m_last.coils34.peak_n_out, new_status.coils34.peak_n_out, m_max_count); // incremental average calculation
filter(m_last.eng_rpm, new_status.eng_rpm, m_max_count); // incremental average calculation // incremental average calculation
filter(m_last.adc_read_time, m_last.adc_read_time, m_max_count); // incremental average calculation
m_last.n_queue_errors = new_status.n_queue_errors;
if (m_count >= m_max_count)
{
+8 -8
View File
@@ -26,9 +26,9 @@
struct Devices
{
// Busses
std::unique_ptr<TwoWire> m_i2c = nullptr;
std::unique_ptr<SPIClass> m_spi_a = nullptr;
std::unique_ptr<SPIClass> m_spi_b = nullptr;
TwoWire *m_i2c = NULL;
SPIClass *m_spi_a = NULL;
SPIClass *m_spi_b = NULL;
// Bus Mutextes
std::mutex m_spi_a_mutex;
@@ -36,13 +36,13 @@ struct Devices
std::mutex m_i2c_mutex;
// Device Pointers
std::unique_ptr<AD5292> m_pot_a = nullptr;
std::unique_ptr<AD5292> m_pot_b = nullptr;
AD5292 *m_pot_a = NULL;
AD5292 *m_pot_b = NULL;
std::unique_ptr<ADS1256> m_adc_a = nullptr;
std::unique_ptr<ADS1256> m_adc_b = nullptr;
ADS1256 *m_adc_a = NULL;
ADS1256 *m_adc_b = NULL;
std::unique_ptr<ExternalIO> m_ext_io = nullptr;
ExternalIO *m_ext_io = NULL;
};
// Adc read channel wrapper to selet mux before reading
+1 -1
View File
@@ -16,7 +16,7 @@
#define CORE_0 0
#define CORE_1 1
#define RT_TASK_STACK 2048 // in words
#define RT_TASK_STACK 4096 // in words
#define RT_TASK_PRIORITY (configMAX_PRIORITIES - 5) // highest priority after wifi tasks
struct isrParams
+84 -68
View File
@@ -16,23 +16,28 @@
#include <ui.h>
#include <led.h>
// Defines to enable channel B
// #define CH_B_ENABLE
#define CH_A_ENABLE
#define CH_B_ENABLE
#define CH_A_RT_ENABLE
#define CH_B_RT_ENABLE
// #define I2C_ENABLE
// #define WEB_ENABLE
// Debug Defines
#define WIFI_SSID "AstroRotaxMonitor"
#define WIFI_PASSWORD "maledettirotax"
#define PSRAM_MAX 4096
#define QUEUE_MAX 256
#define PSRAM_MAX 1024
#define QUEUE_MAX 32
void setup()
{
Serial.begin(921600);
Serial.begin(115200);
delay(250);
Serial.setTimeout(5000);
// Setup Logger
LOG_ATTACH_SERIAL(Serial);
LOG_SET_LEVEL(DebugLogLevel::LVL_INFO);
LOG_SET_LEVEL(DebugLogLevel::LVL_DEBUG);
// Print Processor Info
LOG_DEBUG("ESP32 Chip:", ESP.getChipModel());
@@ -47,6 +52,7 @@ void setup()
LOG_DEBUG("ESP32 Sketch:", ESP.getFreeSketchSpace());
// Init Wifi station
#ifdef WEB_ENABLE
LOG_INFO("Initializing WiFi...");
WiFi.mode(WIFI_AP);
IPAddress local_IP(10, 11, 12, 1);
@@ -68,6 +74,7 @@ void setup()
vTaskDelay(pdMS_TO_TICKS(5000));
esp_restart();
}
#endif
// Initialize Interrupt pins on PICKUP detectors
initTriggerPinsInputs();
@@ -83,7 +90,7 @@ void loop()
led.setBrightness(0.025f);
led.setStatus(RGBled::LedStatus::INIT);
std::shared_ptr<Devices> dev = std::make_shared<Devices>();
Devices dev;
bool running = true;
std::mutex fs_mutex;
LITTLEFSGuard fsGuard;
@@ -91,17 +98,42 @@ void loop()
//////// INIT SPI INTERFACES ////////
bool spiA_ok = true;
bool spiB_ok = true;
//////// INIT SPI INTERFACES ////////
LOG_DEBUG("Init SPI Interfaces");
SPIClass SPI_A(FSPI);
#ifdef CH_A_ENABLE
LOG_DEBUG("Begin Init SPI_A");
SPIClass SPI_A(HSPI);
spiA_ok = SPI_A.begin(SPI_A_SCK, SPI_A_MISO, SPI_A_MOSI);
SPI_A.setDataMode(SPI_MODE1); // ADS1256 requires SPI mode 1
LOG_DEBUG("Init SPI A ok");
LOG_DEBUG("Init SPI_A -> OK");
delay(500);
LOG_DEBUG("Begin Init ADC_A");
ADS1256 ADC_A(ADC_A_DRDY, ADS1256::PIN_UNUSED, ADS1256::PIN_UNUSED, ADC_A_CS, 2.5, &SPI_A);
ADC_A.InitializeADC();
ADC_A.setPGA(PGA_1);
ADC_A.setDRATE(DRATE_7500SPS);
dev.m_adc_a = &ADC_A;
dev.m_spi_a = &SPI_A;
LOG_DEBUG("Init ADC_A -> OK");
delay(1000);
#endif
#ifdef CH_B_ENABLE
delay(50);
SPIClass SPI_B(HSPI);
LOG_DEBUG("Begin Init SPI_B");
SPIClass SPI_B(FSPI);
spiB_ok = SPI_B.begin(SPI_B_SCK, SPI_B_MISO, SPI_B_MOSI);
SPI_B.setDataMode(SPI_MODE1); // ADS1256 requires SPI mode 1
LOG_DEBUG("Init SPI B ok");
LOG_DEBUG("Init SPI_B -> OK");
delay(500);
LOG_DEBUG("Begin Init ADC_B");
ADS1256 ADC_B(ADC_B_DRDY, ADS1256::PIN_UNUSED, ADS1256::PIN_UNUSED, ADC_B_CS, 2.5, &SPI_B);
ADC_B.InitializeADC();
ADC_B.setPGA(PGA_1);
ADC_B.setDRATE(DRATE_7500SPS);
dev.m_adc_b = &ADC_B;
dev.m_spi_b = &SPI_B;
LOG_DEBUG("Init ADC_B -> OK");
delay(1000);
#endif
if (!spiA_ok || !spiB_ok)
@@ -111,50 +143,11 @@ void loop()
vTaskDelay(pdMS_TO_TICKS(5000));
esp_restart();
}
dev->m_spi_a.reset(&SPI_A);
#ifdef CH_B_ENABLE
dev->m_spi_b.reset(&SPI_B);
#endif
// Init ADCs
dev->m_adc_a = std::make_unique<ADS1256>(ADC_A_DRDY, ADS1256::PIN_UNUSED, ADS1256::PIN_UNUSED, ADC_A_CS, 2.5, &SPI_A);
#ifdef CH_B_ENABLE
dev->m_adc_b = std::make_unique<ADS1256>(ADC_B_DRDY, ADS1256::PIN_UNUSED, ADS1256::PIN_UNUSED, ADC_B_CS, 2.5, &SPI_B);
#endif
// Configure ADCs
dev->m_adc_a->InitializeADC();
dev->m_adc_a->setPGA(PGA_1);
// dev->m_adc_a->setDRATE(DRATE_15000SPS);
#ifdef CH_B_ENABLE
dev->m_adc_b->InitializeADC();
dev->m_adc_b->setPGA(PGA_1);
dev->m_adc_b->setDRATE(DRATE_30000SPS);
#endif
LOG_DEBUG("Init SPI OK");
uint8_t chs[8] = {
SING_0, SING_1, SING_2, SING_3, SING_4, SING_5, SING_6, SING_7
};
float res[8];
while (Serial.read() != 's') // The conversion is stopped by a character received from the serial port
{
clearScreen();
auto start = esp_timer_get_time();
for (int i = 0; i < 8; i++){
// dev->m_adc_a->setMUX(chs[i]);
res[i] = dev->m_adc_a->convertToVoltage(dev->m_adc_a->cycleSingle());
}
auto stop = esp_timer_get_time();
for (int j = 0; j < 8; j++){
Serial.printf("ADC_A SING_%d: %5.4f\n",j, res[j]);
}
Serial.printf("ADC Time: %u us\n", stop-start);
delay(100);
}
dev->m_adc_a->stopConversion();
LOG_DEBUG("Init SPI -> OK");
//////// INIT I2C INTERFACES ////////
#ifdef I2C_ENABLE
LOG_DEBUG("Init I2C Interfaces");
bool i2c_ok = true;
i2c_ok = Wire.begin(SDA, SCL, 100000);
@@ -165,11 +158,15 @@ void loop()
vTaskDelay(pdMS_TO_TICKS(5000));
esp_restart();
}
LOG_DEBUG("Init I2c ok");
Serial.readStringUntil('\n');
// Init IO Expanders
// dev->m_ext_io = std::make_unique<ExternalIO>(Wire, dev->m_i2c_mutex, EXPANDER_ALL_INTERRUPT);
dev->m_ext_io = std::make_unique<ExternalIO>(Wire, dev->m_i2c_mutex, EXPANDER_ALL_INTERRUPT);
#endif
//////// INIT REALTIME TASKS PARAMETERS ////////
#ifdef CH_A_RT_ENABLE
const rtIgnitionTask::rtTaskParams taskA_params{
.rt_running = true,
.name = "rtIgnTask_A",
@@ -199,8 +196,9 @@ void loop()
.relay_out_34 = RELAY_OUT_A34,
},
.rt_queue = nullptr,
.dev = dev};
.dev = &dev};
#endif
#ifdef CH_B_RT_ENABLE
const rtIgnitionTask::rtTaskParams taskB_params{
.rt_running = true,
.name = "rtIgnTask_B",
@@ -230,16 +228,30 @@ void loop()
.relay_out_34 = RELAY_OUT_B34,
},
.rt_queue = nullptr,
.dev = dev};
.dev = &dev};
#endif
//////// SPAWN REALTIME TASKS ////////
auto task_A = rtIgnitionTask(taskA_params, PSRAM_MAX, QUEUE_MAX, CORE_0, fs_mutex);
delay(50);
bool tasK_A_rt = true;
bool task_B_rt = true;
BaseType_t ignA_task_success = pdPASS;
BaseType_t ignB_task_success = pdPASS;
#ifdef CH_A_RT_ENABLE
auto task_A = rtIgnitionTask(taskA_params, PSRAM_MAX, QUEUE_MAX, CORE_1, fs_mutex);
ignA_task_success = task_A.getStatus() == rtIgnitionTask::OK ? pdPASS : pdFAIL;
//tasK_A_rt = task_A.start();
delay(1000);
#endif
#ifdef CH_B_RT_ENABLE
auto task_B = rtIgnitionTask(taskB_params, PSRAM_MAX, QUEUE_MAX, CORE_1, fs_mutex);
ignB_task_success = task_B.getStatus() == rtIgnitionTask::OK ? pdPASS : pdFAIL;
//task_B_rt = task_B.start();
delay(1000);
#endif
// Ignition A on Core 0
auto ignA_task_success = task_A.getStatus() == rtIgnitionTask::OK ? pdPASS : pdFAIL;
auto ignB_task_success = task_B.getStatus() == rtIgnitionTask::OK ? pdPASS : pdFAIL;
if (ignA_task_success != pdPASS || ignB_task_success != pdPASS)
{
LOG_ERROR("Unable to initialize ISR task");
@@ -247,10 +259,6 @@ void loop()
vTaskDelay(pdMS_TO_TICKS(5000));
esp_restart();
}
const bool tasK_A_rt = task_A.start();
delay(50);
const bool task_B_rt = task_B.start();
if (tasK_A_rt != true || task_B_rt != true)
{
led.setStatus(RGBled::LedStatus::ERROR);
@@ -263,18 +271,23 @@ void loop()
}
//////// SPAWN WEBSERVER and WEBSOCKET ////////
AstroWebServer webPage(80, LittleFS);
ArduinoJson::JsonDocument json_data;
bool data_a, data_b;
bool data_a = false, data_b = false;
#ifdef WEB_ENABLE
AstroWebServer webPage(80, LittleFS);
delay(1000);
task_A.onMessage([&webPage, &json_data, &data_a](ignitionBoxStatusFiltered sts)
{
json_data["box_a"] = sts.toJson();
data_a = true; });
#ifdef CH_B_RT_ENABLE
task_B.onMessage([&webPage, &json_data, &data_b](ignitionBoxStatusFiltered sts)
{
json_data["box_b"] = sts.toJson();
data_b = true; });
#endif
#endif
// task_A.enableSave(true, "ignitionA_test.csv");
// task_B.enableSave(true, "ignitionB_test.csv");
@@ -285,12 +298,14 @@ void loop()
while (running)
{
uint32_t this_loop = millis();
if (this_loop - monitor_loop > 2000)
if (this_loop - monitor_loop > 5000)
{
clearScreen();
printRunningTasksMod(Serial);
monitor_loop = millis();
}
vTaskDelay(pdMS_TO_TICKS(10));
#ifdef WEB_ENABLE
if ((data_a && data_b) || (this_loop - data_loop > 500))
{
webPage.sendWsData(json_data.as<String>());
@@ -298,6 +313,7 @@ void loop()
data_a = data_b = false;
data_loop = millis();
}
#endif
} //////////////// INNER LOOP /////////////////////
} ////////////////////// MAIN LOOP //////////////////////
+37 -26
View File
@@ -16,9 +16,16 @@ void spark_timeout_callback(void *arg)
void rtIgnitionTask::rtIgnitionTask_manager(void *pvParameters)
{
rtIgnitionTask *cls = (rtIgnitionTask *)pvParameters;
auto last_loop = millis();
uint32_t count(0);
while (cls->m_running)
{
cls->run();
// if (millis() - last_loop > 2000) {
// LOG_DEBUG("TASK [", cls->m_name.c_str(), "] Alive -", count++);
// last_loop = millis();
// }
vTaskDelay(pdMS_TO_TICKS(1));
}
}
@@ -38,10 +45,12 @@ void rtIgnitionTask::rtIgnitionTask_realtime(void *pvParameters)
const rtTaskInterruptParams rt_int = params->rt_int; // copy to avoid external override
const rtTaskIOParams rt_rst = params->rt_io; // copy to avoid external override
QueueHandle_t rt_queue = params->rt_queue;
Devices *dev = params->dev.get();
ADS1256 *adc = params->name == "rtIgnTask_A" ? dev->m_adc_a.get() : dev->m_adc_b.get();
std::mutex &spi_mutex = params->name == "rtIgnTask_A" ? dev->m_spi_a_mutex : dev->m_spi_b_mutex;
ExternalIO *io = dev->m_ext_io.get();
Devices *dev = params->dev;
ExternalIO *io = dev->m_ext_io;
// ADS1256 *adc = params->name == "rtIgnTask_A" ? dev->m_adc_a : dev->m_adc_b;
ADS1256 *adc = NULL;
// std::mutex &spi_mutex = params->name == "rtIgnTask_A" ? dev->m_spi_a_mutex : dev->m_spi_b_mutex;
std::mutex spi_mutex;
TaskStatus_t rt_task_info;
vTaskGetInfo(NULL, &rt_task_info, pdFALSE, eInvalid);
@@ -76,10 +85,6 @@ void rtIgnitionTask::rtIgnitionTask_realtime(void *pvParameters)
.ign_stat = &ign_box_sts,
.rt_handle_ptr = rt_task_info.xHandle};
LOG_DEBUG("rtTask HDL Params OK, HDL* [", (uint32_t)rt_task_info.xHandle, "]");
LOG_DEBUG("rtTask ISR Params OK, ISR* [", (uint32_t)rt_int.isr_ptr, "]");
LOG_DEBUG("rtTask QUE Params OK, QUE* [", (uint32_t)rt_queue, "]");
// Create esp_timer for microsecond precision timeout
esp_timer_handle_t timeout_timer;
esp_timer_create_args_t timer_args = {
@@ -87,7 +92,11 @@ void rtIgnitionTask::rtIgnitionTask_realtime(void *pvParameters)
.arg = (void *)rt_task_info.xHandle,
.dispatch_method = ESP_TIMER_TASK,
.name = "spark_timeout"};
esp_timer_create(&timer_args, &timeout_timer);
if (esp_timer_create(&timer_args, &timeout_timer) != ESP_OK)
{
LOG_INFO("rtTask [", params->name.c_str(), "] Fail to allocate timeoutTimer");
vTaskDelete(NULL);
}
// Attach Pin Interrupts
attachInterruptArg(digitalPinToInterrupt(rt_int.trig_pin_12p), rt_int.isr_ptr, (void *)&isr_params_t12p, RISING);
@@ -238,15 +247,16 @@ void rtIgnitionTask::rtIgnitionTask_realtime(void *pvParameters)
std::lock_guard<std::mutex> lock(spi_mutex);
uint32_t start_adc_read = esp_timer_get_time();
// from peak detector circuits
ign_box_sts.coils12.peak_p_in = adcReadChannel(adc, ADC_CH_PEAK_12P_IN);
ign_box_sts.coils12.peak_n_in = adcReadChannel(adc, ADC_CH_PEAK_12N_IN);
ign_box_sts.coils34.peak_p_in = adcReadChannel(adc, ADC_CH_PEAK_34P_IN);
ign_box_sts.coils34.peak_n_in = adcReadChannel(adc, ADC_CH_PEAK_34N_IN);
ign_box_sts.coils12.peak_p_out = adcReadChannel(adc, ADC_CH_PEAK_12P_OUT);
ign_box_sts.coils12.peak_n_out = adcReadChannel(adc, ADC_CH_PEAK_12N_OUT);
ign_box_sts.coils34.peak_p_out = adcReadChannel(adc, ADC_CH_PEAK_34P_OUT);
ign_box_sts.coils34.peak_n_out = adcReadChannel(adc, ADC_CH_PEAK_34N_OUT);
ign_box_sts.coils12.peak_p_in = adc->convertToVoltage(adc->cycleSingle());
ign_box_sts.coils12.peak_n_in = adc->convertToVoltage(adc->cycleSingle());
ign_box_sts.coils34.peak_p_in = adc->convertToVoltage(adc->cycleSingle());
ign_box_sts.coils34.peak_n_in = adc->convertToVoltage(adc->cycleSingle());
ign_box_sts.coils12.peak_p_out = adc->convertToVoltage(adc->cycleSingle());
ign_box_sts.coils12.peak_n_out = adc->convertToVoltage(adc->cycleSingle());
ign_box_sts.coils34.peak_p_out = adc->convertToVoltage(adc->cycleSingle());
ign_box_sts.coils34.peak_n_out = adc->convertToVoltage(adc->cycleSingle());
ign_box_sts.adc_read_time = (int32_t)(esp_timer_get_time() - start_adc_read);
adc->stopConversion();
}
else // simulate adc read timig
vTaskDelay(pdMS_TO_TICKS(c_adc_time));
@@ -299,6 +309,7 @@ void rtIgnitionTask::rtIgnitionTask_realtime(void *pvParameters)
///////////// CLASS MEMBER DEFINITIONS /////////////
rtIgnitionTask::rtIgnitionTask(const rtTaskParams params, const uint32_t history_size, const uint32_t queue_size, const uint8_t core, std::mutex &fs_mutex, fs::FS &filesystem) : m_params(params), m_filesystem(filesystem), m_fs_mutex(fs_mutex), m_core(core), m_max_history(history_size)
{
LOG_WARN("Starting Manager for [", m_params.name.c_str(), "]");
// create queue buffers
m_queue = xQueueCreate(queue_size, sizeof(ignitionBoxStatus));
if (!m_queue)
@@ -317,12 +328,12 @@ rtIgnitionTask::rtIgnitionTask(const rtTaskParams params, const uint32_t history
m_active_history = std::unique_ptr<PSHistory>(&m_history_0);
m_save_history = std::unique_ptr<PSHistory>(&m_history_1);
LOG_WARN("Starting Manager for [", m_params.name.c_str(), "]");
m_name = (std::string("man_") + m_params.name).c_str();
// auto task_success = pdPASS;
auto task_success = xTaskCreatePinnedToCore(
rtIgnitionTask_manager,
(std::string("man_") + m_params.name).c_str(),
8192,
m_name.c_str(),
RT_TASK_STACK,
(void *)this,
m_params.rt_priority >> 2,
&m_manager_handle,
@@ -361,14 +372,15 @@ void rtIgnitionTask::run()
m_last_data = millis();
m_manager_status = rtTaskStatus::RUNNING;
// if history buffer is full swap buffers and if enabled save history buffer
if (m_counter_status >= m_active_history->size())
if (m_counter_status >= m_max_history)
{
LOG_DEBUG("Save for Buffer Full: ", m_counter_status);
m_counter_status = 0;
m_partial_save = false; // reset partial save flag on new data cycle
std::swap(m_active_history, m_save_history);
if (m_enable_save)
saveHistory(*m_save_history, m_history_path); // directly call the save task function to save without delay
// saveHistory(m_save_history, m_history_path); // directly call the save task function to save without delay
LOG_INFO("Save History");
}
// update filtered data
@@ -390,15 +402,14 @@ void rtIgnitionTask::run()
if (m_counter_status > 0 && !m_partial_save)
{
LOG_DEBUG("Save Partial: ", m_counter_status);
m_active_history->resize(m_counter_status);
saveHistory(*m_active_history, m_history_path);
m_active_history->resize(m_max_history);
// m_active_history->resize(m_counter_status);
// saveHistory(m_active_history, m_history_path);
// m_active_history->resize(m_max_history);
m_counter_status = 0;
m_partial_save = true;
}
m_manager_status = rtTaskStatus::IDLE;
}
delay(5); // yeld to another task
}
}
+3 -1
View File
@@ -41,6 +41,7 @@ static const std::map<const uint32_t, const char *> names = {
class rtIgnitionTask
{
using PSHistory = PSRAMVector<ignitionBoxStatus>;
// using PSHistory = std::vector<ignitionBoxStatus>;
public:
// RT task Interrupt parameters
@@ -84,7 +85,7 @@ public:
const rtTaskInterruptParams rt_int; // interrupt pins to attach
const rtTaskIOParams rt_io; // reset ping for peak detectors
QueueHandle_t rt_queue; // queue for task io
const std::shared_ptr<Devices> dev;
Devices *dev;
};
enum rtTaskStatus
@@ -124,6 +125,7 @@ private: // static functions for FreeRTOS
private:
bool m_running = true;
rtTaskStatus m_manager_status = INIT;
std::string m_name;
rtTaskParams m_params;
const uint8_t m_core;
+13 -17
View File
@@ -7,7 +7,7 @@
#include "esp_heap_caps.h"
#include "esp_system.h"
#include "esp_spi_flash.h"
#include "spi_flash_mmap.h"
#include "esp_partition.h"
#include "LittleFS.h"
@@ -49,23 +49,27 @@ void printBar(Print &printer, const char *label, size_t used, size_t total, cons
{
float perc = total > 0 ? ((float)used / total) : 0;
int filled = perc * BAR_WIDTH;
char str[256] = {0};
uint16_t k(0);
printer.printf("%s%-12s [" COLOR_RESET, color, label);
k += sprintf(str, "%s%-12s [" COLOR_RESET, color, label);
for (int i = 0; i < BAR_WIDTH; i++)
{
if (i < filled)
printer.printf("%s#%s", color, COLOR_RESET);
k += sprintf(&str[k], "%s#%s", color, COLOR_RESET);
else
printer.printf("-");
k += sprintf(&str[k], "-");
}
printer.printf("] %s%6.2f%%%s (%5.3f/%5.3f)MB\n",
sprintf(&str[k], "] %s%6.2f%%%s (%5.3f/%5.3f)MB\n",
color,
perc * 100.0,
COLOR_RESET,
(used / 1024.0f / 1024.0f),
(total / 1024.0f / 1024.0f));
printer.println(str);
}
void printRunningTasksMod(Print &printer, std::function<bool(const TaskStatus_t &a, const TaskStatus_t &b)> orderBy)
@@ -95,6 +99,7 @@ void printRunningTasksMod(Print &printer, std::function<bool(const TaskStatus_t
// Compute system total runtime
ulCurrentRunTime = ulTotalRunTime - ulLastRunTime;
ulCurrentRunTime = ulCurrentRunTime > 0 ? ulCurrentRunTime : 1;
ulLastRunTime = ulTotalRunTime;
// PRINT MEMORY INFO
@@ -134,17 +139,6 @@ void printRunningTasksMod(Print &printer, std::function<bool(const TaskStatus_t
ESP_PARTITION_SUBTYPE_APP_FACTORY,
NULL);
if (app_partition)
{
size_t totalAPP = app_partition->size; // dimensione reale partizione
size_t sketchSize = ESP.getSketchSize();
printBar(printer, "FLASH APP", sketchSize, totalAPP, COLOR_CYAN);
}
else
{
printer.printf(COLOR_YELLOW "%-12s [NOT FOUND]\n" COLOR_RESET, "FLASH APP");
}
// ===== LITTLEFS (corretto con partition table) =====
const esp_partition_t *fs_partition =
esp_partition_find_first(ESP_PARTITION_TYPE_DATA,
@@ -164,7 +158,9 @@ void printRunningTasksMod(Print &printer, std::function<bool(const TaskStatus_t
// ===== MIN HEAP =====
size_t minHeap = esp_get_minimum_free_heap_size();
printer.printf("%s\nMin Heap Ever:%s %u KB\n\n", COLOR_RED, COLOR_RESET, minHeap / 1024);
printer.printf("%s\nMin Heap Ever:%s %u KB\n", COLOR_RED, COLOR_RESET, minHeap / 1024);
size_t max_block = heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM);
printer.printf("%s\nMax PSRAM Block:%s %u KB\n\n", COLOR_RED, COLOR_RESET, max_block / 1024);
// Print Runtime Information
printer.printf("Tasks: %u, Runtime: %lus, Period: %luus\r\n", uxArraySize, ulTotalRunTime / 1000000, ulCurrentRunTime);