Final Arduino Code For Temperature Control

 Final Arduino Code For Temperature Control

The code below is the finalised version for the temperature-controlled prototype, designed to read the temperature data from the DHT22 sensor installed inside the lid of the temperature-controlled protype. It incorporates thresholds for both lower and upper temperature limits, allowing for precise temperature control within the composting environment. These thresholds are modulated, enabling users to adjust the temperature limits according to the specific requirements of different composting materials. This flexibility ensures that the prototype can be tailored to suit various composting needs, enhancing its usability and versatility.

Collaborating closely with Michael Margolis, whose expertise in Arduino systems has been invaluable, this code has undergone refinement and optimisation. As my second advisor, Michael's guidance has broadened my understanding of the capabilities of Arduino Uno microcontrollers and expanded my knowledge of coding practices. His insights have played a pivotal role in the development of the control system for the temperature-controlled prototype, ensuring its effectiveness and reliability in regulating composting temperatures.

This collaborative effort underscores the importance of seeking expertise and leveraging external support to enhance project outcomes. By drawing on the knowledge and experience of industry professionals like Michael Margolis, I have been able to elevate the sophistication and functionality of the temperature-controlled prototype, laying the groundwork for its successful implementation in real-world composting applications.

The code for the temperature-controlled prototype incorporates humidity-checking capabilities, enhancing its functionality beyond temperature regulation alone. By integrating humidity monitoring into the control system, users can gain valuable insights into the moisture levels of the composting material. This feature enables the prototype to provide real-time feedback on the moisture content, allowing users to make informed adjustments to achieve optimal composting conditions.


Final Code


#include <DHT22.h>
#include <SPI.h>
#include <SD.h>
#include <Wire.h>

/*
  MM modified to change pins to match latest hardware
  temperature range and interval reduced to aid initial testing
  Logging now include indication of pin state change
  changed logging interval to 1 minute
*/

// Define the type of DHT sensor and the pin it's connected to
#define DHTPIN  2       // Digital pin for DHT sensor
#define DHTTYPE DHT22   // DHT 22 (AM2302) sensor type

// Create a DHT object
DHT22 dht(DHTPIN);

// Define temperature thresholds
const float lowerThreshold = 22.00;  // Define lower temperature threshold (adjust as needed)
const float upperThreshold = 26.00;  // Define upper temperature threshold (adjust as needed)

// Define file name for temperature log
const char* fileName = "datalog.csv"; // CSV format for Excel

// Define interval for logging temperature (in milliseconds)
const unsigned long loggingInterval = 1 * 60 * 1000L; // 1 minute

// Variables to track logging time
unsigned long previousMillis = 0;

// File object for temperature log
File logFile;

// Pin for controlling the smart plug
const int smartPlugPin =  8;  // was 17

void setup() {
  // Initialize serial communication
  Serial.begin(9600);
  Serial.print("Starting DHT logger, lower threshold is "); Serial.print(lowerThreshold);
  Serial.print(", upper threshold is ");  Serial.println(upperThreshold);
  Serial.print("logging interval minutes is "); Serial.println(int(loggingInterval / 60000));

  //dht.begin();  // Initialize the DHT sensor
  Wire.begin(); // Initialize RTC communication

  // Initialize SD card
  if (!SD.begin()) {
    Serial.println("Failed to initialize SD card!");
    return;
  }

  // Open the temperature log file
  logFile = SD.open(fileName, FILE_WRITE);
  if (!logFile) {
    Serial.println("Failed to open temperature log file!");
    return;
  }

  // Write header to log file
  logFile.println("Timestamp, Temperature (C), PinState");
  logFile.close(); // Close the file

  // Set smart plug pin as output
  pinMode(smartPlugPin, OUTPUT);
}

void loop() {
  // Check if it's time to log temperature
  unsigned long currentMillis = millis();
  char pinState;

  if (currentMillis - previousMillis >= loggingInterval) {
    // Update previousMillis
    previousMillis = currentMillis;

    // Read temperature from DHT sensor
    float temperature = dht.getTemperature();

    // Check temperature thresholds and control smart plug
    if (temperature < lowerThreshold) {
      // Activate heating
      digitalWrite(smartPlugPin, HIGH);
      pinState = 'H';
      Serial.print("smartplug pin is HIGH: ");
    } else if (temperature > upperThreshold) {
      // Deactivate heating
      digitalWrite(smartPlugPin, LOW);
      Serial.print("smartplug pin LOW: ");
      pinState = 'L';
    }
    else {
      pinState = ' ';
    }

    // Log temperature to SD card
    logTemperature(temperature, pinState );
    Serial.print("temperature is "); Serial.println(temperature);
  }
}

// Function to log temperature onto SD card (and pin state)
void logTemperature(float temperature, char pinState) {
  // Open the temperature log file
  logFile = SD.open(fileName, FILE_WRITE);
  if (logFile) {
    // Get current time
    unsigned long currentTime = millis();

    // Print temperature to serial monitor
    String dateTime = rtcDateTime();
    Serial.print(dateTime);
    Serial.print(" Temperature logged: ");
    Serial.println(temperature);

    // Write temperature and timestamp to log file in CSV format
    logFile.print(dateTime);
    logFile.print(", ");
    logFile.print(temperature);
    logFile.print(", ");
    logFile.println(pinState);

    // Close the file
    logFile.close();
  } else {
    // If the file didn't open, print an error to the serial monitor
    Serial.println("Error opening temperature log file!");
  }
}

#define DS1307_ADDRESS 0x68

String rtcDateTime() {
  byte second, minute, hour, dayOfMonth, month, year;

  // Start I2C Transmission
  Wire.beginTransmission(DS1307_ADDRESS);
  Wire.write((byte)0); // Set DS1307 register pointer to 00h
  Wire.endTransmission();

  // Request 7 bytes of data starting from register 00h
  Wire.requestFrom(DS1307_ADDRESS, 7);

  if (Wire.available() == 7) {
    second = bcdToDec(Wire.read() & 0x7F);
    minute = bcdToDec(Wire.read());
    hour = bcdToDec(Wire.read() & 0x3F); // 24-hour format
    Wire.read(); // Skip day of week
    dayOfMonth = bcdToDec(Wire.read());
    month = bcdToDec(Wire.read());
    year = bcdToDec(Wire.read());
  }

  // Format date and time into a terse string: "YYMMDD-HHMMSS"
  char dateTimeStr[14];
  sprintf(dateTimeStr, "%02d%02d%02d-%02d%02d%02d", year, month, dayOfMonth, hour, minute, second);
  return String(dateTimeStr);
}

// Convert Binary Coded Decimal (BCD) to Decimal
byte bcdToDec(byte val) {
  return (val / 16 * 10) + (val % 16);
}

Comments

Popular posts from this blog

Overall Literature Review So Far from The Research I Have Done

Trip To Sackers Waste Management Claydon, Suffolk

Final Video Of The Temperature Controlled Prototype