#include <SPI.h>
#include <SD.h>
const float BETA = 3950; // Beta coefficient of the thermistor
const int chipSelect = 10; // Pin connected to the CS line of the SD card
void init_ADC(void);
unsigned char start_ADC(void);
uint16_t read_ADC(void);
void Temp(uint16_t value); // Function declaration
void setup() {
Serial.begin(9600);
init_ADC();
start_ADC();
// Initialize SD card
if (!SD.begin(chipSelect)) {
Serial.println("SD card initialization failed!");
return;
}
Serial.println("SD card initialized.");
// Open the file and write the header if needed
File dataFile = SD.open("temperature.txt", FILE_WRITE);
if (dataFile) {
dataFile.println("Time, Temperature (C)"); // Write header if this is a new file
dataFile.close();
} else {
Serial.println("Error opening temperature.txt");
}
}
void loop() {
// Read ADC and store temperature data
uint16_t x = read_ADC();
Temp(x); // Pass ADC value to Temp function
delay(1000); // Log temperature every second
}
void init_ADC() {
volatile char *admux = (volatile char *)0x7C;
volatile char *adcsra = (volatile char *)0x7A;
*admux = 0x40; // Internal 1.1V voltage reference with external capacitor at AREF pin
sei(); // Enable global interrupt;
*adcsra = 0xA7; // 11000111: 128 prescaler, ADC enable, start ADC
}
unsigned char start_ADC() {
volatile char *adcsra = (volatile char *)0x7A;
*adcsra = *adcsra | 0x40; // Starting the ADC
}
uint16_t read_ADC() {
volatile char *adcsra = (volatile char *)0x7A;
volatile unsigned char *L = (volatile unsigned char *)0x78;
volatile unsigned char *H = (volatile unsigned char *)0x79;
uint16_t value;
while ((*adcsra & 0x10) == 0); // Wait for conversion to be completed
value = (*H << 8) | *L; // Combine the upper and lower bits to get 10-bit result
*adcsra = *adcsra | 0x10; // Clear the flag
return value;
}
void Temp(uint16_t value) {
float analogValue = float(value); // Convert to float
float celsius = 1 / (log(1 / (1023. / analogValue - 1)) / BETA + 1.0 / 298.15) - 273.15;
// Print temperature to serial monitor
Serial.print("Temperature: ");
Serial.print(celsius);
Serial.println(" C");
// Open the file to append the temperature data
File dataFile = SD.open("temperature.txt", FILE_WRITE);
if (dataFile) {
// Write temperature to SD card file
dataFile.print(millis() / 1000); // Log time in seconds since program start
dataFile.print(", ");
dataFile.print(celsius);
dataFile.println(" C");
dataFile.close(); // Close the file to save the data
} else {
Serial.println("Error opening temperature.txt");
}
}