12 Commits

Author SHA1 Message Date
Obbart 8171cab9cb adc ok 2026-04-14 14:16:11 +02:00
Emanuele Trabattoni 899c8cffbc io expander class ok , adc not working 2026-04-14 11:02:33 +02:00
Emanuele Trabattoni 782aa95ee6 Merge branch 'task-refactor' 2026-04-13 10:28:24 +02:00
Emanuele Trabattoni 212b37c95f updated and fixed charts 2026-04-13 10:26:55 +02:00
Emanuele Trabattoni f8c3c69e80 fix graph 2026-04-12 14:42:40 +02:00
Emanuele Trabattoni 7da58c8a49 Set time from browser 2026-04-12 14:40:58 +02:00
Obbart a153402d28 webpage chats 2026-04-12 02:38:27 +02:00
Obbart 095aa59f36 task refactoring working, sometimes misses events, check priorities 2026-04-12 01:45:32 +02:00
Emanuele Trabattoni fdba6d5ad5 refactor continued, at least it compiles 2026-04-11 16:39:59 +02:00
Emanuele Trabattoni d1b96e932c task refactoring work in progress 2026-04-11 15:49:40 +02:00
Obbart 684c34e209 adding pins and task class 2026-04-11 12:27:19 +02:00
Obbart 37fa6a686f Merge branch 'datasave' 2026-04-11 11:40:20 +02:00
22 changed files with 1953 additions and 1083 deletions
File diff suppressed because one or more lines are too long
+29 -5
View File
@@ -13,11 +13,19 @@
<img src="logo_astro_dev.svg" alt="Astro Tecnologie" class="logo"> <img src="logo_astro_dev.svg" alt="Astro Tecnologie" class="logo">
</div> </div>
<div> <div>
<h1>Rotax Ignition Box Monitor</h1> <h1>Rotax Ignition Box Monitor</h1>
</div> </div>
</header> </header>
<!-- TAB BUTTONS -->
<div class="tabs">
<button class="tab-button active" onclick="openTab('tab1')">Monitor</button>
<button class="tab-button" onclick="openTab('tab2')">Grafico</button>
</div>
<!-- TAB 1 (contenuto attuale) -->
<div id="tab1" class="tab-content active">
<div id="loadingIndicator" class="loading-indicator"> <div id="loadingIndicator" class="loading-indicator">
<span class="spinner"></span> Waiting for data... <span class="spinner"></span> Waiting for data...
</div> </div>
@@ -173,16 +181,32 @@
</table> </table>
</div> </div>
</div> </div>
</div> <!-- END TAB1 -->
<div class="upload-section"> <!-- TAB 2 (grafico) -->
<div id="tab2" class="tab-content">
<div class="chart-container">
<h3>Box A</h3>
<canvas id="chartA" height="100"></canvas>
</div>
<div class="chart-container">
<h3>Box B</h3>
<canvas id="chartB" height="100"></canvas>
</div>
</div>
</body>
<div class="upload-section">
<h3>Upload file to Flash</h3> <h3>Upload file to Flash</h3>
<p>Select a file and upload it to Flash.</p> <p>Select a file and upload it to Flash.</p>
<input type="file" id="littlefsFile"> <input type="file" id="littlefsFile">
<button onclick="uploadLittleFS()">Upload</button> <button onclick="uploadLittleFS()">Upload</button>
<div id="uploadStatus" class="upload-status">No file uploaded yet.</div> <div id="uploadStatus" class="upload-status">No file uploaded yet.</div>
</div> </div>
<script src="script.js"></script> <script src="chart.js"></script>
</body> <script src="script.js"></script>
</html> </html>
+128
View File
@@ -3,6 +3,26 @@ let lastMessageTimestamp = 0;
const IDLE_THRESHOLD_MS = 1000; const IDLE_THRESHOLD_MS = 1000;
const loadingIndicator = document.getElementById("loadingIndicator"); const loadingIndicator = document.getElementById("loadingIndicator");
let chartA, chartB;
let dataA = {
labels: [],
datasets: [
{ label: "RPM", data: [] },
{ label: "Coils12 Delay", data: [] },
{ label: "Coils34 Delay", data: [] }
]
};
let dataB = {
labels: [],
datasets: [
{ label: "RPM", data: [] },
{ label: "Coils12 Delay", data: [] },
{ label: "Coils34 Delay", data: [] }
]
};
function setLoadingIndicator(visible) { function setLoadingIndicator(visible) {
if (!loadingIndicator) { if (!loadingIndicator) {
return; return;
@@ -25,6 +45,11 @@ function connectWS() {
console.log("WebSocket connesso"); console.log("WebSocket connesso");
lastMessageTimestamp = Date.now(); lastMessageTimestamp = Date.now();
setLoadingIndicator(false); setLoadingIndicator(false);
ws.send(JSON.stringify({
cmd: "setTime",
time: Math.floor(Date.now() / 1000)
}));
}; };
ws.onclose = () => { ws.onclose = () => {
@@ -46,6 +71,8 @@ function connectWS() {
lastMessageTimestamp = Date.now(); lastMessageTimestamp = Date.now();
setLoadingIndicator(false); setLoadingIndicator(false);
updateCharts(data)
// Update Box_A // Update Box_A
if (data.box_a) { if (data.box_a) {
const boxA = data.box_a; const boxA = data.box_a;
@@ -118,6 +145,51 @@ function connectWS() {
}; };
} }
function updateCharts(data) {
const t = new Date().toLocaleTimeString();
// ===== BOX A =====
dataA.labels.push(t);
if (data.box_a) {
dataA.datasets[0].data.push(data.box_a.eng_rpm / 10);
dataA.datasets[1].data.push(data.box_a.coils12.spark_delay);
dataA.datasets[2].data.push(data.box_a.coils34.spark_delay);
} else {
dataA.datasets[0].data.push(undefined);
dataA.datasets[1].data.push(undefined);
dataA.datasets[2].data.push(undefined);
}
// ===== BOX B =====
dataB.labels.push(t);
if (data.box_b) {
dataB.datasets[0].data.push(data.box_b.eng_rpm / 10);
dataB.datasets[1].data.push(data.box_b.coils12.spark_delay);
dataB.datasets[2].data.push(data.box_b.coils34.spark_delay);
} else {
dataB.datasets[0].data.push(undefined);
dataB.datasets[1].data.push(undefined);
dataB.datasets[2].data.push(undefined);
}
// limite buffer
const maxPoints = 100;
if (dataA.labels.length > maxPoints) {
dataA.labels.shift();
dataA.datasets.forEach(d => d.data.shift());
}
if (dataB.labels.length > maxPoints) {
dataB.labels.shift();
dataB.datasets.forEach(d => d.data.shift());
}
chartA.update();
chartB.update();
}
function start() { function start() {
fetch("/start"); fetch("/start");
} }
@@ -160,5 +232,61 @@ function uploadLittleFS() {
}); });
} }
function openTab(tabId) {
document.querySelectorAll('.tab-content').forEach(tab => {
tab.classList.remove('active');
});
document.querySelectorAll('.tab-button').forEach(btn => {
btn.classList.remove('active');
});
document.getElementById(tabId).classList.add('active');
event.target.classList.add('active');
}
function initCharts() {
const ctxA = document.getElementById('chartA').getContext('2d');
const ctxB = document.getElementById('chartB').getContext('2d');
chartA = new Chart(ctxA, {
type: 'line',
data: dataA,
options: {
animation: false,
responsive: true,
scales: {
x: {
display: true
},
y: {
beginAtZero: true
}
}
}
});
chartB = new Chart(ctxB, {
type: 'line',
data: dataB,
options: {
animation: false,
responsive: true,
scales: {
x: {
display: true
},
y: {
beginAtZero: true
}
}
}
});
}
window.onload = () => {
initCharts();
};
setInterval(updateLoadingState, 200); setInterval(updateLoadingState, 200);
connectWS(); connectWS();
+38
View File
@@ -219,3 +219,41 @@ button:hover {
span { span {
color: var(--text-dark); color: var(--text-dark);
} }
/* TABS */
.tabs {
display: flex;
justify-content: center;
margin: 20px;
}
.tab-button {
padding: 10px 20px;
margin: 0 5px;
border: none;
cursor: pointer;
background: var(--border-color);
border-radius: 4px;
}
.tab-button.active {
background: var(--primary-blue);
color: white;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
.chart-container {
max-width: 1000px;
margin: 20px auto;
background: white;
padding: 20px;
border-radius: 6px;
box-shadow: 0 1px 3px rgba(0,0,0,0.08);
}
+262 -232
View File
@@ -1,4 +1,4 @@
//ADS1256 cpp file // ADS1256 cpp file
/* /*
Name: ADS1256.cpp Name: ADS1256.cpp
Created: 2022/07/14 Created: 2022/07/14
@@ -15,350 +15,367 @@
#include "ADS1256.h" #include "ADS1256.h"
#include "SPI.h" #include "SPI.h"
#include "DebugLog.h"
#define convertSigned24BitToLong(value) ((value) & (1l << 23) ? (value) - 0x1000000 : value) #define convertSigned24BitToLong(value) ((value) & (1l << 23) ? (value) - 0x1000000 : value)
//Constructor // 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), 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) _DRDY_pin(DRDY_pin), _RESET_pin(RESET_pin), _SYNC_pin(SYNC_pin), _CS_pin(CS_pin), _VREF(VREF), _PGA(0)
{ {
pinMode(_DRDY_pin, INPUT); pinMode(_DRDY_pin, INPUT);
if(RESET_pin != PIN_UNUSED) if (RESET_pin != PIN_UNUSED)
{ {
pinMode(_RESET_pin, OUTPUT); pinMode(_RESET_pin, OUTPUT);
} }
if(SYNC_pin != PIN_UNUSED) if (SYNC_pin != PIN_UNUSED)
{ {
pinMode(_SYNC_pin, OUTPUT); pinMode(_SYNC_pin, OUTPUT);
} }
if(CS_pin != PIN_UNUSED) if (CS_pin != PIN_UNUSED)
{ {
pinMode(_CS_pin, OUTPUT); pinMode(_CS_pin, OUTPUT);
} }
LOG_DEBUG("ADC Class Init OK");
updateConversionParameter(); updateConversionParameter();
} }
//Initialization // Initialization
void ADS1256::InitializeADC() void ADS1256::InitializeADC()
{ {
//Chip select LOW // Chip select LOW
CS_LOW(); CS_LOW();
//We do a manual chip reset on the ADS1256 - Datasheet Page 27/ RESET // We do a manual chip reset on the ADS1256 - Datasheet Page 27/ RESET
if(_RESET_pin != PIN_UNUSED) if (_RESET_pin != PIN_UNUSED)
{ {
digitalWrite(_RESET_pin, LOW); digitalWrite(_RESET_pin, LOW);
delay(200); delay(200);
digitalWrite(_RESET_pin, HIGH); //RESET is set to high digitalWrite(_RESET_pin, HIGH); // RESET is set to high
delay(1000); delay(1000);
} }
//Sync pin is also treated if it is defined // Sync pin is also treated if it is defined
if(_SYNC_pin != PIN_UNUSED) if (_SYNC_pin != PIN_UNUSED)
{ {
digitalWrite(_SYNC_pin, HIGH); //RESET is set to high digitalWrite(_SYNC_pin, HIGH); // RESET is set to high
} }
#ifndef ADS1256_SPI_ALREADY_STARTED //Guard macro to allow external initialization of the SPI #ifndef ADS1256_SPI_ALREADY_STARTED // Guard macro to allow external initialization of the SPI
_spi->begin(); //_spi->begin();
#endif #endif
//Applying arbitrary default values to speed up the starting procedure if the user just want to get quick readouts // 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 // We both pass values to the variables and then send those values to the corresponding registers
delay(200); delay(200);
_STATUS = 0b00110110; //BUFEN and ACAL enabled, Order is MSB, rest is read only _STATUS = 0b00110110; // BUFEN and ACAL enabled, Order is MSB, rest is read only
writeRegister(STATUS_REG, _STATUS); writeRegister(STATUS_REG, _STATUS);
delay(200); delay(200);
_MUX = 0b00000001; //MUX AIN0+AIN1 _MUX = 0b00000001; // MUX AIN0+AIN1
writeRegister(MUX_REG, _MUX); writeRegister(MUX_REG, _MUX);
delay(200); delay(200);
_ADCON = 0b00000000; //ADCON - CLK: OFF, SDCS: OFF, PGA = 0 (+/- 5 V) _ADCON = 0b00000000; // ADCON - CLK: OFF, SDCS: OFF, PGA = 0 (+/- 5 V)
writeRegister(ADCON_REG, _ADCON); writeRegister(ADCON_REG, _ADCON);
delay(200); delay(200);
updateConversionParameter(); updateConversionParameter();
_DRATE = 0b10000010; //100SPS _DRATE = 0b10000010; // 100SPS
writeRegister(DRATE_REG, _DRATE); writeRegister(DRATE_REG, _DRATE);
delay(200); delay(200);
sendDirectCommand(0b11110000); //Offset and self-gain calibration sendDirectCommand(0b11110000); // Offset and self-gain calibration
delay(200); delay(200);
_isAcquisitionRunning = false; //MCU will be waiting to start a continuous acquisition _isAcquisitionRunning = false; // MCU will be waiting to start a continuous acquisition
} }
void ADS1256::waitForLowDRDY() void ADS1256::waitForLowDRDY()
{ {
while (digitalRead(_DRDY_pin) == HIGH) {} while (digitalRead(_DRDY_pin) == HIGH)
{
}
} }
void ADS1256::waitForHighDRDY() void ADS1256::waitForHighDRDY()
{ {
#if F_CPU >= 48000000 //Fast MCUs need this protection to wait until DRDY goes high after a conversion #if F_CPU >= 48000000 // Fast MCUs need this protection to wait until DRDY goes high after a conversion
while (digitalRead(_DRDY_pin) == LOW) {} while (digitalRead(_DRDY_pin) == LOW)
{
}
#endif #endif
} }
void ADS1256::stopConversion() //Sending SDATAC to stop the continuous conversion void ADS1256::stopConversion() // Sending SDATAC to stop the continuous conversion
{ {
waitForLowDRDY(); //SDATAC should be called after DRDY goes LOW (p35. Figure 33) waitForLowDRDY(); // SDATAC should be called after DRDY goes LOW (p35. Figure 33)
_spi->transfer(0b00001111); //Send SDATAC to the ADC _spi->transfer(0b00001111); // Send SDATAC to the ADC
CS_HIGH(); //We finished the command sequence, so we switch it back to HIGH CS_HIGH(); // We finished the command sequence, so we switch it back to HIGH
_spi->endTransaction(); _spi->endTransaction();
_isAcquisitionRunning = false; //Reset to false, so the MCU will be able to start a new conversion _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) void ADS1256::setDRATE(uint8_t drate) // Setting DRATE (sampling frequency)
{ {
writeRegister(DRATE_REG, drate); writeRegister(DRATE_REG, drate);
_DRATE = drate; _DRATE = drate;
delayMicroseconds(500); delayMicroseconds(500);
} }
void ADS1256::setMUX(uint8_t mux) //Setting MUX (input channel) void ADS1256::setMUX(uint8_t mux) // Setting MUX (input channel)
{ {
writeRegister(MUX_REG, mux); writeRegister(MUX_REG, mux);
_MUX = mux; _MUX = mux;
//delayMicroseconds(500); // delayMicroseconds(500);
} }
void ADS1256::setPGA(uint8_t pga) //Setting PGA (input voltage range) void ADS1256::setPGA(uint8_t pga) // Setting PGA (input voltage range)
{ {
_PGA = pga; _PGA = pga;
_ADCON = readRegister(ADCON_REG); //Read the most recent value of the register _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 _ADCON = (_ADCON & 0b11111000) | (_PGA & 0b00000111); // Clearing and then setting bits 2-0 based on pga
writeRegister(ADCON_REG, _ADCON); writeRegister(ADCON_REG, _ADCON);
delayMicroseconds(1000); //Delay to allow the PGA to settle after changing its value delayMicroseconds(1000); // Delay to allow the PGA to settle after changing its value
updateConversionParameter(); //Update the multiplier according top the new PGA value updateConversionParameter(); // Update the multiplier according top the new PGA value
} }
uint8_t ADS1256::getPGA() //Reading PGA from the ADCON register uint8_t ADS1256::getPGA() // Reading PGA from the ADCON register
{ {
uint8_t pgaValue = readRegister(ADCON_REG) & 0b00000111; uint8_t pgaValue = readRegister(ADCON_REG) & 0b00000111;
//Reading the ADCON_REG and keeping the first three bits. // Reading the ADCON_REG and keeping the first three bits.
return(pgaValue); return (pgaValue);
} }
void ADS1256::setCLKOUT(uint8_t clkout) //Setting CLKOUT void ADS1256::setCLKOUT(uint8_t clkout) // Setting CLKOUT
{ {
_ADCON = readRegister(ADCON_REG); //Read the most recent value of the register _ADCON = readRegister(ADCON_REG); // Read the most recent value of the register
//Values: 0, 1, 2, 3 // Values: 0, 1, 2, 3
if(clkout == 0) if (clkout == 0)
{ {
//00 // 00
bitWrite(_ADCON, 6, 0); bitWrite(_ADCON, 6, 0);
bitWrite(_ADCON, 5, 0); bitWrite(_ADCON, 5, 0);
} }
else if(clkout == 1) else if (clkout == 1)
{ {
//01 (default) // 01 (default)
bitWrite(_ADCON, 6, 0); bitWrite(_ADCON, 6, 0);
bitWrite(_ADCON, 5, 1); bitWrite(_ADCON, 5, 1);
} }
else if(clkout == 2) else if (clkout == 2)
{ {
//10 // 10
bitWrite(_ADCON, 6, 1); bitWrite(_ADCON, 6, 1);
bitWrite(_ADCON, 5, 0); bitWrite(_ADCON, 5, 0);
} }
else if(clkout == 3) else if (clkout == 3)
{ {
//11 // 11
bitWrite(_ADCON, 6, 1); bitWrite(_ADCON, 6, 1);
bitWrite(_ADCON, 5, 1); bitWrite(_ADCON, 5, 1);
} }
else{} else
{
}
writeRegister(ADCON_REG, _ADCON); writeRegister(ADCON_REG, _ADCON);
delay(100); delay(100);
} }
void ADS1256::setSDCS(uint8_t sdcs) //Setting SDCS void ADS1256::setSDCS(uint8_t sdcs) // Setting SDCS
{ {
_ADCON = readRegister(ADCON_REG); //Read the most recent value of the register _ADCON = readRegister(ADCON_REG); // Read the most recent value of the register
//Values: 0, 1, 2, 3 // Values: 0, 1, 2, 3
if(sdcs == 0) if (sdcs == 0)
{ {
//00 (default) // 00 (default)
bitWrite(_ADCON, 4, 0); bitWrite(_ADCON, 4, 0);
bitWrite(_ADCON, 3, 0); bitWrite(_ADCON, 3, 0);
} }
else if(sdcs == 1) else if (sdcs == 1)
{ {
//01 // 01
bitWrite(_ADCON, 4, 0); bitWrite(_ADCON, 4, 0);
bitWrite(_ADCON, 3, 1); bitWrite(_ADCON, 3, 1);
} }
else if(sdcs == 2) else if (sdcs == 2)
{ {
//10 // 10
bitWrite(_ADCON, 4, 1); bitWrite(_ADCON, 4, 1);
bitWrite(_ADCON, 3, 0); bitWrite(_ADCON, 3, 0);
} }
else if(sdcs == 3) else if (sdcs == 3)
{ {
//11 // 11
bitWrite(_ADCON, 4, 1); bitWrite(_ADCON, 4, 1);
bitWrite(_ADCON, 3, 1); bitWrite(_ADCON, 3, 1);
} }
else{} else
{
}
writeRegister(ADCON_REG, _ADCON); writeRegister(ADCON_REG, _ADCON);
delay(100); delay(100);
} }
void ADS1256::setByteOrder(uint8_t byteOrder) //Setting byte order (MSB/LSB) void ADS1256::setByteOrder(uint8_t byteOrder) // Setting byte order (MSB/LSB)
{ {
_STATUS = readRegister(STATUS_REG); //Read the most recent value of the register _STATUS = readRegister(STATUS_REG); // Read the most recent value of the register
if(byteOrder == 0) if (byteOrder == 0)
{ {
//Byte order is MSB (default) // Byte order is MSB (default)
bitWrite(_STATUS, 3, 0); bitWrite(_STATUS, 3, 0);
//Set value of _STATUS at the third bit to 0 // Set value of _STATUS at the third bit to 0
} }
else if(byteOrder == 1) else if (byteOrder == 1)
{ {
//Byte order is LSB // Byte order is LSB
bitWrite(_STATUS, 3, 1); bitWrite(_STATUS, 3, 1);
//Set value of _STATUS at the third bit to 1 // Set value of _STATUS at the third bit to 1
}
else
{
} }
else{}
writeRegister(STATUS_REG, _STATUS); writeRegister(STATUS_REG, _STATUS);
delay(100); delay(100);
} }
uint8_t ADS1256::getByteOrder() //Getting byte order (MSB/LSB) uint8_t ADS1256::getByteOrder() // Getting byte order (MSB/LSB)
{ {
uint8_t statusValue = readRegister(STATUS_REG); //Read the whole STATUS register uint8_t statusValue = readRegister(STATUS_REG); // Read the whole STATUS register
return bitRead(statusValue, 3); return bitRead(statusValue, 3);
} }
void ADS1256::setAutoCal(uint8_t acal) //Setting ACAL (Automatic SYSCAL) void ADS1256::setAutoCal(uint8_t acal) // Setting ACAL (Automatic SYSCAL)
{ {
_STATUS = readRegister(STATUS_REG); //Read the most recent value of the register _STATUS = readRegister(STATUS_REG); // Read the most recent value of the register
if(acal == 0) if (acal == 0)
{ {
//Auto-calibration is disabled (default) // Auto-calibration is disabled (default)
bitWrite(_STATUS, 2, 0); bitWrite(_STATUS, 2, 0);
//_STATUS |= B00000000; //_STATUS |= B00000000;
} }
else if(acal == 1) else if (acal == 1)
{ {
//Auto-calibration is enabled // Auto-calibration is enabled
bitWrite(_STATUS, 2, 1); bitWrite(_STATUS, 2, 1);
//_STATUS |= B00000100; //_STATUS |= B00000100;
} }
else{} else
{
}
writeRegister(STATUS_REG, _STATUS); writeRegister(STATUS_REG, _STATUS);
delay(100); delay(100);
} }
uint8_t ADS1256::getAutoCal() //Getting ACAL (Automatic SYSCAL) uint8_t ADS1256::getAutoCal() // Getting ACAL (Automatic SYSCAL)
{ {
uint8_t statusValue = readRegister(STATUS_REG); //Read the whole STATUS register uint8_t statusValue = readRegister(STATUS_REG); // Read the whole STATUS register
return bitRead(statusValue, 2); return bitRead(statusValue, 2);
} }
void ADS1256::setBuffer(uint8_t bufen) //Setting input buffer (Input impedance) void ADS1256::setBuffer(uint8_t bufen) // Setting input buffer (Input impedance)
{ {
_STATUS = readRegister(STATUS_REG); //Read the most recent value of the register _STATUS = readRegister(STATUS_REG); // Read the most recent value of the register
if(bufen == 0) if (bufen == 0)
{ {
//Analog input buffer is disabled (default) // Analog input buffer is disabled (default)
//_STATUS |= B00000000; //_STATUS |= B00000000;
bitWrite(_STATUS, 1, 0); bitWrite(_STATUS, 1, 0);
} }
else if(bufen == 1) else if (bufen == 1)
{ {
//Analog input buffer is enabled (recommended) // Analog input buffer is enabled (recommended)
//_STATUS |= B00000010; //_STATUS |= B00000010;
bitWrite(_STATUS, 1, 1); bitWrite(_STATUS, 1, 1);
} }
else{} else
{
}
writeRegister(STATUS_REG, _STATUS); writeRegister(STATUS_REG, _STATUS);
delay(100); delay(100);
} }
uint8_t ADS1256::getBuffer() //Getting input buffer (Input impedance) uint8_t ADS1256::getBuffer() // Getting input buffer (Input impedance)
{ {
uint8_t statusValue = readRegister(STATUS_REG); //Read the whole STATUS register uint8_t statusValue = readRegister(STATUS_REG); // Read the whole STATUS register
return bitRead(statusValue, 1); return bitRead(statusValue, 1);
} }
void ADS1256::setGPIO(uint8_t dir0, uint8_t dir1, uint8_t dir2, uint8_t dir3) //Setting GPIO 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 _GPIO = readRegister(IO_REG); // Read the most recent value of the register
//Default: 11100000 - DEC: 224 - Ref: p32 I/O section // Default: 11100000 - DEC: 224 - Ref: p32 I/O section
//Sets D3-D0 as input or output // Sets D3-D0 as input or output
uint8_t GPIO_bit7, GPIO_bit6, GPIO_bit5, GPIO_bit4; uint8_t GPIO_bit7, GPIO_bit6, GPIO_bit5, GPIO_bit4;
//Bit7: DIR3 // Bit7: DIR3
if(dir3 == 1) if (dir3 == 1)
{ {
GPIO_bit7 = 1; //D3 is input (default) GPIO_bit7 = 1; // D3 is input (default)
} }
else else
{ {
GPIO_bit7 = 0; //D3 is output GPIO_bit7 = 0; // D3 is output
} }
bitWrite(_GPIO, 7, GPIO_bit7); bitWrite(_GPIO, 7, GPIO_bit7);
//----------------------------------------------------- //-----------------------------------------------------
//Bit6: DIR2 // Bit6: DIR2
if(dir2 == 1) if (dir2 == 1)
{ {
GPIO_bit6 = 1; //D2 is input (default) GPIO_bit6 = 1; // D2 is input (default)
} }
else else
{ {
GPIO_bit6 = 0; //D2 is output GPIO_bit6 = 0; // D2 is output
} }
bitWrite(_GPIO, 6, GPIO_bit6); bitWrite(_GPIO, 6, GPIO_bit6);
//----------------------------------------------------- //-----------------------------------------------------
//Bit5: DIR1 // Bit5: DIR1
if(dir1 == 1) if (dir1 == 1)
{ {
GPIO_bit5 = 1; //D1 is input (default) GPIO_bit5 = 1; // D1 is input (default)
} }
else else
{ {
GPIO_bit5 = 0; //D1 is output GPIO_bit5 = 0; // D1 is output
} }
bitWrite(_GPIO, 5, GPIO_bit5); bitWrite(_GPIO, 5, GPIO_bit5);
//----------------------------------------------------- //-----------------------------------------------------
//Bit4: DIR0 // Bit4: DIR0
if(dir0 == 1) if (dir0 == 1)
{ {
GPIO_bit4 = 1; //D0 is input GPIO_bit4 = 1; // D0 is input
} }
else else
{ {
GPIO_bit4 = 0; //D0 is output (default) GPIO_bit4 = 0; // D0 is output (default)
} }
bitWrite(_GPIO, 4, GPIO_bit4); bitWrite(_GPIO, 4, GPIO_bit4);
//----------------------------------------------------- //-----------------------------------------------------
@@ -367,17 +384,17 @@ void ADS1256::setGPIO(uint8_t dir0, uint8_t dir1, uint8_t dir2, uint8_t dir3) //
delay(100); delay(100);
} }
void ADS1256::writeGPIO(uint8_t dir0value, uint8_t dir1value, uint8_t dir2value, uint8_t dir3value) //Writing GPIO void ADS1256::writeGPIO(uint8_t dir0value, uint8_t dir1value, uint8_t dir2value, uint8_t dir3value) // Writing GPIO
{ {
_GPIO = readRegister(IO_REG); _GPIO = readRegister(IO_REG);
//Sets D3-D0 output values // Sets D3-D0 output values
//It is important that first one must use setGPIO, then writeGPIO // It is important that first one must use setGPIO, then writeGPIO
uint8_t GPIO_bit3, GPIO_bit2, GPIO_bit1, GPIO_bit0; uint8_t GPIO_bit3, GPIO_bit2, GPIO_bit1, GPIO_bit0;
//Bit3: DIR3 // Bit3: DIR3
if(dir3value == 1) if (dir3value == 1)
{ {
GPIO_bit3 = 1; GPIO_bit3 = 1;
} }
@@ -387,8 +404,8 @@ void ADS1256::writeGPIO(uint8_t dir0value, uint8_t dir1value, uint8_t dir2value,
} }
bitWrite(_GPIO, 3, GPIO_bit3); bitWrite(_GPIO, 3, GPIO_bit3);
//----------------------------------------------------- //-----------------------------------------------------
//Bit2: DIR2 // Bit2: DIR2
if(dir2value == 1) if (dir2value == 1)
{ {
GPIO_bit2 = 1; GPIO_bit2 = 1;
} }
@@ -398,8 +415,8 @@ void ADS1256::writeGPIO(uint8_t dir0value, uint8_t dir1value, uint8_t dir2value,
} }
bitWrite(_GPIO, 2, GPIO_bit2); bitWrite(_GPIO, 2, GPIO_bit2);
//----------------------------------------------------- //-----------------------------------------------------
//Bit1: DIR1 // Bit1: DIR1
if(dir1value == 1) if (dir1value == 1)
{ {
GPIO_bit1 = 1; GPIO_bit1 = 1;
} }
@@ -409,8 +426,8 @@ void ADS1256::writeGPIO(uint8_t dir0value, uint8_t dir1value, uint8_t dir2value,
} }
bitWrite(_GPIO, 1, GPIO_bit1); bitWrite(_GPIO, 1, GPIO_bit1);
//----------------------------------------------------- //-----------------------------------------------------
//Bit0: DIR0 // Bit0: DIR0
if(dir0value == 1) if (dir0value == 1)
{ {
GPIO_bit0 = 1; GPIO_bit0 = 1;
} }
@@ -425,13 +442,13 @@ void ADS1256::writeGPIO(uint8_t dir0value, uint8_t dir1value, uint8_t dir2value,
delay(100); delay(100);
} }
uint8_t ADS1256::readGPIO(uint8_t gpioPin) //Reading GPIO uint8_t ADS1256::readGPIO(uint8_t gpioPin) // Reading GPIO
{ {
uint8_t GPIO_bit3, GPIO_bit2, GPIO_bit1, GPIO_bit0, GPIO_return; uint8_t GPIO_bit3, GPIO_bit2, GPIO_bit1, GPIO_bit0, GPIO_return;
_GPIO = readRegister(IO_REG); //Read the GPIO register _GPIO = readRegister(IO_REG); // Read the GPIO register
//Save each bit values in a variable // Save each bit values in a variable
GPIO_bit3 = bitRead(_GPIO, 3); GPIO_bit3 = bitRead(_GPIO, 3);
GPIO_bit2 = bitRead(_GPIO, 2); GPIO_bit2 = bitRead(_GPIO, 2);
GPIO_bit1 = bitRead(_GPIO, 1); GPIO_bit1 = bitRead(_GPIO, 1);
@@ -439,7 +456,7 @@ uint8_t ADS1256::readGPIO(uint8_t gpioPin) //Reading GPIO
delay(100); delay(100);
switch(gpioPin) //Selecting which value should be returned switch (gpioPin) // Selecting which value should be returned
{ {
case 0: case 0:
GPIO_return = GPIO_bit0; GPIO_return = GPIO_bit0;
@@ -459,66 +476,78 @@ uint8_t ADS1256::readGPIO(uint8_t gpioPin) //Reading GPIO
} }
return GPIO_return; return GPIO_return;
} }
void ADS1256::sendDirectCommand(uint8_t directCommand) void ADS1256::sendDirectCommand(uint8_t directCommand)
{ {
//Direct commands can be found in the datasheet Page 34, Table 24. LOG_DEBUG("Direct Command");
// Direct commands can be found in the datasheet Page 34, Table 24.
LOG_DEBUG("Direct Command Begin");
_spi->beginTransaction(SPISettings(1920000, MSBFIRST, SPI_MODE1)); _spi->beginTransaction(SPISettings(1920000, MSBFIRST, SPI_MODE1));
CS_LOW(); //REF: P34: "CS must stay low during the entire command sequence" CS_LOW(); // REF: P34: "CS must stay low during the entire command sequence"
LOG_DEBUG("Direct Command CS LOW");
delayMicroseconds(5); delayMicroseconds(5);
_spi->transfer(directCommand); //Send Command _spi->transfer(directCommand); // Send Command
LOG_DEBUG("Transfer OK");
delayMicroseconds(5); delayMicroseconds(5);
CS_HIGH(); //REF: P34: "CS must stay low during the entire command sequence" CS_HIGH(); // REF: P34: "CS must stay low during the entire command sequence"
LOG_DEBUG("Direct Command CS HIGH");
_spi->endTransaction(); _spi->endTransaction();
LOG_DEBUG("Direct Command End");
} }
float ADS1256::convertToVoltage(int32_t rawData) // Converting the 24-bit data into a voltage value
float ADS1256::convertToVoltage(int32_t rawData) //Converting the 24-bit data into a voltage value
{ {
return(conversionParameter * rawData); return (conversionParameter * rawData);
} }
void ADS1256::writeRegister(uint8_t registerAddress, uint8_t registerValueToWrite) void ADS1256::writeRegister(uint8_t registerAddress, uint8_t registerValueToWrite)
{ {
waitForLowDRDY(); waitForLowDRDY();
LOG_DEBUG("DRDY Low");
_spi->beginTransaction(SPISettings(1920000, MSBFIRST, SPI_MODE1)); _spi->beginTransaction(SPISettings(1920000, MSBFIRST, SPI_MODE1));
//SPI_MODE1 = output edge: rising, data capture: falling; clock polarity: 0, clock phase: 1. // SPI_MODE1 = output edge: rising, data capture: falling; clock polarity: 0, clock phase: 1.
LOG_DEBUG("SPI Begin");
CS_LOW(); //CS must stay LOW during the entire sequence [Ref: P34, T24] CS_LOW(); // CS must stay LOW during the entire sequence [Ref: P34, T24]
LOG_DEBUG("CS Low");
delayMicroseconds(5); //see t6 in the datasheet delayMicroseconds(5); // see t6 in the datasheet
_spi->transfer(0x50 | registerAddress); // 0x50 = 01010000 = WREG _spi->transfer(0x50 | registerAddress); // 0x50 = 01010000 = WREG
LOG_DEBUG("Transfer 1");
_spi->transfer(0x00); //2nd (empty) command byte _spi->transfer(0x00); // 2nd (empty) command byte
LOG_DEBUG("Transfer 2");
_spi->transfer(registerValueToWrite); //pass the value to the register _spi->transfer(registerValueToWrite); // pass the value to the register
LOG_DEBUG("Transfer 3");
CS_HIGH(); CS_HIGH();
LOG_DEBUG("CS High");
_spi->endTransaction(); _spi->endTransaction();
LOG_DEBUG("SPI End");
} }
long ADS1256::readRegister(uint8_t registerAddress) //Reading a register long ADS1256::readRegister(uint8_t registerAddress) // Reading a register
{ {
waitForLowDRDY(); waitForLowDRDY();
_spi->beginTransaction(SPISettings(1920000, MSBFIRST, SPI_MODE1)); _spi->beginTransaction(SPISettings(1920000, MSBFIRST, SPI_MODE1));
//SPI_MODE1 = output edge: rising, data capture: falling; clock polarity: 0, clock phase: 1. // 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] 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(0x10 | registerAddress); // 0x10 = 0001000 = RREG - OR together the two numbers (command + address)
_spi->transfer(0x00); //2nd (empty) command byte _spi->transfer(0x00); // 2nd (empty) command byte
delayMicroseconds(5); //see t6 in the datasheet delayMicroseconds(5); // see t6 in the datasheet
uint8_t regValue = _spi->transfer(0xFF); //read out the register value uint8_t regValue = _spi->transfer(0xFF); // read out the register value
CS_HIGH(); CS_HIGH();
_spi->endTransaction(); _spi->endTransaction();
@@ -526,39 +555,38 @@ long ADS1256::readRegister(uint8_t registerAddress) //Reading a register
return regValue; return regValue;
} }
long ADS1256::readSingle() // Reading a single value ONCE using the RDATA command
long ADS1256::readSingle() //Reading a single value ONCE using the RDATA command
{ {
_spi->beginTransaction(SPISettings(1920000, MSBFIRST, SPI_MODE1)); _spi->beginTransaction(SPISettings(1920000, MSBFIRST, SPI_MODE1));
CS_LOW(); //REF: P34: "CS must stay low during the entire command sequence" CS_LOW(); // REF: P34: "CS must stay low during the entire command sequence"
waitForLowDRDY(); waitForLowDRDY();
_spi->transfer(0b00000001); //Issue RDATA (0000 0001) command _spi->transfer(0b00000001); // Issue RDATA (0000 0001) command
delayMicroseconds(7); //Wait t6 time (~6.51 us) REF: P34, FIG:30. delayMicroseconds(7); // Wait t6 time (~6.51 us) REF: P34, FIG:30.
_outputBuffer[0] = _spi->transfer(0); // MSB _outputBuffer[0] = _spi->transfer(0); // MSB
_outputBuffer[1] = _spi->transfer(0); // Mid-byte _outputBuffer[1] = _spi->transfer(0); // Mid-byte
_outputBuffer[2] = _spi->transfer(0); // LSB _outputBuffer[2] = _spi->transfer(0); // LSB
//Shifting and combining the above three items into a single, 24-bit number // 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 = ((long)_outputBuffer[0] << 16) | ((long)_outputBuffer[1] << 8) | (_outputBuffer[2]);
_outputValue = convertSigned24BitToLong(_outputValue); _outputValue = convertSigned24BitToLong(_outputValue);
CS_HIGH(); //We finished the command sequence, so we set CS to HIGH CS_HIGH(); // We finished the command sequence, so we set CS to HIGH
_spi->endTransaction(); _spi->endTransaction();
return(_outputValue); return (_outputValue);
} }
long ADS1256::readSingleContinuous() //Reads the recently selected input channel using RDATAC long ADS1256::readSingleContinuous() // Reads the recently selected input channel using RDATAC
{ {
if(_isAcquisitionRunning == false) if (_isAcquisitionRunning == false)
{ {
_isAcquisitionRunning = true; _isAcquisitionRunning = true;
_spi->beginTransaction(SPISettings(1920000, MSBFIRST, SPI_MODE1)); _spi->beginTransaction(SPISettings(1920000, MSBFIRST, SPI_MODE1));
CS_LOW(); //REF: P34: "CS must stay low during the entire command sequence" CS_LOW(); // REF: P34: "CS must stay low during the entire command sequence"
waitForLowDRDY(); waitForLowDRDY();
_spi->transfer(0b00000011); //Issue RDATAC (0000 0011) _spi->transfer(0b00000011); // Issue RDATAC (0000 0011)
delayMicroseconds(7); //Wait t6 time (~6.51 us) REF: P34, FIG:30. delayMicroseconds(7); // Wait t6 time (~6.51 us) REF: P34, FIG:30.
} }
else else
{ {
@@ -569,7 +597,7 @@ long ADS1256::readSingleContinuous() //Reads the recently selected input channel
_outputBuffer[1] = _spi->transfer(0); // Mid-byte _outputBuffer[1] = _spi->transfer(0); // Mid-byte
_outputBuffer[2] = _spi->transfer(0); // LSB _outputBuffer[2] = _spi->transfer(0); // LSB
_outputValue = ((long)_outputBuffer[0]<<16) | ((long)_outputBuffer[1]<<8) | (_outputBuffer[2]); _outputValue = ((long)_outputBuffer[0] << 16) | ((long)_outputBuffer[1] << 8) | (_outputBuffer[2]);
_outputValue = convertSigned24BitToLong(_outputValue); _outputValue = convertSigned24BitToLong(_outputValue);
waitForHighDRDY(); waitForHighDRDY();
@@ -579,83 +607,84 @@ long ADS1256::readSingleContinuous() //Reads the recently selected input channel
long ADS1256::cycleSingle() long ADS1256::cycleSingle()
{ {
if(_isAcquisitionRunning == false) if (_isAcquisitionRunning == false)
{ {
_isAcquisitionRunning = true; _isAcquisitionRunning = true;
_cycle = 0; _cycle = 0;
_spi->beginTransaction(SPISettings(1920000, MSBFIRST, SPI_MODE1)); _spi->beginTransaction(SPISettings(1920000, MSBFIRST, SPI_MODE1));
CS_LOW(); //CS must stay LOW during the entire sequence [Ref: P34, T24] CS_LOW(); // CS must stay LOW during the entire sequence [Ref: P34, T24]
_spi->transfer(0x50 | 1); // 0x50 = WREG //1 = MUX _spi->transfer(0x50 | 1); // 0x50 = WREG //1 = MUX
_spi->transfer(0x00); _spi->transfer(0x00);
_spi->transfer(SING_0); //AIN0+AINCOM _spi->transfer(SING_0); // AIN0+AINCOM
CS_HIGH(); CS_HIGH();
delay(50); delay(50);
CS_LOW(); //CS must stay LOW during the entire sequence [Ref: P34, T24] CS_LOW(); // CS must stay LOW during the entire sequence [Ref: P34, T24]
} }
else else
{} {
}
if(_cycle < 8) if (_cycle < 8)
{ {
_outputValue = 0; _outputValue = 0;
waitForLowDRDY(); waitForLowDRDY();
//Step 1. - Updating MUX // Step 1. - Updating MUX
switch (_cycle) switch (_cycle)
{ {
//Channels are written manually // Channels are written manually
case 0: //Channel 2 case 0: // Channel 2
updateMUX(SING_1); //AIN1+AINCOM updateMUX(SING_1); // AIN1+AINCOM
break; break;
case 1: //Channel 3 case 1: // Channel 3
updateMUX(SING_2); //AIN2+AINCOM updateMUX(SING_2); // AIN2+AINCOM
break; break;
case 2: //Channel 4 case 2: // Channel 4
updateMUX(SING_3); //AIN3+AINCOM updateMUX(SING_3); // AIN3+AINCOM
break; break;
case 3: //Channel 5 case 3: // Channel 5
updateMUX(SING_4); //AIN4+AINCOM updateMUX(SING_4); // AIN4+AINCOM
break; break;
case 4: //Channel 6 case 4: // Channel 6
updateMUX(SING_5); //AIN5+AINCOM updateMUX(SING_5); // AIN5+AINCOM
break; break;
case 5: //Channel 7 case 5: // Channel 7
updateMUX(SING_6); //AIN6+AINCOM updateMUX(SING_6); // AIN6+AINCOM
break; break;
case 6: //Channel 8 case 6: // Channel 8
updateMUX(SING_7); //AIN7+AINCOM updateMUX(SING_7); // AIN7+AINCOM
break; break;
case 7: //Channel 1 case 7: // Channel 1
updateMUX(SING_0); //AIN0+AINCOM updateMUX(SING_0); // AIN0+AINCOM
break; break;
} }
//Step 2. // Step 2.
_spi->transfer(0b11111100); //SYNC _spi->transfer(0b11111100); // SYNC
delayMicroseconds(4); //t11 delay 24*tau = 3.125 us //delay should be larger, so we delay by 4 us 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(0b11111111); // WAKEUP
//Step 3. // Step 3.
//Issue RDATA (0000 0001) command // Issue RDATA (0000 0001) command
_spi->transfer(0b00000001); _spi->transfer(0b00000001);
delayMicroseconds(7); //Wait t6 time (~6.51 us) REF: P34, FIG:30. delayMicroseconds(7); // Wait t6 time (~6.51 us) REF: P34, FIG:30.
_outputBuffer[0] = _spi->transfer(0x0F); // MSB _outputBuffer[0] = _spi->transfer(0x0F); // MSB
_outputBuffer[1] = _spi->transfer(0x0F); // Mid-byte _outputBuffer[1] = _spi->transfer(0x0F); // Mid-byte
_outputBuffer[2] = _spi->transfer(0x0F); // LSB _outputBuffer[2] = _spi->transfer(0x0F); // LSB
_outputValue = ((long)_outputBuffer[0]<<16) | ((long)_outputBuffer[1]<<8) | (_outputBuffer[2]); _outputValue = ((long)_outputBuffer[0] << 16) | ((long)_outputBuffer[1] << 8) | (_outputBuffer[2]);
_outputValue = convertSigned24BitToLong(_outputValue); _outputValue = convertSigned24BitToLong(_outputValue);
_cycle++; //Increase cycle - This will move to the next MUX input channel _cycle++; // Increase cycle - This will move to the next MUX input channel
if(_cycle == 8) if (_cycle == 8)
{ {
_cycle = 0; //Reset to 0 - Restart conversion from the 1st input channel _cycle = 0; // Reset to 0 - Restart conversion from the 1st input channel
} }
} }
@@ -664,70 +693,71 @@ long ADS1256::cycleSingle()
long ADS1256::cycleDifferential() long ADS1256::cycleDifferential()
{ {
if(_isAcquisitionRunning == false) if (_isAcquisitionRunning == false)
{ {
_cycle = 0; _cycle = 0;
_isAcquisitionRunning = true; _isAcquisitionRunning = true;
_spi->beginTransaction(SPISettings(1920000, MSBFIRST, SPI_MODE1)); _spi->beginTransaction(SPISettings(1920000, MSBFIRST, SPI_MODE1));
//Set the AIN0+AIN1 as inputs manually // Set the AIN0+AIN1 as inputs manually
CS_LOW(); //CS must stay LOW during the entire sequence [Ref: P34, T24] CS_LOW(); // CS must stay LOW during the entire sequence [Ref: P34, T24]
_spi->transfer(0x50 | 1); // 0x50 = WREG //1 = MUX _spi->transfer(0x50 | 1); // 0x50 = WREG //1 = MUX
_spi->transfer(0x00); _spi->transfer(0x00);
_spi->transfer(DIFF_0_1); //AIN0+AIN1 _spi->transfer(DIFF_0_1); // AIN0+AIN1
CS_HIGH(); CS_HIGH();
delay(50); delay(50);
CS_LOW(); //CS must stay LOW during the entire sequence [Ref: P34, T24] CS_LOW(); // CS must stay LOW during the entire sequence [Ref: P34, T24]
} }
else else
{} {
}
if(_cycle < 4) if (_cycle < 4)
{ {
_outputValue = 0; _outputValue = 0;
//DRDY has to go low // DRDY has to go low
waitForLowDRDY(); waitForLowDRDY();
//Step 1. - Updating MUX // Step 1. - Updating MUX
switch (_cycle) switch (_cycle)
{ {
case 0: //Channel 2 case 0: // Channel 2
updateMUX(DIFF_2_3); //AIN2+AIN3 updateMUX(DIFF_2_3); // AIN2+AIN3
break; break;
case 1: //Channel 3 case 1: // Channel 3
updateMUX(DIFF_4_5); //AIN4+AIN5 updateMUX(DIFF_4_5); // AIN4+AIN5
break; break;
case 2: //Channel 4 case 2: // Channel 4
updateMUX(DIFF_6_7); //AIN6+AIN7 updateMUX(DIFF_6_7); // AIN6+AIN7
break; break;
case 3: //Channel 1 case 3: // Channel 1
updateMUX(DIFF_0_1); //AIN0+AIN1 updateMUX(DIFF_0_1); // AIN0+AIN1
break; break;
} }
_spi->transfer(0b11111100); //SYNC _spi->transfer(0b11111100); // SYNC
delayMicroseconds(4); //t11 delay 24*tau = 3.125 us //delay should be larger, so we delay by 4 us 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(0b11111111); // WAKEUP
//Step 3. // Step 3.
_spi->transfer(0b00000001); //Issue RDATA (0000 0001) command _spi->transfer(0b00000001); // Issue RDATA (0000 0001) command
delayMicroseconds(7); //Wait t6 time (~6.51 us) REF: P34, FIG:30. delayMicroseconds(7); // Wait t6 time (~6.51 us) REF: P34, FIG:30.
_outputBuffer[0] = _spi->transfer(0); // MSB _outputBuffer[0] = _spi->transfer(0); // MSB
_outputBuffer[1] = _spi->transfer(0); // Mid-byte _outputBuffer[1] = _spi->transfer(0); // Mid-byte
_outputBuffer[2] = _spi->transfer(0); // LSB _outputBuffer[2] = _spi->transfer(0); // LSB
_outputValue = ((long)_outputBuffer[0]<<16) | ((long)_outputBuffer[1]<<8) | (_outputBuffer[2]); _outputValue = ((long)_outputBuffer[0] << 16) | ((long)_outputBuffer[1] << 8) | (_outputBuffer[2]);
_outputValue = convertSigned24BitToLong(_outputValue); _outputValue = convertSigned24BitToLong(_outputValue);
_cycle++; _cycle++;
if(_cycle == 4) if (_cycle == 4)
{ {
_cycle = 0; _cycle = 0;
//After the 4th cycle, we reset to zero so the next iteration reads the 1st MUX again // After the 4th cycle, we reset to zero so the next iteration reads the 1st MUX again
} }
} }
@@ -736,20 +766,20 @@ long ADS1256::cycleDifferential()
void ADS1256::updateConversionParameter() void ADS1256::updateConversionParameter()
{ {
conversionParameter = ((2.0 * _VREF) / 8388608.0) / (pow(2, _PGA)); //Calculate the "bit to Volts" multiplier conversionParameter = ((2.0 * _VREF) / 8388608.0) / (pow(2, _PGA)); // Calculate the "bit to Volts" multiplier
//8388608 = 2^{23} - 1, REF: p23, Table 16. // 8388608 = 2^{23} - 1, REF: p23, Table 16.
} }
void ADS1256::updateMUX(uint8_t muxValue) void ADS1256::updateMUX(uint8_t muxValue)
{ {
_spi->transfer(0x50 | MUX_REG); //Write to the MUX register (0x50 is the WREG command) _spi->transfer(0x50 | MUX_REG); // Write to the MUX register (0x50 is the WREG command)
_spi->transfer(0x00); _spi->transfer(0x00);
_spi->transfer(muxValue); //Write the new MUX value _spi->transfer(muxValue); // Write the new MUX value
} }
inline void ADS1256::CS_LOW() inline void ADS1256::CS_LOW()
{ {
if (_CS_pin != PIN_UNUSED) //Sets CS LOW if it is not an unused pin if (_CS_pin != PIN_UNUSED) // Sets CS LOW if it is not an unused pin
{ {
digitalWrite(_CS_pin, LOW); digitalWrite(_CS_pin, LOW);
} }
@@ -757,7 +787,7 @@ inline void ADS1256::CS_LOW()
inline void ADS1256::CS_HIGH() inline void ADS1256::CS_HIGH()
{ {
if (_CS_pin != PIN_UNUSED) //Sets CS HIGH if it is not an unused pin if (_CS_pin != PIN_UNUSED) // Sets CS HIGH if it is not an unused pin
{ {
digitalWrite(_CS_pin, HIGH); digitalWrite(_CS_pin, HIGH);
} }
+8 -2
View File
@@ -4,6 +4,7 @@ RGBled::RGBled(const uint8_t pin) : m_led(pin)
{ {
pinMode(m_led, OUTPUT); pinMode(m_led, OUTPUT);
writeStatus(RGBled::ERROR); writeStatus(RGBled::ERROR);
m_brightness = 1.0f;
} }
RGBled::~RGBled() RGBled::~RGBled()
@@ -11,6 +12,11 @@ RGBled::~RGBled()
pinMode(m_led, INPUT); pinMode(m_led, INPUT);
} }
void RGBled::setBrightness(const float b)
{
m_brightness = b;
}
void RGBled::setStatus(const LedStatus s) void RGBled::setStatus(const LedStatus s)
{ {
if (m_status == s) if (m_status == s)
@@ -27,6 +33,6 @@ const RGBled::LedStatus RGBled::getSatus(void)
void RGBled::writeStatus(const RGBled::LedStatus s) void RGBled::writeStatus(const RGBled::LedStatus s)
{ {
RGBled::color_u u{.status = s}; const RGBled::color_u u{.status = s};
rgbLedWrite(m_led, u.color.r, u.color.g, u.color.b); rgbLedWrite(m_led, (uint8_t)(m_brightness*u.color.r), (uint8_t)(m_brightness*u.color.g), (uint8_t)(m_brightness*u.color.b));
} }
+3 -1
View File
@@ -37,7 +37,7 @@ public:
struct color_t struct color_t
{ {
uint8_t a, g, r, b; uint8_t a, r, g, b;
}; };
union color_u union color_u
@@ -50,6 +50,7 @@ public:
RGBled(const uint8_t pin = 48); RGBled(const uint8_t pin = 48);
~RGBled(); ~RGBled();
void setBrightness(const float b);
void setStatus(const LedStatus s); void setStatus(const LedStatus s);
const LedStatus getSatus(void); const LedStatus getSatus(void);
@@ -59,5 +60,6 @@ private:
private: private:
LedStatus m_status = LedStatus::IDLE; LedStatus m_status = LedStatus::IDLE;
std::mutex m_mutex; std::mutex m_mutex;
float m_brightness;
const uint8_t m_led; const uint8_t m_led;
}; };
+4 -4
View File
@@ -28,7 +28,7 @@ monitor_port = /dev/ttyACM0
monitor_speed = 921600 monitor_speed = 921600
build_type = release build_type = release
build_flags = build_flags =
-DCORE_DEBUG_LEVEL=1 -DCORE_DEBUG_LEVEL=5
-DARDUINO_USB_CDC_ON_BOOT=0 -DARDUINO_USB_CDC_ON_BOOT=0
-DARDUINO_USB_MODE=0 -DARDUINO_USB_MODE=0
-DCONFIG_ASYNC_TCP_MAX_ACK_TIME=5000 -DCONFIG_ASYNC_TCP_MAX_ACK_TIME=5000
@@ -59,12 +59,12 @@ build_flags =
-O0 -O0
-g3 -g3
-ggdb3 -ggdb3
-DCORE_DEBUG_LEVEL=3 -DCORE_DEBUG_LEVEL=5
-DARDUINO_USB_CDC_ON_BOOT=0 -DARDUINO_USB_CDC_ON_BOOT=0
-DARDUINO_USB_MODE=0 -DARDUINO_USB_MODE=0
-DCONFIG_ASYNC_TCP_MAX_ACK_TIME=5000 -DCONFIG_ASYNC_TCP_MAX_ACK_TIME=5000
-DCONFIG_ASYNC_TCP_PRIORITY=21 -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_RUNNING_CORE=1
-DCONFIG_ASYNC_TCP_STACK_SIZE=4096 -DCONFIG_ASYNC_TCP_STACK_SIZE=8192
-fstack-protector-all -fstack-protector-all
+7 -101
View File
@@ -1,7 +1,7 @@
#include "datasave.h" #include "datasave.h"
#include <math.h> #include <math.h>
static const size_t min_free = 1024 * 1024; // minimum free space in LittleFS to allow saving history (1MB)
LITTLEFSGuard::LITTLEFSGuard() LITTLEFSGuard::LITTLEFSGuard()
{ {
@@ -22,26 +22,26 @@ LITTLEFSGuard::~LITTLEFSGuard()
LOG_INFO("LittleFS unmounted successfully"); LOG_INFO("LittleFS unmounted successfully");
} }
void ignitionBoxStatusAverage::filter(int32_t &old, const int32_t value, const uint32_t k) void ignitionBoxStatusFiltered::filter(int32_t &old, const int32_t value, const uint32_t k)
{ {
float alpha = 1.0f / (float)k; float alpha = 1.0f / (float)k;
old = old + (int32_t)(alpha * (float)(value - old)); old = old + (int32_t)(alpha * (float)(value - old));
} }
void ignitionBoxStatusAverage::filter(float &old, const float value, const uint32_t k) void ignitionBoxStatusFiltered::filter(float &old, const float value, const uint32_t k)
{ {
float alpha = 1.0f / (float)k; float alpha = 1.0f / (float)k;
old = old + (float)(alpha * (float)(value - old)); old = old + (float)(alpha * (float)(value - old));
} }
void ignitionBoxStatusAverage::reset() void ignitionBoxStatusFiltered::reset()
{ {
m_last = ignitionBoxStatus(); m_last = ignitionBoxStatus();
m_count = 0; m_count = 0;
m_data_valid = false; m_data_valid = false;
} }
void ignitionBoxStatusAverage::update(const ignitionBoxStatus &new_status) void ignitionBoxStatusFiltered::update(const ignitionBoxStatus &new_status)
{ {
if (m_count == 0 && !m_data_valid) if (m_count == 0 && !m_data_valid)
{ {
@@ -81,7 +81,7 @@ void ignitionBoxStatusAverage::update(const ignitionBoxStatus &new_status)
} }
} }
const bool ignitionBoxStatusAverage::get(ignitionBoxStatus &status) const const bool ignitionBoxStatusFiltered::get(ignitionBoxStatus &status) const
{ {
if (m_data_valid) if (m_data_valid)
{ {
@@ -90,7 +90,7 @@ const bool ignitionBoxStatusAverage::get(ignitionBoxStatus &status) const
return m_data_valid; return m_data_valid;
} }
const ArduinoJson::JsonDocument ignitionBoxStatusAverage::toJson() const const ArduinoJson::JsonDocument ignitionBoxStatusFiltered::toJson() const
{ {
ArduinoJson::JsonDocument doc; ArduinoJson::JsonDocument doc;
if (m_data_valid) if (m_data_valid)
@@ -125,97 +125,3 @@ const ArduinoJson::JsonDocument ignitionBoxStatusAverage::toJson() const
return doc; return doc;
} }
void saveHistoryTask(void *pvParameters)
{
const auto *params = static_cast<dataSaveParams *>(pvParameters);
const auto &history = *params->history;
const auto &file_path = params->file_path;
if (!params)
{
LOG_ERROR("Invalid parameters for saveHistoryTask");
return;
}
LOG_DEBUG("Starting saving: ", file_path.c_str());
save_history(history, file_path);
vTaskDelete(NULL);
}
void save_history(const PSRAMVector<ignitionBoxStatus> &history, const std::filesystem::path &file_name)
{
// Initialize SPIFFS
if (!SAVE_HISTORY_TO_LITTLEFS)
return;
auto littlefs_guard = LITTLEFSGuard(); // use RAII guard to ensure LittleFS is properly mounted and unmounted
if (LittleFS.totalBytes() - LittleFS.usedBytes() < min_free) // check if at least 1MB is free for saving history
{
LOG_ERROR("Not enough space in SPIFFS to save history");
return;
}
std::filesystem::path file_path = file_name;
if (file_name.root_path() != "/littlefs")
file_path = std::filesystem::path("/littlefs") / file_name;
auto save_flags = std::ios::out;
if (first_save && LittleFS.exists(file_path.c_str()))
{
first_save = false;
save_flags |= std::ios::trunc; // overwrite existing file
LittleFS.remove(file_path.c_str()); // ensure file is removed before saving to avoid issues with appending to existing file in SPIFFS
LOG_INFO("Saving history to LittleFS, new file:", file_path.c_str());
}
else
{
save_flags |= std::ios::app; // append to new file
LOG_INFO("Saving history to LittleFS, appending to existing file:", file_path.c_str());
}
std::ofstream ofs(file_path, save_flags);
if (ofs.fail())
{
LOG_ERROR("Failed to open file for writing");
return;
}
// write csv header
if (first_save)
{
ofs << "TS,\
EVENTS_12,DLY_12,STAT_12,V_12_1,V_12_2,V_12_3,V_12_4,IGNITION_MODE_12,\
EVENTS_34,DLY_34,STAT_34,V_34_1,V_34_2,V_34_3,V_34_4,IGNITION_MODE_34,\
ENGINE_RPM,ADC_READTIME,N_QUEUE_ERRORS"
<< std::endl;
ofs.flush();
}
for (const auto &entry : history)
{
ofs << std::to_string(entry.timestamp) << ","
<< std::to_string(entry.coils12.n_events) << ","
<< std::to_string(entry.coils12.spark_delay) << ","
<< std::string(sparkStatusNames.at(entry.coils12.spark_status)) << ","
<< std::to_string(entry.coils12.peak_p_in) << ","
<< std::to_string(entry.coils12.peak_n_in) << ","
<< std::to_string(entry.coils12.peak_p_out) << ","
<< std::to_string(entry.coils12.peak_n_out) << ","
<< std::string(softStartStatusNames.at(entry.coils12.sstart_status)) << ","
<< std::to_string(entry.coils34.n_events) << ","
<< std::to_string(entry.coils34.spark_delay) << ","
<< std::string(sparkStatusNames.at(entry.coils34.spark_status)) << ","
<< std::to_string(entry.coils34.peak_p_in) << ","
<< std::to_string(entry.coils34.peak_n_in) << ","
<< std::to_string(entry.coils34.peak_p_out) << ","
<< std::to_string(entry.coils34.peak_n_out) << ","
<< std::string(softStartStatusNames.at(entry.coils34.sstart_status)) << ","
<< std::to_string(entry.eng_rpm) << ","
<< std::to_string(entry.adc_read_time) << ","
<< std::to_string(entry.n_queue_errors);
ofs << std::endl;
ofs.flush();
}
ofs.close();
LOG_INFO("Ignition A history saved to LittleFS, records written: ", history.size());
}
+3 -15
View File
@@ -15,14 +15,6 @@
#include "psvector.h" #include "psvector.h"
const uint32_t max_history = 256; const uint32_t max_history = 256;
const bool SAVE_HISTORY_TO_LITTLEFS = false; // Set to true to enable saving history to LittleFS, false to disable
static bool first_save = true; // flag to indicate if this is the first save (to write header)
struct dataSaveParams
{
const PSRAMVector<ignitionBoxStatus> *history;
const std::filesystem::path file_path;
};
class LITTLEFSGuard class LITTLEFSGuard
{ {
@@ -31,7 +23,7 @@ public:
~LITTLEFSGuard(); ~LITTLEFSGuard();
}; };
class ignitionBoxStatusAverage class ignitionBoxStatusFiltered
{ {
private: private:
ignitionBoxStatus m_last; ignitionBoxStatus m_last;
@@ -40,8 +32,8 @@ private:
bool m_data_valid = false; // flag to indicate if the average data is valid (i.e. at least one sample has been added) bool m_data_valid = false; // flag to indicate if the average data is valid (i.e. at least one sample has been added)
public: public:
ignitionBoxStatusAverage() = default; ignitionBoxStatusFiltered() = default;
ignitionBoxStatusAverage(const uint32_t max_count) : m_max_count(max_count) ignitionBoxStatusFiltered(const uint32_t max_count) : m_max_count(max_count)
{ {
m_data_valid = false; m_data_valid = false;
m_count = 0; m_count = 0;
@@ -56,7 +48,3 @@ private:
void filter(int32_t &old, const int32_t value, const uint32_t k); void filter(int32_t &old, const int32_t value, const uint32_t k);
void filter(float &old, const float value, const uint32_t k); void filter(float &old, const float value, const uint32_t k);
}; };
// Task and function declarations
void saveHistoryTask(void *pvParameters);
void save_history(const PSRAMVector<ignitionBoxStatus> &history, const std::filesystem::path &file_path);
+30 -7
View File
@@ -3,10 +3,14 @@
// Library defines // Library defines
#define ADS1256_SPI_ALREADY_STARTED #define ADS1256_SPI_ALREADY_STARTED
// System Includes
#include <memory>
// Device Libraries // Device Libraries
#include <ADS1256.h> #include <ADS1256.h>
#include <AD5292.h> #include <AD5292.h>
#include <PCA95x5.h> #include <extio.h>
#include <Wire.h>
// ADC Channel mapping // ADC Channel mapping
#define ADC_CH_PEAK_12P_IN SING_0 #define ADC_CH_PEAK_12P_IN SING_0
@@ -19,17 +23,36 @@
#define ADC_CH_PEAK_34N_OUT SING_7 #define ADC_CH_PEAK_34N_OUT SING_7
// Device Pointer structs for tasks // Device Pointer structs for tasks
struct Devices { struct Devices
AD5292 *pot_a = NULL, *pot_b = NULL; {
ADS1256 *adc_a = NULL, *adc_b = NULL; // Busses
PCA9555* io = NULL; std::unique_ptr<TwoWire> m_i2c = nullptr;
std::unique_ptr<SPIClass> m_spi_a = nullptr;
std::unique_ptr<SPIClass> m_spi_b = nullptr;
// Bus Mutextes
std::mutex m_spi_a_mutex;
std::mutex m_spi_b_mutex;
std::mutex m_i2c_mutex;
// Device Pointers
std::unique_ptr<AD5292> m_pot_a = nullptr;
std::unique_ptr<AD5292> m_pot_b = nullptr;
std::unique_ptr<ADS1256> m_adc_a = nullptr;
std::unique_ptr<ADS1256> m_adc_b = nullptr;
std::unique_ptr<ExternalIO> m_ext_io = nullptr;
}; };
// Adc read channel wrapper to selet mux before reading // Adc read channel wrapper to selet mux before reading
inline float adcReadChannel(ADS1256* adc, const uint8_t ch){ inline float adcReadChannel(ADS1256 *adc, const uint8_t ch)
{
adc->setMUX(ch); adc->setMUX(ch);
// scarta 3 conversioni // scarta 3 conversioni
for (int i = 0; i < 3; i++) { for (int i = 0; i < 5; i++)
{
adc->readSingle(); adc->readSingle();
} }
// ora lettura valida a 30kSPS → ~100 µs di settling // ora lettura valida a 30kSPS → ~100 µs di settling
+129
View File
@@ -0,0 +1,129 @@
#include <extio.h>
// Static interrupt callback
static void onExpanderInterrupt(void *arg)
{
auto cls = (ExternalIO *)(arg);
if (!cls) // invalid args
return;
cls->extReadInterrupt();
}
ExternalIO::ExternalIO(TwoWire &i2c, std::mutex &i2c_mutex, const uint8_t int_pin) : m_i2cMutex(i2c_mutex), m_i2c(i2c), m_intPin(int_pin)
{
std::lock_guard<std::mutex> lock(m_i2cMutex);
// Attach OUT expanders on BUS
m_outMap[EXPANDER_A_OUT_ADDR] = std::make_unique<PCA9555>();
m_outMap[EXPANDER_A_OUT_ADDR]->attach(m_i2c, EXPANDER_A_OUT_ADDR);
m_outMap[EXPANDER_B_OUT_ADDR] = std::make_unique<PCA9555>();
m_outMap[EXPANDER_B_OUT_ADDR]->attach(m_i2c, EXPANDER_B_OUT_ADDR);
for (auto &[a, e] : m_outMap)
{
e->direction(PCA95x5::Direction::OUT_ALL);
e->polarity(PCA95x5::Polarity::ORIGINAL_ALL);
};
// Attach IN Expanders on Bus
m_inMap[EXPANDER_A_IN_ADDR] = std::make_unique<PCA9555>();
m_inMap[EXPANDER_A_IN_ADDR]->attach(m_i2c, EXPANDER_A_IN_ADDR);
m_inMap[EXPANDER_B_IN_ADDR] = std::make_unique<PCA9555>();
m_inMap[EXPANDER_B_IN_ADDR]->attach(m_i2c, EXPANDER_B_IN_ADDR);
for (auto &[a, e] : m_inMap)
{
e->direction(PCA95x5::Direction::IN_ALL);
e->polarity(PCA95x5::Polarity::ORIGINAL_ALL);
m_lastInputState[a] = e->read(); /// initialize input state to collect interrupts
};
}
ExternalIO::~ExternalIO() {
}
void ExternalIO::extDigitalWrite(const uint32_t mappedPin, const bool val)
{
std::lock_guard<std::mutex> lock(m_i2cMutex);
const io_t pa = map2pin(mappedPin);
if (!m_outMap.contains(pa.addr))
{
LOG_ERROR("Undefined IO Expander addr: [", pa.addr, "]");
return;
}
auto &io = m_outMap.at(pa.addr);
if (!io->write(static_cast<PCA95x5::Port::Port>(pa.pin), val ? PCA95x5::Level::H : PCA95x5::Level::L))
{
LOG_ERROR("IO Expander [", pa.addr, "] Unable to WRITE Port [", pa.pin, "] to [", val ? "HIGH" : "LOW");
LOG_ERROR("IO Expander Error [", io->i2c_error(), "]");
}
}
const bool ExternalIO::extDigitalRead(const uint32_t mappedPin)
{
std::lock_guard<std::mutex> lock(m_i2cMutex);
const io_t pa = map2pin(mappedPin);
if (!m_inMap.contains(pa.addr))
{
LOG_ERROR("Undefined IO Expander addr: [", pa.addr, "]");
return false;
}
auto &io = m_inMap.at(pa.addr);
const bool rv = io->read(static_cast<PCA95x5::Port::Port>(pa.pin)) == PCA95x5::Level::H ? true : false; // read value
const uint8_t err = io->i2c_error();
if (err)
{
LOG_ERROR("IO Expander [", pa.addr, "] Unable to READ Port [", pa.pin, "]");
LOG_ERROR("IO Expander Error [", err, "]");
}
return rv;
}
void ExternalIO::extAttachInterrupt(ExtInterruptCb cb)
{
attachInterruptArg(EXPANDER_ALL_INTERRUPT, onExpanderInterrupt, (void *)(this), FALLING);
m_extInterruptCb = cb;
}
void ExternalIO::extDetachInterrupt()
{
detachInterrupt(EXPANDER_ALL_INTERRUPT);
}
void ExternalIO::extReadInterrupt()
{
std::lock_guard<std::mutex> lock(m_i2cMutex);
disableInterrupt(EXPANDER_ALL_INTERRUPT);
// read all registers and collect
IOstate interruptState;
for (auto &[a, e] : m_inMap)
{
interruptState[a] = e->read();
}
m_lastInputState = interruptState; // restore to current values
// compare to last state to see the difference
if (m_extInterruptCb)
{
for (auto &[a, v] : interruptState)
{
if (v)
m_extInterruptCb(stat2map(a, v));
}
}
enableInterrupt(EXPANDER_ALL_INTERRUPT);
}
const ExternalIO::io_t ExternalIO::map2pin(const uint32_t mappedIO)
{
return io_t{
.addr = (uint8_t)((mappedIO >> 16) & (uint8_t)0xFF),
.pin = (uint8_t)(mappedIO && (uint32_t)0xFF),
};
}
const uint32_t ExternalIO::stat2map(const uint8_t addr, const uint16_t stat)
{
if (!stat)
return 0;
return (uint32_t)(addr << 16) | (1UL << __builtin_ctz(stat));
}
+49
View File
@@ -0,0 +1,49 @@
#pragma once
#define DEBUGLOG_DEFAULT_LOG_LEVEL_DEBUG
#include <Arduino.h>
#include <DebugLog.h>
#include <PCA95x5.h>
#include <pins.h>
#include <memory>
#include <map>
class ExternalIO
{
using IOptr = std::unique_ptr<PCA9555>;
using IOmap = std::map<const uint8_t, IOptr>;
using IOstate = std::map<const uint8_t, uint16_t>;
using ExtInterruptCb = std::function<void(const uint32_t)>;
struct io_t
{
uint8_t addr;
uint8_t pin;
};
public:
ExternalIO(TwoWire &i2c, std::mutex &i2c_mutex, const uint8_t int_pin);
~ExternalIO();
void extDigitalWrite(const uint32_t mappedPin, const bool val);
const bool extDigitalRead(const uint32_t mappedPin);
void extAttachInterrupt(ExtInterruptCb cb = nullptr);
void extDetachInterrupt();
void extReadInterrupt();
private:
const io_t map2pin(const uint32_t mappedIO);
const uint32_t stat2map(const uint8_t addr, const uint16_t stat);
private:
const uint8_t m_intPin;
IOmap m_inMap;
IOmap m_outMap;
uint8_t m_intPinChanged;
IOstate m_lastInputState;
ExtInterruptCb m_extInterruptCb = nullptr;
std::mutex &m_i2cMutex;
TwoWire &m_i2c;
};
+1 -1
View File
@@ -17,7 +17,7 @@
#define CORE_0 0 #define CORE_0 0
#define CORE_1 1 #define CORE_1 1
#define RT_TASK_STACK 2048 // in words #define RT_TASK_STACK 2048 // in words
#define RT_TASK_PRIORITY (configMAX_PRIORITIES - 6) // highest priority after wifi tasks #define RT_TASK_PRIORITY (configMAX_PRIORITIES - 5) // highest priority after wifi tasks
struct isrParams struct isrParams
{ {
+153 -219
View File
@@ -17,12 +17,13 @@
#include <led.h> #include <led.h>
// Defines to enable channel B // Defines to enable channel B
#define CH_B_ENABLE // #define CH_B_ENABLE
#define TEST
// Debug Defines // Debug Defines
#define WIFI_SSID "AstroRotaxMonitor" #define WIFI_SSID "AstroRotaxMonitor"
#define WIFI_PASSWORD "maledettirotax" #define WIFI_PASSWORD "maledettirotax"
#define PSRAM_MAX 4096
#define QUEUE_MAX 256
void setup() void setup()
{ {
@@ -52,6 +53,7 @@ void setup()
IPAddress gateway(10, 11, 12, 1); IPAddress gateway(10, 11, 12, 1);
IPAddress subnet(255, 255, 255, 0); IPAddress subnet(255, 255, 255, 0);
WiFi.softAPConfig(local_IP, gateway, subnet); WiFi.softAPConfig(local_IP, gateway, subnet);
WiFi.setTxPower(WIFI_POWER_13dBm); // reduce wifi power
if (WiFi.softAP(WIFI_SSID, WIFI_PASSWORD)) if (WiFi.softAP(WIFI_SSID, WIFI_PASSWORD))
{ {
LOG_INFO("WiFi AP Mode Started"); LOG_INFO("WiFi AP Mode Started");
@@ -78,86 +80,30 @@ void loop()
{ {
// global variables // global variables
RGBled led; RGBled led;
led.setBrightness(0.025f);
led.setStatus(RGBled::LedStatus::INIT); led.setStatus(RGBled::LedStatus::INIT);
std::shared_ptr<Devices> dev = std::make_shared<Devices>();
bool running = true; bool running = true;
const uint32_t max_queue = 128; std::mutex fs_mutex;
const uint32_t filter_k = 10; LITTLEFSGuard fsGuard;
PSRAMVector<ignitionBoxStatus> ignA_history_0(max_history); //////// INIT SPI INTERFACES ////////
PSRAMVector<ignitionBoxStatus> ignA_history_1(max_history);
auto *active_history_A = &ignA_history_0;
auto *writable_history_A = &ignA_history_1;
#ifdef CH_B_ENABLE
PSRAMVector<ignitionBoxStatus> ignB_history_0(max_history);
PSRAMVector<ignitionBoxStatus> ignB_history_1(max_history);
auto *active_history_B = &ignB_history_0;
auto *writable_history_B = &ignB_history_1;
#endif
// Resources Initialization
Devices dev;
// Task handle
TaskHandle_t trigA_TaskHandle = NULL;
TaskHandle_t trigB_TaskHandle = NULL;
// Data Queue for real time task to main loop communication
QueueHandle_t rt_taskA_queue = xQueueCreate(max_queue, sizeof(ignitionBoxStatus));
QueueHandle_t rt_taskB_queue = xQueueCreate(max_queue, sizeof(ignitionBoxStatus));
rtTaskParams taskA_params{
.rt_running = true,
.dev = &dev,
.rt_queue = rt_taskA_queue,
.rt_int = rtTaskInterrupts{
.isr_ptr = &trig_isr_A,
.trig_pin_12p = TRIG_PIN_A12P,
.trig_pin_12n = TRIG_PIN_A12N,
.trig_pin_34p = TRIG_PIN_A34P,
.trig_pin_34n = TRIG_PIN_A34N,
.spark_pin_12 = SPARK_PIN_A12,
.spark_pin_34 = SPARK_PIN_A34},
.rt_resets = rtTaskResets{.rst_io_peak = RST_EXT_PEAK_DETECT_A, .rst_io_sh = RST_EXT_SAMPLE_HOLD_A}};
#ifdef CH_B_ENABLE
rtTaskParams taskB_params{
.rt_running = true,
.dev = &dev,
.rt_queue = rt_taskB_queue,
.rt_int = rtTaskInterrupts{
.isr_ptr = &trig_isr_B,
.trig_pin_12p = TRIG_PIN_B12P,
.trig_pin_12n = TRIG_PIN_B12N,
.trig_pin_34p = TRIG_PIN_B34P,
.trig_pin_34n = TRIG_PIN_B34N,
.spark_pin_12 = SPARK_PIN_B12,
.spark_pin_34 = SPARK_PIN_B34},
.rt_resets = rtTaskResets{.rst_io_peak = RST_EXT_PEAK_DETECT_B, .rst_io_sh = RST_EXT_SAMPLE_HOLD_B}};
#endif
if (!rt_taskA_queue || !rt_taskB_queue)
{
LOG_ERROR("Unable To Create task queues");
LOG_ERROR("5 seconds to restart...");
vTaskDelay(pdMS_TO_TICKS(5000));
esp_restart();
}
else
LOG_DEBUG("Task Variables OK");
// Spi ok flags
bool spiA_ok = true; bool spiA_ok = true;
bool spiB_ok = true; bool spiB_ok = true;
// Init 2 SPI interfaces LOG_DEBUG("Init SPI Interfaces");
SPIClass SPI_A(FSPI); SPIClass SPI_A(FSPI);
spiA_ok = SPI_A.begin(SPI_A_SCK, SPI_A_MISO, SPI_A_MOSI); spiA_ok = SPI_A.begin(SPI_A_SCK, SPI_A_MISO, SPI_A_MOSI);
SPI_A.setDataMode(SPI_MODE1); // ADS1256 requires SPI mode 1 SPI_A.setDataMode(SPI_MODE1); // ADS1256 requires SPI mode 1
LOG_DEBUG("Init SPI A ok");
#ifdef CH_B_ENABLE #ifdef CH_B_ENABLE
#ifndef TEST delay(50);
SPIClass SPI_B(HSPI); SPIClass SPI_B(HSPI);
spiB_ok = SPI_B.begin(SPI_B_SCK, SPI_B_MISO, SPI_B_MOSI); spiB_ok = SPI_B.begin(SPI_B_SCK, SPI_B_MISO, SPI_B_MOSI);
SPI_B.setDataMode(SPI_MODE1); // ADS1256 requires SPI mode 1 SPI_B.setDataMode(SPI_MODE1); // ADS1256 requires SPI mode 1
LOG_DEBUG("Init SPI B ok");
#endif #endif
#endif
if (!spiA_ok || !spiB_ok) if (!spiA_ok || !spiB_ok)
{ {
LOG_ERROR("Unable to Initialize SPI Busses"); LOG_ERROR("Unable to Initialize SPI Busses");
@@ -165,54 +111,112 @@ void loop()
vTaskDelay(pdMS_TO_TICKS(5000)); vTaskDelay(pdMS_TO_TICKS(5000));
esp_restart(); 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_7500SPS);
#ifdef CH_B_ENABLE
dev->m_adc_b->InitializeADC();
dev->m_adc_b->setPGA(PGA_1);
dev->m_adc_b->setDRATE(DRATE_7500SPS);
#endif
LOG_DEBUG("Init SPI OK"); LOG_DEBUG("Init SPI OK");
#ifndef TEST //////// INIT I2C INTERFACES ////////
// Init ADC_A LOG_DEBUG("Init I2C Interfaces");
dev.adc_a = new ADS1256(ADC_A_DRDY, ADS1256::PIN_UNUSED, ADS1256::PIN_UNUSED, ADC_A_CS, 2.5, &SPI_A); bool i2c_ok = true;
dev.adc_a->InitializeADC(); i2c_ok = Wire.begin(SDA, SCL, 100000);
dev.adc_a->setPGA(PGA_1); if (!i2c_ok)
dev.adc_a->setDRATE(DRATE_7500SPS); {
#endif LOG_ERROR("Unable to Initialize I2C Bus");
#ifdef CH_B_ENABLE LOG_ERROR("5 seconds to restart...");
#ifndef TEST vTaskDelay(pdMS_TO_TICKS(5000));
// Init ADC_B esp_restart();
dev.adc_a = new ADS1256(ADC_B_DRDY, ADS1256::PIN_UNUSED, ADS1256::PIN_UNUSED, ADC_B_CS, 2.5, &SPI_B); }
dev.adc_a->InitializeADC();
dev.adc_a->setPGA(PGA_1);
dev.adc_a->setDRATE(DRATE_1000SPS);
#endif
#endif
LOG_DEBUG("Init ADC OK"); // Init IO Expanders
// dev->m_ext_io = std::make_unique<ExternalIO>(Wire, dev->m_i2c_mutex, EXPANDER_ALL_INTERRUPT);
//////// INIT REALTIME TASKS PARAMETERS ////////
const rtIgnitionTask::rtTaskParams taskA_params{
.rt_running = true,
.name = "rtIgnTask_A",
.rt_stack_size = RT_TASK_STACK,
.rt_priority = RT_TASK_PRIORITY,
.rt_int = rtIgnitionTask::rtTaskInterruptParams{
.isr_ptr = &trig_isr_A,
.trig_pin_12p = TRIG_PIN_A12P,
.trig_pin_12n = TRIG_PIN_A12N,
.trig_pin_34p = TRIG_PIN_A34P,
.trig_pin_34n = TRIG_PIN_A34N,
.spark_pin_12 = SPARK_PIN_A12,
.spark_pin_34 = SPARK_PIN_A34},
.rt_io = rtIgnitionTask::rtTaskIOParams{
.pot_cs_12 = POT_CS_A12,
.pot_cs_34 = POT_CS_A34,
.ss_force = SS_FORCE_A,
.ss_inhibit_12 = SS_INIBHIT_A12,
.ss_inhibit_34 = SS_INHIBIT_A34,
.sh_disch_12 = SH_DISCH_A12,
.sh_disch_34 = SH_DISCH_A34,
.sh_arm_12 = SH_ARM_A12,
.sh_arm_34 = SH_ARM_A34,
.relay_in_12 = RELAY_IN_A12,
.relay_in_34 = RELAY_OUT_A12,
.relay_out_12 = RELAY_IN_A34,
.relay_out_34 = RELAY_OUT_A34,
},
.rt_queue = nullptr,
.dev = dev};
const rtIgnitionTask::rtTaskParams taskB_params{
.rt_running = true,
.name = "rtIgnTask_B",
.rt_stack_size = RT_TASK_STACK,
.rt_priority = RT_TASK_PRIORITY,
.rt_int = rtIgnitionTask::rtTaskInterruptParams{
.isr_ptr = &trig_isr_B,
.trig_pin_12p = TRIG_PIN_B12P,
.trig_pin_12n = TRIG_PIN_B12N,
.trig_pin_34p = TRIG_PIN_B34P,
.trig_pin_34n = TRIG_PIN_B34N,
.spark_pin_12 = SPARK_PIN_B12,
.spark_pin_34 = SPARK_PIN_B34},
.rt_io = rtIgnitionTask::rtTaskIOParams{
.pot_cs_12 = POT_CS_B12,
.pot_cs_34 = POT_CS_B34,
.ss_force = SS_FORCE_B,
.ss_inhibit_12 = SS_INIBHIT_B12,
.ss_inhibit_34 = SS_INHIBIT_B34,
.sh_disch_12 = SH_DISCH_B12,
.sh_disch_34 = SH_DISCH_B34,
.sh_arm_12 = SH_ARM_B12,
.sh_arm_34 = SH_ARM_B34,
.relay_in_12 = RELAY_IN_B12,
.relay_in_34 = RELAY_OUT_B12,
.relay_out_12 = RELAY_IN_B34,
.relay_out_34 = RELAY_OUT_B34,
},
.rt_queue = nullptr,
.dev = dev};
//////// SPAWN REALTIME TASKS ////////
auto task_A = rtIgnitionTask(taskA_params, PSRAM_MAX, QUEUE_MAX, CORE_0, fs_mutex);
delay(50);
auto task_B = rtIgnitionTask(taskB_params, PSRAM_MAX, QUEUE_MAX, CORE_1, fs_mutex);
// Ignition A on Core 0 // Ignition A on Core 0
auto ignA_task_success = pdPASS; auto ignA_task_success = task_A.getStatus() == rtIgnitionTask::OK ? pdPASS : pdFAIL;
ignA_task_success = xTaskCreatePinnedToCore( auto ignB_task_success = task_B.getStatus() == rtIgnitionTask::OK ? pdPASS : pdFAIL;
rtIgnitionTask,
"rtTask_A",
RT_TASK_STACK,
(void *)&taskA_params,
RT_TASK_PRIORITY,
&trigA_TaskHandle,
CORE_0);
delay(100); // give some time to the thread to start
// Ignition B on Core 1
auto ignB_task_success = pdPASS;
#ifdef CH_B_ENABLE
ignB_task_success = xTaskCreatePinnedToCore(
rtIgnitionTask,
"rtTask_B",
RT_TASK_STACK,
(void *)&taskB_params,
RT_TASK_PRIORITY, // priorità leggermente più alta
&trigB_TaskHandle,
CORE_1);
delay(100); // give some time to the thread to start
#endif
if (ignA_task_success != pdPASS || ignB_task_success != pdPASS) if (ignA_task_success != pdPASS || ignB_task_success != pdPASS)
{ {
LOG_ERROR("Unable to initialize ISR task"); LOG_ERROR("Unable to initialize ISR task");
@@ -221,126 +225,56 @@ void loop()
esp_restart(); 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);
LOG_ERROR("Unable to start realtime tasks");
}
else
{
LOG_DEBUG("Real Time Tasks A & B initialized"); LOG_DEBUG("Real Time Tasks A & B initialized");
led.setStatus(RGBled::LedStatus::OK); led.setStatus(RGBled::LedStatus::OK);
}
bool partial_save = false; // flag to indicate if a partial save has been done after a timeout //////// SPAWN WEBSERVER and WEBSOCKET ////////
auto last_data = millis(); AstroWebServer webPage(80, LittleFS);
auto last_info = millis(); ArduinoJson::JsonDocument json_data;
bool data_a, data_b;
task_A.onMessage([&webPage, &json_data, &data_a](ignitionBoxStatusFiltered sts)
{
json_data["box_a"] = sts.toJson();
data_a = true; });
uint32_t counter_a = 0; task_B.onMessage([&webPage, &json_data, &data_b](ignitionBoxStatusFiltered sts)
uint32_t counter_b = 0; {
uint32_t wait_count = 0; json_data["box_b"] = sts.toJson();
data_b = true; });
ignitionBoxStatus ign_info_A; // task_A.enableSave(true, "ignitionA_test.csv");
ignitionBoxStatus ign_info_B; // task_B.enableSave(true, "ignitionB_test.csv");
ignitionBoxStatusAverage ign_info_avg_A(filter_k);
ignitionBoxStatusAverage ign_info_avg_B(filter_k);
LITTLEFSGuard fsGuard;
WebPage webPage(80, LittleFS); // Initialize webserver and Websocket
uint32_t monitor_loop = millis();
uint32_t data_loop = monitor_loop;
//////////////// INNER LOOP ///////////////////// //////////////// INNER LOOP /////////////////////
while (running) while (running)
{ {
auto dataA = pdFALSE; uint32_t this_loop = millis();
auto dataB = pdFALSE; if (this_loop - monitor_loop > 2000)
dataA = xQueueReceive(rt_taskA_queue, &ign_info_A, 0);
if (counter_a >= active_history_A->size()) // not concurrent with write task
{
counter_a = 0;
partial_save = false; // reset partial save flag on new data cycle
swapHistory(active_history_A, writable_history_A);
save_history(*writable_history_A, "ignition_historyA.csv"); // directly call the save task function to save without delay
}
#ifdef CH_B_ENABLE
dataB = xQueueReceive(rt_taskB_queue, &ign_info_B, 0);
if (counter_b >= active_history_B->size()) // not concurrent with write task
{
counter_b = 0;
partial_save = false; // reset partial save flag on new data cycle
swapHistory(active_history_B, writable_history_B);
save_history(*writable_history_B, "ignition_historyB.csv"); // directly call the save task function to save without delay
}
#endif
// Update last data
if (dataA == pdTRUE || dataB == pdTRUE)
last_data = millis();
// Update Led color
if (dataA == pdTRUE && dataB == pdFALSE)
led.setStatus(RGBled::DATA_A);
else if (dataB == pdTRUE && dataA == pdFALSE)
led.setStatus(RGBled::DATA_B);
else
led.setStatus(RGBled::DATA_ALL);
if (dataA == pdTRUE)
{
(*active_history_A)[counter_a++ % active_history_A->size()] = ign_info_A;
ign_info_avg_A.update(ign_info_A); // update moving average with latest ignition status
// Serial.printf("Data Received A: %d/%d\n\r", counter_a, (*active_history_A).size());
if (counter_a % filter_k == 0) // send data every 10 samples
{
ArduinoJson::JsonDocument wsData;
wsData["box_a"] = ign_info_avg_A.toJson();
wsData["box_b"] = JsonObject();
webPage.sendWsData(wsData.as<String>());
}
}
#ifdef CH_B_ENABLE
if (dataB == pdTRUE)
{
(*active_history_B)[counter_b++ % active_history_B->size()] = ign_info_B;
ign_info_avg_B.update(ign_info_B); // update moving average with latest ignition status
// Serial.printf("Data Received B: %d/%d\n\r", counter_b, (*active_history_B).size());
if (counter_b % filter_k == 0) // send data every 10 samples
{
ArduinoJson::JsonDocument wsData;
wsData["box_a"] = JsonObject();
wsData["box_b"] = ign_info_avg_B.toJson();
webPage.sendWsData(wsData.as<String>());
}
}
#endif
if (dataA == pdFALSE && dataB == pdFALSE && (millis() - last_data) > 2000)
{
if (!partial_save && counter_a > 0) // if timeout occurs but we have unsaved data, save it before next timeout
{
active_history_A->resize(counter_a); // resize active history to actual number of records received to avoid saving empty records
save_history(*active_history_A, "ignition_history_A.csv");
active_history_A->resize(max_history); // resize back to max history size for next data cycle
#ifdef CH_B_ENABLE
active_history_B->resize(counter_a); // resize active history to actual number of records received to avoid saving empty records
save_history(*active_history_B, "ignition_history_B.csv");
active_history_B->resize(max_history); // resize back to max history size for next data cycle
#endif
counter_a = 0; // reset counter after saving
counter_b = 0; // reset counter after saving
partial_save = true;
first_save = true;
}
// Serial.printf("[%d] Waiting for data...\r", wait_count++);
led.setStatus(RGBled::LedStatus::IDLE);
delay(100);
}
if ((millis() - last_info) > 1000)
{ {
clearScreen(); clearScreen();
Serial.println();
printRunningTasksMod(Serial); printRunningTasksMod(Serial);
last_info = millis(); monitor_loop = millis();
}
if ((data_a && data_b) || (this_loop - data_loop > 500))
{
webPage.sendWsData(json_data.as<String>());
json_data.clear();
data_a = data_b = false;
data_loop = millis();
} }
} //////////////// INNER LOOP ///////////////////// } //////////////// INNER LOOP /////////////////////
if (trigA_TaskHandle)
vTaskDelete(trigA_TaskHandle);
if (trigB_TaskHandle)
vTaskDelete(trigB_TaskHandle);
} ////////////////////// MAIN LOOP ////////////////////// } ////////////////////// MAIN LOOP //////////////////////
+77 -27
View File
@@ -53,12 +53,6 @@
#define ADC_B_CS 21 #define ADC_B_CS 21
#define ADC_B_DRDY 47 #define ADC_B_DRDY 47
// =====================
// DIGITAL POT
// =====================
#define POT_A_CS 18
#define POT_B_CS 35
// ===================== // =====================
// TRIGGER INPUT INTERRUPTS // TRIGGER INPUT INTERRUPTS
// ===================== // =====================
@@ -79,31 +73,87 @@
#define SPARK_PIN_B12 1 #define SPARK_PIN_B12 1
#define SPARK_PIN_B34 2 #define SPARK_PIN_B34 2
// ===================== // +++++++++++++++++++++
// PCA9555 (I2C EXPANDER) // MACRO TO COMBINE PIN NUMBER AND ADDRESS
// ===================== #define PIN2ADDR(p, a) ((1UL << p) | ((uint32_t)(a) << 16))
// +++++++++++++++++++++
// --- RESET LINES --- // =====================
#define RST_EXT_PEAK_DETECT_A 0 // PCA9555 I/O EXPANDER INTERRUPT (Common)
#define RST_EXT_SAMPLE_HOLD_A 1 // =====================
#define RST_EXT_PEAK_DETECT_B 2 #define EXPANDER_ALL_INTERRUPT 17
#define RST_EXT_SAMPLE_HOLD_B 3
#define BTN_3 4 // =====================
#define BTN_4 5 // PCA9555 I/O EXPANDER BOX_A (OUT)
#define BTN_5 6 // =====================
#define BTN_6 7 #define EXPANDER_A_OUT_ADDR 0xFF
// --- DIGITAL POT CHIP SELECT LINES ---
#define POT_CS_A12 PIN2ADDR(0, EXPANDER_A_OUT_ADDR)
#define POT_CS_A34 PIN2ADDR(1, EXPANDER_A_OUT_ADDR)
// --- SOFT START FORCE LINES ---
#define SS_FORCE_A PIN2ADDR(2, EXPANDER_A_OUT_ADDR)
#define SS_INIBHIT_A12 PIN2ADDR(3, EXPANDER_A_OUT_ADDR)
#define SS_INHIBIT_A34 PIN2ADDR(4, EXPANDER_A_OUT_ADDR)
// --- SAMPLE AND HOLD ARM AND DISCHARGE ---
#define SH_DISCH_A12 PIN2ADDR(5, EXPANDER_A_OUT_ADDR)
#define SH_DISCH_A34 PIN2ADDR(6, EXPANDER_A_OUT_ADDR)
#define SH_ARM_A12 PIN2ADDR(7, EXPANDER_A_OUT_ADDR)
#define SH_ARM_A34 PIN2ADDR(8, EXPANDER_A_OUT_ADDR)
// --- RELAY --- // --- RELAY ---
#define EXT_RELAY_A 8 #define RELAY_IN_A12 PIN2ADDR(9, EXPANDER_A_OUT_ADDR)
#define EXT_RELAY_B 9 #define RELAY_OUT_A12 PIN2ADDR(10, EXPANDER_A_OUT_ADDR)
#define RELAY_IN_A34 PIN2ADDR(11, EXPANDER_A_OUT_ADDR)
#define RELAY_OUT_A34 PIN2ADDR(12, EXPANDER_A_OUT_ADDR)
// --- STATUS / BUTTON --- // =====================
#define BTN_7 10 // PCA9555 I/O EXPANDER BOX_A (IN)
#define BTN_8 11 // =====================
#define STA_1 12 #define EXPANDER_A_IN_ADDR 0xFF
#define STA_2 13
#define STA_3 14 #define SS_A12_ON PIN2ADDR(0, EXPANDER_A_IN_ADDR)
#define STA_4 15 #define SS_A12_OFF PIN2ADDR(1, EXPANDER_A_IN_ADDR)
#define SS_A34_ON PIN2ADDR(2, EXPANDER_A_IN_ADDR)
#define SS_A34_OFF PIN2ADDR(3, EXPANDER_A_IN_ADDR)
// =====================
// PCA9555 I/O EXPANDER BOX_B (OUT)
// =====================
#define EXPANDER_B_OUT_ADDR 0xFF
// --- DIGITAL POT CHIP SELECT LINES ---
#define POT_CS_B12 PIN2ADDR(0, EXPANDER_B_OUT_ADDR)
#define POT_CS_B34 PIN2ADDR(1, EXPANDER_B_OUT_ADDR)
// --- SOFT START FORCE LINES ---
#define SS_FORCE_B PIN2ADDR(2, EXPANDER_B_OUT_ADDR)
#define SS_INIBHIT_B12 PIN2ADDR(3, EXPANDER_B_OUT_ADDR)
#define SS_INHIBIT_B34 PIN2ADDR(4, EXPANDER_B_OUT_ADDR)
// --- SAMPLE AND HOLD ARM AND DISCHARGE ---
#define SH_DISCH_B12 PIN2ADDR(5, EXPANDER_B_OUT_ADDR)
#define SH_DISCH_B34 PIN2ADDR(6, EXPANDER_B_OUT_ADDR)
#define SH_ARM_B12 PIN2ADDR(7, EXPANDER_B_OUT_ADDR)
#define SH_ARM_B34 PIN2ADDR(8, EXPANDER_B_OUT_ADDR)
// --- RELAY ---
#define RELAY_IN_B12 PIN2ADDR(9, EXPANDER_B_OUT_ADDR)
#define RELAY_OUT_B12 PIN2ADDR(10, EXPANDER_B_OUT_ADDR)
#define RELAY_IN_B34 PIN2ADDR(11, EXPANDER_B_OUT_ADDR)
#define RELAY_OUT_B34 PIN2ADDR(12, EXPANDER_B_OUT_ADDR)
// =====================
// PCA9555 I/O EXPANDER BOX_B (IN)
// =====================
#define EXPANDER_B_IN_ADDR 0xFF
#define SS_B12_ON PIN2ADDR(0, EXPANDER_B_IN_ADDR)
#define SS_B12_OFF PIN2ADDR(1, EXPANDER_B_IN_ADDR)
#define SS_B34_ON PIN2ADDR(2, EXPANDER_B_IN_ADDR)
#define SS_B34_OFF PIN2ADDR(3, EXPANDER_B_IN_ADDR)
// Init Pin Functions // Init Pin Functions
inline void initTriggerPinsInputs() inline void initTriggerPinsInputs()
+1 -1
View File
@@ -65,7 +65,7 @@
#define RST_EXT_A34N 3 #define RST_EXT_A34N 3
// --- RELAY --- // --- RELAY ---
#define EXT_RELAY_A 8 #define SH_ARM_A34 8
// Init Pin Functions // Init Pin Functions
+277 -16
View File
@@ -1,5 +1,9 @@
#include "tasks.h" #include "tasks.h"
#include <esp_timer.h> #include <esp_timer.h>
#include <datasave.h>
#include <mutex>
//// GLOBAL STATIC FUNCTIONS
// Timeout callback for microsecond precision // Timeout callback for microsecond precision
void spark_timeout_callback(void *arg) void spark_timeout_callback(void *arg)
@@ -8,7 +12,18 @@ void spark_timeout_callback(void *arg)
xTaskNotify(handle, SPARK_FLAG_TIMEOUT, eSetValueWithOverwrite); xTaskNotify(handle, SPARK_FLAG_TIMEOUT, eSetValueWithOverwrite);
} }
void rtIgnitionTask(void *pvParameters) // Manages queue receive, save data and callback to external tasks for communication
void rtIgnitionTask::rtIgnitionTask_manager(void *pvParameters)
{
rtIgnitionTask *cls = (rtIgnitionTask *)pvParameters;
while (cls->m_running)
{
cls->run();
}
}
// Static task function
void rtIgnitionTask::rtIgnitionTask_realtime(void *pvParameters)
{ {
// Invalid real time rt_task_ptr parameters, exit immediate // Invalid real time rt_task_ptr parameters, exit immediate
@@ -18,15 +33,15 @@ void rtIgnitionTask(void *pvParameters)
vTaskDelete(NULL); vTaskDelete(NULL);
} }
// Task Parameters and Devices // Task Parameters and Devices
rtTaskParams *params = (rtTaskParams *)pvParameters; rtTaskParams *params = (rtTaskParams *)pvParameters;
const rtTaskInterrupts rt_int = params->rt_int; // copy to avoid external override const rtTaskInterruptParams rt_int = params->rt_int; // copy to avoid external override
const rtTaskResets rt_rst = params->rt_resets; // copy to avoid external override const rtTaskIOParams rt_rst = params->rt_io; // copy to avoid external override
QueueHandle_t rt_queue = params->rt_queue; QueueHandle_t rt_queue = params->rt_queue;
Devices *dev = params->dev; Devices *dev = params->dev.get();
ADS1256 *adc = dev->adc_a; ADS1256 *adc = params->name == "rtIgnTask_A" ? dev->m_adc_a.get() : dev->m_adc_b.get();
PCA9555 *io = dev->io; 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();
TaskStatus_t rt_task_info; TaskStatus_t rt_task_info;
vTaskGetInfo(NULL, &rt_task_info, pdFALSE, eInvalid); vTaskGetInfo(NULL, &rt_task_info, pdFALSE, eInvalid);
@@ -75,7 +90,6 @@ void rtIgnitionTask(void *pvParameters)
.name = "spark_timeout"}; .name = "spark_timeout"};
esp_timer_create(&timer_args, &timeout_timer); esp_timer_create(&timer_args, &timeout_timer);
// Attach Pin Interrupts // Attach Pin Interrupts
attachInterruptArg(digitalPinToInterrupt(rt_int.trig_pin_12p), rt_int.isr_ptr, (void *)&isr_params_t12p, RISING); attachInterruptArg(digitalPinToInterrupt(rt_int.trig_pin_12p), rt_int.isr_ptr, (void *)&isr_params_t12p, RISING);
attachInterruptArg(digitalPinToInterrupt(rt_int.trig_pin_12n), rt_int.isr_ptr, (void *)&isr_params_t12n, RISING); attachInterruptArg(digitalPinToInterrupt(rt_int.trig_pin_12n), rt_int.isr_ptr, (void *)&isr_params_t12n, RISING);
@@ -222,6 +236,7 @@ void rtIgnitionTask(void *pvParameters)
// read adc channels: pickup12, out12 [ pos + neg ] // read adc channels: pickup12, out12 [ pos + neg ]
if (adc) // read only if adc initialized if (adc) // read only if adc initialized
{ {
std::lock_guard<std::mutex> lock (spi_mutex);
uint32_t start_adc_read = esp_timer_get_time(); uint32_t start_adc_read = esp_timer_get_time();
// from peak detector circuits // from peak detector circuits
ign_box_sts.coils12.peak_p_in = adcReadChannel(adc, ADC_CH_PEAK_12P_IN); ign_box_sts.coils12.peak_p_in = adcReadChannel(adc, ADC_CH_PEAK_12P_IN);
@@ -235,20 +250,16 @@ void rtIgnitionTask(void *pvParameters)
ign_box_sts.adc_read_time = (int32_t)(esp_timer_get_time() - start_adc_read); ign_box_sts.adc_read_time = (int32_t)(esp_timer_get_time() - start_adc_read);
} }
else // simulate adc read timig else // simulate adc read timig
vTaskDelay(pdMS_TO_TICKS(1)); vTaskDelay(pdMS_TO_TICKS(c_adc_time));
// reset peak detectors + sample and hold // reset peak detectors + sample and hold
// outputs on io expander // outputs on io expander
if (io) if (io)
{ {
const uint16_t iostat = io->read(); // [TODO] code to reset sample and hold and arm trigger level detectors
const uint16_t rst_bitmask = (0x0001 << rt_rst.rst_io_peak);
io->write(iostat | rst_bitmask);
vTaskDelay(pdMS_TO_TICKS(1));
io->write(iostat & ~rst_bitmask);
} }
else else
vTaskDelay(pdMS_TO_TICKS(1)); vTaskDelay(pdMS_TO_TICKS(2));
// send essage to main loop with ignition info, by copy so local static variable is ok // send essage to main loop with ignition info, by copy so local static variable is ok
if (rt_queue) if (rt_queue)
@@ -261,7 +272,7 @@ void rtIgnitionTask(void *pvParameters)
} }
// Delete the timeout timer // Delete the timeout timer
esp_timer_delete(timeout_timer); esp_timer_delete(timeout_timer);
LOG_WARN("Ending realTime Task"); LOG_WARN("rtTask Ending [", rt_task_name, "]");
// Ignition A Interrupts DETACH // Ignition A Interrupts DETACH
detachInterrupt(rt_int.trig_pin_12p); detachInterrupt(rt_int.trig_pin_12p);
detachInterrupt(rt_int.trig_pin_12n); detachInterrupt(rt_int.trig_pin_12n);
@@ -272,3 +283,253 @@ void rtIgnitionTask(void *pvParameters)
// delete present task // delete present task
vTaskDelete(NULL); vTaskDelete(NULL);
} }
///////////// 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)
{
// create queue buffers
m_queue = xQueueCreate(queue_size, sizeof(ignitionBoxStatus));
if (!m_queue)
{
LOG_ERROR("Unable To Create Task [", params.name.c_str(), "] queues");
m_manager_status = rtTaskStatus::ERROR;
return;
}
else
m_params.rt_queue = m_queue;
// create PSram history vectors
m_history_0 = PSHistory(history_size);
m_history_1 = PSHistory(history_size);
// assing active and writable 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(), "]");
// auto task_success = pdPASS;
auto task_success = xTaskCreatePinnedToCore(
rtIgnitionTask_manager,
(std::string("man_") + m_params.name).c_str(),
8192,
(void *)this,
m_params.rt_priority >> 2,
&m_manager_handle,
m_core);
if (task_success != pdPASS)
{
LOG_ERROR("Unable To Create Manager for [", params.name.c_str(), "]");
m_manager_status = rtTaskStatus::ERROR;
return;
}
// average every 10 samples
m_info_filtered = ignitionBoxStatusFiltered(10);
m_last_data = millis();
m_manager_status = rtTaskStatus::OK;
}
rtIgnitionTask::~rtIgnitionTask()
{
if (m_rt_handle)
vTaskDelete(m_rt_handle);
if (m_manager_handle)
vTaskDelete(m_manager_handle);
if (m_queue)
vQueueDelete(m_queue);
}
void rtIgnitionTask::run()
{
// receive new data from the queue
auto new_data = xQueueReceive(m_queue, &m_last_status, 0); // non blocking receive
if (new_data == pdPASS)
{
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())
{
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
}
// update filtered data
m_info_filtered.update(m_last_status);
(*m_active_history)[m_counter_status] = m_last_status;
if (m_on_message_cb && m_counter_status % 10 == 0)
{
m_on_message_cb(m_info_filtered);
}
// update data counter
m_counter_status++;
}
else
{
if (millis() - m_last_data > c_idle_time)
{
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_counter_status = 0;
m_partial_save = true;
}
m_manager_status = rtTaskStatus::IDLE;
}
delay(5); // yeld to another task
}
}
const bool rtIgnitionTask::start()
{
LOG_WARN("Starting rtTask [", m_params.name.c_str(), "]");
auto task_success = xTaskCreatePinnedToCore(
rtIgnitionTask_realtime,
m_params.name.c_str(),
m_params.rt_stack_size,
(void *)&m_params,
m_params.rt_priority,
&m_rt_handle,
m_core);
const bool success = task_success == pdPASS && m_rt_handle != nullptr;
if (success)
m_manager_status = rtTaskStatus::IDLE;
return success;
}
const bool rtIgnitionTask::stop()
{
LOG_WARN("Ending Task [", m_params.name.c_str(), "]");
if (m_rt_handle)
{
m_params.rt_running = false;
m_rt_handle = nullptr;
m_manager_status = rtTaskStatus::STOPPED;
return true;
}
return false;
}
const ignitionBoxStatus rtIgnitionTask::getLast() const
{
return m_last_status;
}
const ignitionBoxStatusFiltered rtIgnitionTask::getFiltered() const
{
return m_info_filtered;
}
const rtIgnitionTask::rtTaskStatus rtIgnitionTask::getStatus() const
{
return m_manager_status;
}
void rtIgnitionTask::enableSave(const bool enable, const std::filesystem::path filename)
{
m_enable_save = enable;
if (enable && !filename.empty())
{
LOG_WARN("Save History Enabled Task [", m_params.name.c_str(), "]");
m_history_path = m_filesystem.mountpoint() / filename;
}
else
{
LOG_WARN("Save History Disabled Task [", m_params.name.c_str(), "]");
}
}
void rtIgnitionTask::onMessage(std::function<void(ignitionBoxStatusFiltered)> callaback)
{
m_on_message_cb = callaback;
}
void rtIgnitionTask::saveHistory(const rtIgnitionTask::PSHistory &history, const std::filesystem::path &file_name)
{
// Lock filesystem mutex to avoid concurrent access
std::lock_guard<std::mutex> fs_lock(m_fs_mutex);
// Check for free space
if (LittleFS.totalBytes() - LittleFS.usedBytes() < history.size() * sizeof(ignitionBoxStatus)) // check if at least 1MB is free for saving history
{
LOG_ERROR("Not enough space in SPIFFS to save history");
return;
}
// create complete file path
const std::filesystem::path mount_point = std::filesystem::path(m_filesystem.mountpoint());
std::filesystem::path file_path = file_name;
if (file_name.root_path() != mount_point)
file_path = mount_point / file_name;
// if firt save remove old file and create new
auto save_flags = std::ios::out;
if (m_first_save)
{
save_flags |= std::ios::trunc; // overwrite existing file
m_filesystem.remove(file_path.c_str()); // ensure file is removed before saving to avoid issues with appending to existing file in SPIFFS
LOG_INFO("Saving history to Flash, new file:", file_path.c_str());
}
else // else append to existing file
{
save_flags |= std::ios::app; // append to new file
LOG_INFO("Saving history to Flash, appending to existing file:", file_path.c_str());
}
std::ofstream ofs(file_path, save_flags);
if (ofs.fail())
{
LOG_ERROR("Failed to open file for writing");
return;
}
// write csv header
if (m_first_save)
{
ofs << "TS,EVENTS_12,DLY_12,STAT_12,V_12_1,V_12_2,V_12_3,V_12_4,IGNITION_MODE_12,"
<< "EVENTS_34,DLY_34,STAT_34,V_34_1,V_34_2,V_34_3,V_34_4,IGNITION_MODE_34,"
<< "ENGINE_RPM,ADC_READTIME,N_QUEUE_ERRORS"
<< std::endl;
ofs.flush();
m_first_save = false;
}
for (const auto &entry : history)
{
ofs << std::to_string(entry.timestamp) << ","
<< std::to_string(entry.coils12.n_events) << ","
<< std::to_string(entry.coils12.spark_delay) << ","
<< std::string(sparkStatusNames.at(entry.coils12.spark_status)) << ","
<< std::to_string(entry.coils12.peak_p_in) << ","
<< std::to_string(entry.coils12.peak_n_in) << ","
<< std::to_string(entry.coils12.peak_p_out) << ","
<< std::to_string(entry.coils12.peak_n_out) << ","
<< std::string(softStartStatusNames.at(entry.coils12.sstart_status)) << ","
<< std::to_string(entry.coils34.n_events) << ","
<< std::to_string(entry.coils34.spark_delay) << ","
<< std::string(sparkStatusNames.at(entry.coils34.spark_status)) << ","
<< std::to_string(entry.coils34.peak_p_in) << ","
<< std::to_string(entry.coils34.peak_n_in) << ","
<< std::to_string(entry.coils34.peak_p_out) << ","
<< std::to_string(entry.coils34.peak_n_out) << ","
<< std::string(softStartStatusNames.at(entry.coils34.sstart_status)) << ","
<< std::to_string(entry.eng_rpm) << ","
<< std::to_string(entry.adc_read_time) << ","
<< std::to_string(entry.n_queue_errors);
ofs << std::endl;
ofs.flush();
}
ofs.close();
LOG_INFO("Ignition Box history saved to Flash, records written: ", history.size());
}
+115 -19
View File
@@ -2,12 +2,19 @@
#define DEBUGLOG_DEFAULT_LOG_LEVEL_DEBUG #define DEBUGLOG_DEFAULT_LOG_LEVEL_DEBUG
// Serial debug flag // Serial debug flag
//#define DEBUG // #define DEBUG
// Arduino Libraries // Arduino Libraries
#include <Arduino.h> #include <Arduino.h>
#include <DebugLog.h> #include <DebugLog.h>
#include "utils.h" #include "utils.h"
#include <memory>
#include <mutex>
#include <filesystem>
#include <FS.h>
#include <LittleFS.h>
#include <datasave.h>
#include <functional>
// ISR // ISR
#include "isr.h" #include "isr.h"
@@ -31,9 +38,14 @@ static const std::map<const uint32_t, const char *> names = {
}; };
#endif #endif
// RT task Interrupt parameters class rtIgnitionTask
struct rtTaskInterrupts
{ {
using PSHistory = PSRAMVector<ignitionBoxStatus>;
public:
// RT task Interrupt parameters
struct rtTaskInterruptParams
{
void (*isr_ptr)(void *); void (*isr_ptr)(void *);
const uint8_t trig_pin_12p; const uint8_t trig_pin_12p;
const uint8_t trig_pin_12n; const uint8_t trig_pin_12n;
@@ -41,23 +53,107 @@ struct rtTaskInterrupts
const uint8_t trig_pin_34n; const uint8_t trig_pin_34n;
const uint8_t spark_pin_12; const uint8_t spark_pin_12;
const uint8_t spark_pin_34; const uint8_t spark_pin_34;
}; };
// RT Task Peak Detector Reset pins // RT Task Peak Detector Reset pins
struct rtTaskResets struct rtTaskIOParams
{ {
const uint8_t rst_io_peak; const uint32_t expander_addr;
const uint8_t rst_io_sh; const uint32_t pot_cs_12;
}; const uint32_t pot_cs_34;
const uint32_t ss_force;
const uint32_t ss_inhibit_12;
const uint32_t ss_inhibit_34;
const uint32_t sh_disch_12;
const uint32_t sh_disch_34;
const uint32_t sh_arm_12;
const uint32_t sh_arm_34;
const uint32_t relay_in_12;
const uint32_t relay_in_34;
const uint32_t relay_out_12;
const uint32_t relay_out_34;
};
// RT task parameters // RT task parameters
struct rtTaskParams struct rtTaskParams
{ {
bool rt_running; // run flag, false to terminate bool rt_running; // run flag, false to terminate
Devices *dev; const std::string name;
const QueueHandle_t rt_queue; const uint32_t rt_stack_size;
const rtTaskInterrupts rt_int; // interrupt pins to attach const uint32_t rt_priority;
const rtTaskResets rt_resets; // reset ping for peak detectors 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;
};
void rtIgnitionTask(void *pvParameters); enum rtTaskStatus
{
INIT,
OK,
ERROR,
RUNNING,
IDLE,
STOPPED
};
public:
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 = LittleFS);
~rtIgnitionTask();
void run();
const bool start();
const bool stop();
const ignitionBoxStatus getLast() const;
const ignitionBoxStatusFiltered getFiltered() const;
const rtTaskStatus getStatus() const;
void enableSave(const bool enable, const std::filesystem::path filename);
void onMessage(std::function<void(ignitionBoxStatusFiltered)> callaback);
private:
void saveHistory(const rtIgnitionTask::PSHistory &history, const std::filesystem::path &file_name);
private: // static functions for FreeRTOS
static void rtIgnitionTask_manager(void *pvParameters);
static void rtIgnitionTask_realtime(void *pvParameters);
private:
bool m_running = true;
rtTaskStatus m_manager_status = INIT;
rtTaskParams m_params;
const uint8_t m_core;
TaskHandle_t m_rt_handle = nullptr;
TaskHandle_t m_manager_handle = nullptr;
QueueHandle_t m_queue = nullptr;
bool m_enable_save = false;
std::filesystem::path m_history_path;
const uint32_t m_max_history;
PSHistory m_history_0;
PSHistory m_history_1;
std::unique_ptr<PSHistory> m_active_history;
std::unique_ptr<PSHistory> m_save_history;
fs::FS &m_filesystem;
std::mutex &m_fs_mutex;
bool m_partial_save = false;
bool m_first_save = true;
uint32_t m_counter_status = 0;
uint32_t m_last_data = 0;
ignitionBoxStatus m_last_status;
ignitionBoxStatusFiltered m_info_filtered;
std::function<void(ignitionBoxStatusFiltered)> m_on_message_cb = nullptr;
static const uint32_t c_idle_time = 10000; // in mS
static const uint32_t c_spark_timeout_max = 500; // uS
static const uint8_t c_adc_time = 4; // in mS
static const uint8_t c_io_time = 2; // in mS
};
+116 -4
View File
@@ -5,25 +5,69 @@
#include "freertos/FreeRTOS.h" #include "freertos/FreeRTOS.h"
#include "freertos/portable.h" #include "freertos/portable.h"
#include "esp_heap_caps.h"
#include "esp_system.h"
#include "esp_spi_flash.h"
#include "esp_partition.h"
#include "LittleFS.h"
#include <vector> #include <vector>
#include <algorithm> #include <algorithm>
#include <functional> #include <functional>
#define FREERTOS_TASK_NUMBER_MAX_NUM 256 // RunTime stats for how many Tasks to be stored #define FREERTOS_TASK_NUMBER_MAX_NUM 256 // RunTime stats for how many Tasks to be stored
std::string printBits(uint32_t value) { std::string printBits(uint32_t value)
{
std::string result; std::string result;
for (int i = 31; i >= 0; i--) { for (int i = 31; i >= 0; i--)
{
// ottieni il singolo bit // ottieni il singolo bit
result += ((value >> i) & 1) ? '1' : '0'; result += ((value >> i) & 1) ? '1' : '0';
// aggiungi uno spazio ogni 8 bit, tranne dopo l'ultimo // aggiungi uno spazio ogni 8 bit, tranne dopo l'ultimo
if (i % 8 == 0 && i != 0) { if (i % 8 == 0 && i != 0)
{
result += ' '; result += ' ';
} }
} }
return result; return result;
} }
// ANSI colors
#define BAR_WIDTH 30
#define COLOR_RESET "\033[0m"
#define COLOR_RED "\033[31m"
#define COLOR_GREEN "\033[32m"
#define COLOR_BLUE "\033[34m"
#define COLOR_MAGENTA "\033[35m"
#define COLOR_CYAN "\033[36m"
#define COLOR_YELLOW "\033[33m"
#define COLOR_WHITE "\033[37m"
#define COLOR_LBLUE "\033[94m"
void printBar(Print &printer, const char *label, size_t used, size_t total, const char *color)
{
float perc = total > 0 ? ((float)used / total) : 0;
int filled = perc * BAR_WIDTH;
printer.printf("%s%-12s [" COLOR_RESET, color, label);
for (int i = 0; i < BAR_WIDTH; i++)
{
if (i < filled)
printer.printf("%s#%s", color, COLOR_RESET);
else
printer.printf("-");
}
printer.printf("] %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));
}
void printRunningTasksMod(Print &printer, std::function<bool(const TaskStatus_t &a, const TaskStatus_t &b)> orderBy) void printRunningTasksMod(Print &printer, std::function<bool(const TaskStatus_t &a, const TaskStatus_t &b)> orderBy)
{ {
static const char *taskStates[] = {"Running", "Ready", "Blocked", "Suspended", "Deleted", "Invalid"}; static const char *taskStates[] = {"Running", "Ready", "Blocked", "Suspended", "Deleted", "Invalid"};
@@ -53,6 +97,75 @@ void printRunningTasksMod(Print &printer, std::function<bool(const TaskStatus_t
ulCurrentRunTime = ulTotalRunTime - ulLastRunTime; ulCurrentRunTime = ulTotalRunTime - ulLastRunTime;
ulLastRunTime = ulTotalRunTime; ulLastRunTime = ulTotalRunTime;
// PRINT MEMORY INFO
printer.printf("\033[H");
printer.printf(COLOR_LBLUE "=================== ESP32 SYSTEM MONITOR ===================\n" COLOR_RESET);
std::string buffer;
time_t now = time(nullptr);
struct tm *t = localtime(&now);
buffer.resize(64);
strftime(buffer.data(), sizeof(buffer), "%Y-%m-%d %H:%M:%S", t);
printer.printf(COLOR_YELLOW "=============== Datetime: %s ===============\n\n" COLOR_RESET, buffer.c_str());
// ===== HEAP =====
size_t freeHeap = esp_get_free_heap_size();
size_t totalHeap = heap_caps_get_total_size(MALLOC_CAP_DEFAULT);
printBar(printer, "HEAP", totalHeap - freeHeap, totalHeap, COLOR_GREEN);
// ===== RAM INTERNA =====
size_t freeInternal = heap_caps_get_free_size(MALLOC_CAP_INTERNAL);
size_t totalInternal = heap_caps_get_total_size(MALLOC_CAP_INTERNAL);
printBar(printer, "INTERNAL", totalInternal - freeInternal, totalInternal, COLOR_BLUE);
// ===== PSRAM =====
size_t totalPsram = heap_caps_get_total_size(MALLOC_CAP_SPIRAM);
if (totalPsram > 0)
{
size_t freePsram = heap_caps_get_free_size(MALLOC_CAP_SPIRAM);
printBar(printer, "PSRAM", totalPsram - freePsram, totalPsram, COLOR_MAGENTA);
}
printer.printf("\n");
// ===== FLASH APP (approssimato) =====
const esp_partition_t *app_partition =
esp_partition_find_first(ESP_PARTITION_TYPE_APP,
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,
ESP_PARTITION_SUBTYPE_DATA_LITTLEFS,
"littlefs");
if (fs_partition)
{
size_t totalFS = fs_partition->size; // dimensione reale partizione
size_t usedFS = LittleFS.usedBytes(); // spazio usato reale
printBar(printer, "LITTLEFS", usedFS, totalFS, COLOR_YELLOW);
}
else
{
printer.printf(COLOR_YELLOW "%-12s [NOT FOUND]\n" COLOR_RESET, "LITTLEFS");
}
// ===== 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);
// Print Runtime Information // Print Runtime Information
printer.printf("Tasks: %u, Runtime: %lus, Period: %luus\r\n", uxArraySize, ulTotalRunTime / 1000000, ulCurrentRunTime); printer.printf("Tasks: %u, Runtime: %lus, Period: %luus\r\n", uxArraySize, ulTotalRunTime / 1000000, ulCurrentRunTime);
@@ -79,4 +192,3 @@ void printRunningTasksMod(Print &printer, std::function<bool(const TaskStatus_t
} }
printer.println(); printer.println();
} }
+95 -27
View File
@@ -1,7 +1,22 @@
#include <webserver.h> #include <webserver.h>
#include <ArduinoJson.h>
WebPage::WebPage(const uint8_t port, fs::FS &filesystem) : m_port(port), m_webserver(AsyncWebServer(port)), m_websocket(AsyncWebSocket("/ws")), m_filesystem(filesystem) static std::map<const std::string, AstroWebServer::c_commandEnum> s_webserverCommands = {
{"setTime", AstroWebServer::SET_TIME},
};
void on_ping(TimerHandle_t xTimer)
{ {
if (!xTimer)
return;
auto ws = (AsyncWebSocket *)pvTimerGetTimerID(xTimer);
ws->pingAll();
ws->cleanupClients();
}
AstroWebServer::AstroWebServer(const uint8_t port, fs::FS &filesystem) : m_port(port), m_webserver(AsyncWebServer(port)), m_websocket(AsyncWebSocket("/ws")), m_filesystem(filesystem)
{
LOG_DEBUG("Initializing Web Server");
m_websocket.onEvent([this](AsyncWebSocket *server, AsyncWebSocketClient *client, m_websocket.onEvent([this](AsyncWebSocket *server, AsyncWebSocketClient *client,
AwsEventType type, void *arg, uint8_t *data, size_t len) AwsEventType type, void *arg, uint8_t *data, size_t len)
{ onWsEvent(server, client, type, arg, data, len); }); { onWsEvent(server, client, type, arg, data, len); });
@@ -9,61 +24,114 @@ WebPage::WebPage(const uint8_t port, fs::FS &filesystem) : m_port(port), m_webse
m_webserver.addHandler(&m_websocket); m_webserver.addHandler(&m_websocket);
m_webserver.serveStatic("/", m_filesystem, "/").setDefaultFile("index.html"); m_webserver.serveStatic("/", m_filesystem, "/").setDefaultFile("index.html");
m_webserver.on("/upload", HTTP_POST, m_webserver.on("/upload", HTTP_POST, [this](AsyncWebServerRequest *request)
[this](AsyncWebServerRequest *request) { onUploadRequest(request); }, [this](AsyncWebServerRequest *request, const String &filename, size_t index, uint8_t *data, size_t len, bool final)
{ onUploadRequest(request); }, { onUploadHandler(request, filename, index, data, len, final); });
[this](AsyncWebServerRequest *request, const String &filename, size_t index, uint8_t *data, size_t len, bool final)
{ onUploadHandler(request, filename, index, data, len, final); }
);
m_webserver.begin(); m_webserver.begin();
m_websocket.enable(true);
m_pingTimer = xTimerCreate("wsPingTimer", pdMS_TO_TICKS(2000), pdTRUE, (void *)&m_websocket, on_ping);
LOG_DEBUG("Webserver Init OK");
} }
WebPage::~WebPage() AstroWebServer::~AstroWebServer()
{ {
xTimerDelete(m_pingTimer, pdMS_TO_TICKS(10));
m_webserver.removeHandler(&m_websocket); m_webserver.removeHandler(&m_websocket);
m_webserver.end(); m_webserver.end();
} }
void WebPage::sendWsData(const String &data){ void AstroWebServer::sendWsData(const String &data)
if (m_websocket.count()){ {
if (m_websocket.count())
{
m_websocket.textAll(data); m_websocket.textAll(data);
} }
} }
void WebPage::onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) void AstroWebServer::onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len)
{ {
switch (type) switch (type)
{ {
case WS_EVT_CONNECT: case WS_EVT_CONNECT:
Serial.printf("WS client IP[%s]-ID[%u] CONNECTED\r\n", client->remoteIP().toString().c_str(), client->id()); LOG_DEBUG("WS client IP[", client->remoteIP().toString().c_str(), "]-ID[", client->id(), "] CONNECTED");
break; break;
case WS_EVT_DISCONNECT: case WS_EVT_DISCONNECT:
Serial.printf("WS client ID[%u] DISCONNECTED\r\n", client->remoteIP().toString().c_str(), client->id()); LOG_DEBUG("WS client IP[", client->remoteIP().toString().c_str(), "]-ID[", client->id(), "] DISCONNECTED");
break; break;
case WS_EVT_PONG:
LOG_DEBUG("WS client IP[", client->remoteIP().toString().c_str(), "]-ID[", client->id(), "] PONG");
break;
case WS_EVT_DATA:
{
AwsFrameInfo *info = (AwsFrameInfo *)arg;
if (info->final && info->index == 0 && info->len == len)
{
std::string data_str((char *)data, len);
ArduinoJson::JsonDocument doc;
if (auto rv = ArduinoJson::deserializeJson(doc, data_str) != ArduinoJson::DeserializationError::Ok)
{
LOG_ERROR("WS Client unable to deserialize Json");
return;
}
if (!doc["cmd"].is<std::string>() || !s_webserverCommands.contains(doc["cmd"]))
{
LOG_WARN("WS Client Invalid Json command [", doc["cmd"].as<std::string>().c_str(), "]");
return;
}
std::string buffer;
switch (s_webserverCommands.at(doc["cmd"]))
{
case SET_TIME:
{
auto epoch = doc["time"].as<time_t>();
timeval te{
.tv_sec = epoch,
.tv_usec = 0,
};
timezone tz{
.tz_minuteswest = 0,
.tz_dsttime = DST_MET,
};
settimeofday(&te, &tz);
time_t now = time(nullptr);
struct tm *t = localtime(&now);
buffer.resize(64);
strftime(buffer.data(), sizeof(buffer), "%Y-%m-%d %H:%M:%S", t);
LOG_DEBUG("WS Client set Datetime to: ", buffer.c_str());
break;
}
default:
// call external command callback
break;
}
}
}
} }
} }
void WebPage::onUploadRequest(AsyncWebServerRequest *request) void AstroWebServer::onUploadRequest(AsyncWebServerRequest *request)
{ {
if (m_upload_failed) if (m_uploadFailed)
request->send(500, "text/plain", "Upload failed"); request->send(500, "text/plain", "Upload failed");
else else
request->send(200, "text/plain", "Upload successful"); request->send(200, "text/plain", "Upload successful");
} }
void WebPage::onUploadHandler(AsyncWebServerRequest *request, const String &filename, size_t index, uint8_t *data, size_t len, bool final) void AstroWebServer::onUploadHandler(AsyncWebServerRequest *request, const String &filename, size_t index, uint8_t *data, size_t len, bool final)
{ {
if (index == 0) // only on first iteration to open file if (index == 0) // only on first iteration to open file
{ {
m_upload_failed = false; m_uploadFailed = false;
String safeName = filename; String safeName = filename;
int slashIndex = safeName.lastIndexOf('/'); int slashIndex = safeName.lastIndexOf('/');
if (slashIndex >= 0) if (slashIndex >= 0)
safeName = safeName.substring(slashIndex + 1); safeName = safeName.substring(slashIndex + 1);
if (safeName.length() == 0) if (safeName.length() == 0)
{ {
m_upload_failed = true; m_uploadFailed = true;
LOG_ERROR("Invalid file name"); LOG_ERROR("Invalid file name");
return; return;
} }
@@ -72,27 +140,27 @@ void WebPage::onUploadHandler(AsyncWebServerRequest *request, const String &file
if (m_filesystem.exists(filePath.c_str())) if (m_filesystem.exists(filePath.c_str()))
m_filesystem.remove(filePath.c_str()); m_filesystem.remove(filePath.c_str());
m_upload_file = m_filesystem.open(filePath.c_str(), FILE_WRITE); m_uploadFile = m_filesystem.open(filePath.c_str(), FILE_WRITE);
if (!m_upload_file) if (!m_uploadFile)
{ {
m_upload_failed = true; m_uploadFailed = true;
LOG_ERROR("Failed to open upload file:", filePath.c_str()); LOG_ERROR("Failed to open upload file:", filePath.c_str());
return; return;
} }
} }
// Actual write of file data // Actual write of file data
if (!m_upload_failed && m_upload_file) if (!m_uploadFailed && m_uploadFile)
{ {
if (m_upload_file.write(data, len) != len) if (m_uploadFile.write(data, len) != len)
m_upload_failed = true; m_uploadFailed = true;
} }
// close the file and save on final call // close the file and save on final call
if (final && m_upload_file) if (final && m_uploadFile)
{ {
m_upload_file.close(); m_uploadFile.close();
if (!m_upload_failed) if (!m_uploadFailed)
LOG_INFO("Uploaded file to LittleFS:", filename.c_str()); LOG_INFO("Uploaded file to LittleFS:", filename.c_str());
} }
} }
+20 -10
View File
@@ -1,5 +1,5 @@
#pragma once #pragma once
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO #define DEBUGLOG_DEFAULT_LOG_LEVEL_DEBUG
// System includes // System includes
#include <Arduino.h> #include <Arduino.h>
@@ -7,20 +7,16 @@
#include <ESPAsyncWebServer.h> #include <ESPAsyncWebServer.h>
#include <AsyncTCP.h> #include <AsyncTCP.h>
#include <filesystem> #include <filesystem>
#include <map>
#include <FS.h> #include <FS.h>
class WebPage class AstroWebServer
{ {
const uint8_t m_port = 80;
fs::FS &m_filesystem;
AsyncWebServer m_webserver;
AsyncWebSocket m_websocket;
bool m_upload_failed = false;
fs::File m_upload_file;
public: public:
WebPage(const uint8_t port, fs::FS &filesystem); AstroWebServer(const uint8_t port, fs::FS &filesystem);
~WebPage(); ~AstroWebServer();
void sendWsData(const String &data); void sendWsData(const String &data);
@@ -35,4 +31,18 @@ private:
void onStop(AsyncWebServerRequest *request); void onStop(AsyncWebServerRequest *request);
void onDownload(AsyncWebServerRequest *request); void onDownload(AsyncWebServerRequest *request);
private:
const uint8_t m_port = 80;
fs::FS &m_filesystem;
AsyncWebServer m_webserver;
AsyncWebSocket m_websocket;
bool m_uploadFailed = false;
fs::File m_uploadFile;
TimerHandle_t m_pingTimer = NULL;
public:
enum c_commandEnum
{
SET_TIME
};
}; };