#include <OneWire.h>
#include <DallasTemperature.h>
#include <SPI.h>
#include <SD.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <math.h>
#include <string.h>
// ---------------- Project configuration ----------------
#define NUM_SITES 3
#define SAMPLE_INTERVAL_MS 5000UL
#define SD_CS_PIN 49
#define RADIO_CS_PIN 48
#define RADIO_RESET_PIN 47
#define RADIO_DIO0_PIN 46
// SX1276 register addresses
#define REG_FIFO 0x00
#define REG_OP_MODE 0x01
#define REG_FRF_MSB 0x06
#define REG_FRF_MID 0x07
#define REG_FRF_LSB 0x08
#define REG_PA_CONFIG 0x09
#define REG_FIFO_ADDR_PTR 0x0D
#define REG_FIFO_TX_BASE 0x0E
#define REG_IRQ_FLAGS 0x12
#define REG_MODEM_CONFIG1 0x1D
#define REG_MODEM_CONFIG2 0x1E
#define REG_PREAMBLE_MSB 0x20
#define REG_PREAMBLE_LSB 0x21
#define REG_PAYLOAD_LENGTH 0x22
#define REG_MODEM_CONFIG3 0x26
#define REG_SYNC_WORD 0x39
#define REG_VERSION 0x42
#define IRQ_TX_DONE 0x08
LiquidCrystal_I2C lcd(0x27, 16, 2);
// ---------------- Sensor pin mapping ----------------
struct Site {
const char* name;
byte tempPin;
byte phPin;
byte ecPin;
byte turbPin;
byte lightPin;
byte ledPin;
};
Site sites[NUM_SITES] = {
{"UPSTREAM", 3, A1, A2, A3, A10, 22},
{"MIDSTREAM", 4, A4, A5, A6, A11, 23},
{"DOWNSTREAM", 5, A7, A8, A9, A12, 24}
};
OneWire* oneWireBus[NUM_SITES];
DallasTemperature* tempSensor[NUM_SITES];
unsigned long lastSample = 0;
unsigned long packetCounter = 0;
bool sdReady = false;
bool radioReady = false;
// ---------------- Sensor conversion functions ----------------
// pH custom chip model:
// pH 0..14 maps linearly to 0..5V.
// This is a behavioral simulation, not a calibrated probe model.
float readPH(byte pin) {
return analogRead(pin) * (14.0f / 1023.0f);
}
// EC custom chip model:
// EC 0..5 mS/cm maps linearly to 0..5V.
float readEC(byte pin) {
return analogRead(pin) * (5.0f / 1023.0f);
}
// Turbidity custom chip model:
// Vout = 5 - NTU/600.
// This is an illustrative model, not a calibrated sensor curve.
float readTurbidity(byte pin) {
float voltage = analogRead(pin) * (5.0f / 1023.0f);
float ntu = (5.0f - voltage) * 600.0f;
return constrain(ntu, 0.0f, 3000.0f);
}
// Approximate lux conversion for the Wokwi photoresistor model.
float readLightLux(byte pin) {
const float GAMMA = 0.7f;
const float RL10 = 50.0f;
float adc = analogRead(pin);
float voltage = adc / 1023.0f * 5.0f;
if (voltage <= 0.001f) return 0.0f;
if (voltage >= 4.999f) return 100000.0f;
float resistance = 2000.0f * voltage / (5.0f - voltage);
float lux = powf(
(RL10 * 1000.0f * powf(10.0f, GAMMA)) / resistance,
1.0f / GAMMA
);
if (!isfinite(lux) || lux < 0) return 0.0f;
return lux;
}
// Demonstration thresholds only.
// These are NOT a drinking-water safety assessment.
bool valuesWithinDemoLimits(float ph, float ec, float turbidity) {
return ph >= 6.5f &&
ph <= 8.5f &&
ec <= 2.0f &&
turbidity <= 5.0f;
}
// ---------------- SX1276 SPI functions ----------------
void radioWrite(uint8_t address, uint8_t value) {
digitalWrite(RADIO_CS_PIN, LOW);
SPI.transfer(address | 0x80);
SPI.transfer(value);
digitalWrite(RADIO_CS_PIN, HIGH);
}
uint8_t radioRead(uint8_t address) {
digitalWrite(RADIO_CS_PIN, LOW);
SPI.transfer(address & 0x7F);
uint8_t value = SPI.transfer(0x00);
digitalWrite(RADIO_CS_PIN, HIGH);
return value;
}
void radioBurstWrite(
uint8_t address,
const uint8_t* data,
uint8_t length
) {
digitalWrite(RADIO_CS_PIN, LOW);
SPI.transfer(address | 0x80);
for (uint8_t i = 0; i < length; i++) {
SPI.transfer(data[i]);
}
digitalWrite(RADIO_CS_PIN, HIGH);
}
// Initialize the SX1276 SPI register emulator.
bool radioBegin() {
pinMode(RADIO_CS_PIN, OUTPUT);
pinMode(RADIO_RESET_PIN, OUTPUT);
pinMode(RADIO_DIO0_PIN, INPUT);
digitalWrite(RADIO_CS_PIN, HIGH);
// Hardware reset sequence
digitalWrite(RADIO_RESET_PIN, LOW);
delay(5);
digitalWrite(RADIO_RESET_PIN, HIGH);
delay(10);
// Read SX1276 version register.
uint8_t version = radioRead(REG_VERSION);
Serial.print("RADIO,SX1276_VERSION,0x");
Serial.println(version, HEX);
if (version != 0x12) {
return false;
}
// Enter LoRa sleep, then standby.
radioWrite(REG_OP_MODE, 0x80);
delay(2);
radioWrite(REG_OP_MODE, 0x81);
// Frequency configuration: 868.1 MHz.
// This is a register configuration only; no RF is transmitted.
const uint32_t frf =
(uint32_t)((868100000.0 * 524288.0) / 32000000.0);
radioWrite(REG_FRF_MSB, (frf >> 16) & 0xFF);
radioWrite(REG_FRF_MID, (frf >> 8) & 0xFF);
radioWrite(REG_FRF_LSB, frf & 0xFF);
// LoRa modem configuration.
radioWrite(REG_PA_CONFIG, 0x8F);
radioWrite(REG_FIFO_TX_BASE, 0x00);
radioWrite(REG_FIFO_ADDR_PTR, 0x00);
// BW = 125 kHz, CR = 4/5, explicit header.
radioWrite(REG_MODEM_CONFIG1, 0x72);
// SF7 and payload CRC enabled.
radioWrite(REG_MODEM_CONFIG2, 0x74);
// Automatic gain control.
radioWrite(REG_MODEM_CONFIG3, 0x04);
// Preamble length = 8 symbols.
radioWrite(REG_PREAMBLE_MSB, 0x00);
radioWrite(REG_PREAMBLE_LSB, 0x08);
// LoRa sync word.
radioWrite(REG_SYNC_WORD, 0x12);
// Clear pending interrupt flags.
radioWrite(REG_IRQ_FLAGS, 0xFF);
// Return to standby.
radioWrite(REG_OP_MODE, 0x81);
Serial.println(
"RADIO,CONFIG_OK,LoRa,SF7,BW125kHz,CR4/5,868.1MHz"
);
return true;
}
// Send a payload to the emulator FIFO.
// TxDone is generated by the custom chip emulator,
// not by a real wireless transmission.
bool radioSendSimulated(const char* payload) {
if (!radioReady) return false;
uint8_t length = (uint8_t)strlen(payload);
if (length == 0 || length > 64) {
return false;
}
// Standby mode.
radioWrite(REG_OP_MODE, 0x81);
// Reset FIFO pointer.
radioWrite(REG_FIFO_ADDR_PTR, 0x00);
// Write payload bytes to FIFO.
radioBurstWrite(
REG_FIFO,
(const uint8_t*)payload,
length
);
// Set payload length.
radioWrite(REG_PAYLOAD_LENGTH, length);
// Clear previous IRQ flags.
radioWrite(REG_IRQ_FLAGS, 0xFF);
// Set TX mode.
// The custom chip emulator raises simulated TxDone.
radioWrite(REG_OP_MODE, 0x83);
bool txDone = false;
for (uint8_t tries = 0; tries < 20; tries++) {
if (
digitalRead(RADIO_DIO0_PIN) == HIGH ||
(radioRead(REG_IRQ_FLAGS) & IRQ_TX_DONE)
) {
txDone = true;
break;
}
delay(1);
}
// Read and clear IRQ flags.
uint8_t irq = radioRead(REG_IRQ_FLAGS);
radioWrite(REG_IRQ_FLAGS, irq);
// Return radio to standby.
radioWrite(REG_OP_MODE, 0x81);
return txDone;
}
// ---------------- SD card logging ----------------
void createLogFileIfNeeded() {
if (!sdReady) return;
if (!SD.exists("river_log.csv")) {
File file = SD.open("river_log.csv", FILE_WRITE);
if (file) {
file.println(
"cycle,packet,node,temp_C,pH,EC_mS_cm,"
"turbidity_NTU_demo,light_lux,status,radio"
);
file.close();
}
}
}
void logToSD(
unsigned long cycle,
unsigned long packet,
const Site& site,
float temp,
float ph,
float ec,
float turbidity,
float lux,
bool normal
) {
if (!sdReady) return;
File file = SD.open("river_log.csv", FILE_WRITE);
if (!file) {
Serial.println("GATEWAY,SD_WRITE_ERROR");
return;
}
file.print(cycle);
file.print(',');
file.print(packet);
file.print(',');
file.print(site.name);
file.print(',');
file.print(temp, 2);
file.print(',');
file.print(ph, 2);
file.print(',');
file.print(ec, 3);
file.print(',');
file.print(turbidity, 1);
file.print(',');
file.print(lux, 1);
file.print(',');
file.print(
normal ? "WITHIN_DEMO_LIMITS" : "CHECK_READING"
);
file.print(',');
file.println(
radioReady ? "SPI_EMULATED_TX" : "RADIO_UNAVAILABLE"
);
file.close();
}
// ---------------- LCD gateway display ----------------
void showGatewayLCD(
const Site& site,
float ph,
float temp
) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(site.name);
lcd.setCursor(0, 1);
lcd.print("pH:");
lcd.print(ph, 1);
lcd.print(" T:");
lcd.print(temp, 1);
}
// ---------------- Gateway packet processing ----------------
void processGatewayPacket(
unsigned long cycle,
const Site& site,
float temp,
float ph,
float ec,
float turbidity,
float lux
) {
packetCounter++;
bool valid =
isfinite(temp) &&
temp > -50.0f &&
temp < 100.0f &&
ph >= 0.0f &&
ph <= 14.0f &&
ec >= 0.0f &&
ec <= 5.0f &&
turbidity >= 0.0f &&
turbidity <= 3000.0f;
if (!valid) {
Serial.print("GATEWAY,PACKET_REJECTED,");
Serial.println(site.name);
return;
}
bool normal = valuesWithinDemoLimits(
ph,
ec,
turbidity
);
// Compact application payload.
char packet[64];
snprintf(
packet,
sizeof(packet),
"%lu,%s,%.2f,%.3f,%.1f,%.1f",
packetCounter,
site.name,
temp,
ph,
ec,
turbidity
);
bool txDone = radioSendSimulated(packet);
Serial.print("GATEWAY,PROCESS_OK,cycle=");
Serial.print(cycle);
Serial.print(",packet=");
Serial.print(packetCounter);
Serial.print(",node=");
Serial.print(site.name);
Serial.print(",temp_C=");
Serial.print(temp, 2);
Serial.print(",pH=");
Serial.print(ph, 2);
Serial.print(",EC_mS_cm=");
Serial.print(ec, 3);
Serial.print(",turbidity_NTU_demo=");
Serial.print(turbidity, 1);
Serial.print(",light_lux=");
Serial.print(lux, 1);
Serial.print(",status=");
Serial.print(
normal ? "WITHIN_DEMO_LIMITS" : "CHECK_READING"
);
Serial.print(",SPI_TxDone=");
Serial.println(txDone ? "YES_SIMULATED" : "NO");
// Store the received/processed sample.
logToSD(
cycle,
packetCounter,
site,
temp,
ph,
ec,
turbidity,
lux,
normal
);
showGatewayLCD(site, ph, temp);
}
// ---------------- Sampling each monitoring location ----------------
void sampleAndForwardSite(
byte index,
unsigned long cycle
) {
Site& site = sites[index];
// Read temperature.
tempSensor[index]->requestTemperatures();
float temp =
tempSensor[index]->getTempCByIndex(0);
if (temp == DEVICE_DISCONNECTED_C) {
Serial.print("SENSOR_ERROR,DS18B20,");
Serial.println(site.name);
temp = -127.0f;
}
// Read analog sensors.
float ph = readPH(site.phPin);
float ec = readEC(site.ecPin);
float turbidity = readTurbidity(site.turbPin);
float lux = readLightLux(site.lightPin);
// Evaluate demonstration thresholds.
bool normal = valuesWithinDemoLimits(
ph,
ec,
turbidity
);
// LED ON means reading needs checking.
digitalWrite(
site.ledPin,
normal ? LOW : HIGH
);
// Print sensor data.
Serial.print("NODE,SAMPLE,");
Serial.print(site.name);
Serial.print(",pH=");
Serial.print(ph, 2);
Serial.print(",EC=");
Serial.print(ec, 3);
Serial.print(",Turbidity_NTU_demo=");
Serial.print(turbidity, 1);
Serial.print(",Temp_C=");
Serial.print(temp, 2);
Serial.print(",Light_lux=");
Serial.println(lux, 1);
// Process data at the gateway emulator.
processGatewayPacket(
cycle,
site,
temp,
ph,
ec,
turbidity,
lux
);
}
// ---------------- Setup ----------------
void setup() {
Serial.begin(115200);
Wire.begin();
SPI.begin();
// Initialize LCD.
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("River Monitor");
lcd.setCursor(0, 1);
lcd.print("Starting...");
// Initialize the three logical sensor locations.
for (byte i = 0; i < NUM_SITES; i++) {
pinMode(sites[i].ledPin, OUTPUT);
digitalWrite(sites[i].ledPin, LOW);
oneWireBus[i] = new OneWire(sites[i].tempPin);
tempSensor[i] =
new DallasTemperature(oneWireBus[i]);
tempSensor[i]->begin();
}
// Keep Mega hardware SS configured as output.
pinMode(53, OUTPUT);
// Configure independent SPI chip-select pins.
pinMode(SD_CS_PIN, OUTPUT);
digitalWrite(SD_CS_PIN, HIGH);
pinMode(RADIO_CS_PIN, OUTPUT);
digitalWrite(RADIO_CS_PIN, HIGH);
// Initialize radio emulator.
radioReady = radioBegin();
Serial.println(
radioReady
? "RADIO,READY,SPI_REGISTER_EMULATOR"
: "RADIO,INIT_FAILED,CHECK_VERSION_AND_WIRING"
);
// Initialize SD card.
sdReady = SD.begin(SD_CS_PIN);
if (sdReady) {
Serial.println("GATEWAY,SD_CARD_READY");
createLogFileIfNeeded();
} else {
Serial.println("GATEWAY,SD_CARD_INIT_FAILED");
}
Serial.println();
Serial.println("RIVER WATER QUALITY MONITORING");
Serial.println("3 logical sites on one Mega board");
Serial.println("Gateway: software emulation on Mega");
Serial.println(
"SX1276: SPI register emulator; "
"TxDone is simulated, no RF link"
);
Serial.println(
"SD log: river_log.csv | Sampling: 5 seconds"
);
Serial.println("----------------------------------------");
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Gateway Ready");
lcd.setCursor(0, 1);
lcd.print(
sdReady ? "SD OK / 3 nodes" : "SD ERROR"
);
lastSample = millis() - SAMPLE_INTERVAL_MS;
}
// ---------------- Main loop ----------------
void loop() {
if (millis() - lastSample >= SAMPLE_INTERVAL_MS) {
lastSample = millis();
unsigned long cycle =
(unsigned long)(millis() / SAMPLE_INTERVAL_MS) + 1;
Serial.println();
Serial.print("=== MONITORING CYCLE ");
Serial.print(cycle);
Serial.println(" ===");
for (byte i = 0; i < NUM_SITES; i++) {
sampleAndForwardSite(i, cycle);
}
Serial.println("=== GATEWAY CYCLE COMPLETE ===");
}
}