Untitled

mail@pastecode.io avatar
unknown
plain_text
11 days ago
2.2 kB
1
Indexable
Never
#include <SPI.h>
#include <SD.h>

const int chipSelect = 10; // SD card chip select pin for the Adafruit Data Logger Shield
const int analogPin = A0; // Pin where the AD590 with 10k resistor is connected
const float resistorValue = 10000.0; // Resistor value in ohms (10kΩ)
const float measuredVref = 5.0; // Replace with the actual measured reference voltage if different

File dataFile;

void setup() {
  // Start serial communication for debugging
  Serial.begin(9600);

  // Initialize the SD card
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    while (1);
  }
  Serial.println("Card initialized.");
}

void loop() {
  // Open the file in write mode
  dataFile = SD.open("datalog.txt", FILE_WRITE);

  if (dataFile) {
    // Read the analog value from A0
    int sensorValue = analogRead(analogPin);

    // Convert the analog reading to voltage using the actual measured Vref
    float voltage = sensorValue * (measuredVref / 1023.0);

    // Calculate the current from the AD590 (I = V / R)
    float current = voltage / resistorValue; // in amperes
    float current_uA = current * 1000000.0; // convert to microamperes

    // Calculate the temperature in Kelvin from the current (1 µA = 1 K)
    float temperatureK = current_uA; // in Kelvin

    // Convert temperature from Kelvin to Celsius
    float temperatureC = temperatureK - 273.15; // in Celsius

    // Convert temperature from Celsius to Fahrenheit
    float temperatureF = temperatureC * 9.0 / 5.0 + 32.0; // in Fahrenheit

    // Create a string for the data
    String dataString = "";
    dataString += String(voltage, 3) + " V, ";
    dataString += String(temperatureK, 2) + " K, ";
    dataString += String(temperatureC, 2) + " °C, ";
    dataString += String(temperatureF, 2) + " °F";

    // Print the results to the serial monitor
    Serial.println(dataString);

    // Write the data to the SD card
    dataFile.println(dataString);

    // Close the file
    dataFile.close();
  } else {
    // If the file didn't open, print an error
    Serial.println("Error opening datalog.txt");
  }

  // Delay before the next reading
  delay(1000);
}
Leave a Comment