I’m trying to write a program to measure the intensity of an LED using a photoresistor and log that data to an SD card. I’d like to know if analogRead() is performing well enough to be appropriate for such a task (I need very precise and quick measurements), but I’m not sure how to measure this. Any help or hints would be greatly appreciated!
Here’s the code I’ve put together - a few parts of it probably don’t make sense to use for this situation; I’m very new to Arduino and coding in general, and the code is a work in progress.
#include <SD.h>
const int chipSelect = 53;
int LED = 12; //LED attached to defined pin
int brightness = 0; //how bright the LED is
int fadeAmount = 5; //how many points to fade the LED by per cycle
int PR = A0; //photoresistor is connected to defined pin
int val = 0; //value used to store the value coming from the sensor
void setup() {
{
//declare defined pin to be an output:
pinMode(LED, OUTPUT);
Serial.begin(9600); //send data to computer at 9600 bits/second
}
{
Serial.print("Initializing SD card...");
//make sure the default chip select pin is set to output
pinMode(53, OUTPUT);
//see if the card is present and can be initilized:
if (!SD.begin(chipSelect)) {
Serial.println("Card failed or not present");
//dont do anything else:
return;
}
Serial.println("Card initialized!");
}
//Write Log File Header
File logFile = SD.open("LOG.txt", FILE_WRITE);
if(logFile)
{
logFile.println(", "); //Just a leading blank line, in case there was previous data
String header = "ID, Photoresistor";
logFile.println(header);
logFile.close();
Serial.println(header);
}
else
{
Serial.println("Couldn't open log file");
}
}
void loop()
{
{
val = analogRead(PR); //read input value from photoresistor and store it
Serial.println(val); //print the value from photoresistor to serial port
delay(20);
}
{
//set the brightness of the defined LED pin
analogWrite(LED, brightness);
//change the brightness for the next loop:
brightness = brightness + fadeAmount;
//reverse the direction of the fading at ends of fade loop:
if (brightness == 0 || brightness == 255) {
fadeAmount = -fadeAmount ;
}
//wait for defined milliseconds to see the dimming effect:
delay(20);
}
// make a string for assembling the data to log:
String dataString = "";
// read three sensors and append to the string:
for (int analogPin = 0; analogPin < 1; analogPin++) {
int sensor = analogRead(analogPin);
dataString += String(sensor);
}
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
File dataFile = SD.open("datalog.txt", FILE_WRITE);
// if the file is available, write to it:
if (dataFile) {
dataFile.println(dataString);
dataFile.close();
// print to the serial port too:
Serial.println(dataString);
}
// if the file isn't open, pop up an error:
else {
Serial.println("error opening datalog.txt");
}
}