#include <math.h>
int pinA = 4; // First digital pin (Most Significant Bit)
int pinB = 5; // Second digital pin
int pinC = 6; // Third digital pin
int pinD = 7; // Fourth digital pin (Least Significant Bit)
int value;
const int analogPin = A0; // Analog pin to read data
const int numChannels = 4; // Total number of channels
int analogValues[numChannels]; // Array to store analog values
float tdsValue;
float phValue;
float turbidityValue;
void setup() {
Serial.begin(115200); // Initialize serial communication
// Initialize pins
pinMode(pinA, OUTPUT);
pinMode(pinB, OUTPUT);
pinMode(pinC, OUTPUT);
pinMode(pinD, OUTPUT);
}
void loop() {
// Read and store analog values for all channels
for (int a = 0; a < numChannels; a++) {
value = a;
// Convert the value to binary and output to the pins
digitalWrite(pinA, bitRead(value, 0)); // Most significant bit
digitalWrite(pinB, bitRead(value, 1));
digitalWrite(pinC, bitRead(value, 2));
digitalWrite(pinD, bitRead(value, 3)); // Least significant bit
delay(1000); // Allow the analog multiplexer to stabilize
// Read the analog value and store it in the array
analogValues[a] = analogRead(analogPin);
}
// Assign sensor values
int pHvoltage = analogValues[0];
int tdsvoltage = analogValues[1];
int turbidityvoltage = analogValues[2];
// Calculate sensor values
phValue = pH_Calculet(pHvoltage);
tdsValue = tds_calculet(tdsvoltage);
turbidityValue = turbidity_calculet(turbidityvoltage);
// Print sensor values
Serial.print("pH: ");
Serial.println(phValue, 2);
Serial.print("TDS: ");
Serial.print(tdsValue, 2);
Serial.println(" ppm");
Serial.print("Turbidity: ");
Serial.print(turbidityValue, 2);
Serial.println(" NTU");
delay(1000); // Add delay to make readings human-readable
}
float pH_Calculet(int pHvoltage) {
long sensorSum = 0; // Initialize the sum
for (int m = 0; m < 50; m++) {
sensorSum += pHvoltage; // Accumulate pH voltage readings
}
float sensorValue = sensorSum / 50.0; // Calculate the average
float phValue = 7 - (1000 * (sensorValue - 372) * 4.98 / 59.16 / 1023);
return phValue;
}
float tds_calculet(int tdsvoltage) {
float Voltage = tdsvoltage * 5.0 / 1023.0; // Convert analog reading to Voltage
float tdsValue = (133.42 * Voltage * Voltage * Voltage - 255.86 * Voltage * Voltage + 857.39 * Voltage) * 0.5; // TDS formula
return tdsValue;
}
float turbidity_calculet(int turbidityvoltage) {
float volt = 0;
for (int i = 0; i < 800; i++) {
volt += (float)turbidityvoltage / 1023 * 5.0;
}
volt = volt / 800; // Calculate the average voltage
volt = round_to_dp(volt, 2); // Round to 2 decimal places
if (volt < 2.5) {
turbidityValue = 3000; // High turbidity case
} else {
turbidityValue = -1120.4 * (volt * volt) + 5742.3 * volt - 4353.8; // Turbidity formula
}
return turbidityValue;
}
float round_to_dp(float in_value, int decimal_place) {
float multiplier = pow(10.0, decimal_place);
return round(in_value * multiplier) / multiplier;
}
Loading
cd74hc4067
cd74hc4067