I have an issue of transferring sensor data over SPI communication.
I mean the SPI does transfer the value but the sensor not working like it only read 0.
like for example I attach soil moisture sensor on A0 the value it reads is 0 even if I put water in the soil. Is there something I have mess? this the code for sensor
#include <SPI.h>
#include <DHT.h>
const int numSensors = 3;
const int soilMoistureSensor[numSensors] = {A0, A1, A2};
#define DHT_TYPE DHT11
#define DHT_PIN A3
const int lightSensor = A4;
const int masterDataRequest = 2;
DHT dht(DHT_PIN, DHT_TYPE);
int soilMoistVal; int humidityVal; int lightVal;
void setup() {
Serial.begin(9600);
SPI.begin();
dht.begin();
pinMode(SS, INPUT);
pinMode(lightSensor, INPUT);
pinMode(DHT_PIN, INPUT);
for (int s = 0; s < numSensors; s++) {
pinMode(soilMoistureSensor[s], INPUT);
}
pinMode(masterDataRequest, INPUT);
}
void loop() {
if (digitalRead(masterDataRequest) == HIGH) {
// Respond to the master's data request
float humidity = dht.readHumidity();
for (int s = 0; s < numSensors; s++) {
soilMoistVal = analogRead(soilMoistureSensor[s]);
}
humidityVal = analogRead(DHT_PIN);
lightVal = analogRead(lightSensor);
// Wait for the master to deselect
while (digitalRead(SS) == HIGH);
// Send the sensor data to the master
SPI.transfer(soilMoistVal >> 8);
SPI.transfer(soilMoistVal & 0xFF);
SPI.transfer(humidityVal >> 8);
SPI.transfer(humidityVal & 0xFF);
SPI.transfer(lightVal >> 8);
SPI.transfer(lightVal & 0xFF);
// Wait for the master to finish
while (digitalRead(SS) == LOW);
}
Serial.print("Soil Moisture: " + String(soilMoistVal) + " | ");
Serial.println("Humidity: " + String(humidityVal));
Serial.println("Light: " + String(lightVal));
delay(1000);
}
this is the for the master
#include <SPI.h>
const int sensorsDataRequest = 2;
void setup() {
Serial.begin(9600);
SPI.begin();
pinMode(SS, OUTPUT);
pinMode(sensorsDataRequest, OUTPUT);
}
void loop() {
// Request sensor data from the sensor node
digitalWrite(sensorsDataRequest, HIGH);
delay(1);
digitalWrite(sensorsDataRequest, LOW);
// Select the control node
digitalWrite(SS, LOW);
// Send a request to the sensor node
SPI.transfer('R');
// Receive sensor data from the sensor node
int soilMoistureVal = (SPI.transfer(0) << 8) | SPI.transfer(0);
int humidityVal = (SPI.transfer(0) << 8) | SPI.transfer(0);
int lightVal = (SPI.transfer(0) << 8) | SPI.transfer(0);
// Deselect the control node
digitalWrite(SS, HIGH);
Serial.println("Received Sensor Data:");
Serial.println("Soil Moisture: " + String(soilMoistureVal));
Serial.println("Humidity: " + String(humidityVal));
Serial.println("Light: " + String(lightVal));
delay(1000);
}
