// Variables for Timer test
volatile bool interruptFlag = false; // Flag to indicate when the interrupt has occurred
bool ledState; // LED state
int ledPin = 13; // Built-in LED pin in Arduino
// Variable for ADC test
const int lightSensorPin = A0; // Analog pin connected to the light sensor
void setup() {
// Initialize serial communication at 9600 baud rate
Serial.begin(9600);
Serial.println("Press 1 to read light sensor data");
// Set output LED pin
pinMode(ledPin, OUTPUT);
cli(); //Stop interrupts till finish the settings
// Set up Timer1:
// Set the prescaler to 256
// Timer frequency = 16 MHz / 256 = 62.5 kHz
// Pulse time = 1/62.5 Khz = 16us
// Number of ticks = 500ms / 16us = 31250 ticks
TCCR1A = 0; // Normal mode, no PWM
TCCR1B = (1 << WGM12) | (1 << CS12); // CTC mode, prescaler 256
OCR1A = 31250; // Trigger interrupt at 31250 ticks
// Enable Timer1 compare match interrupt
TIMSK1 |= (1 << OCIE1A);
// Enable global interrupts
sei();
}
void loop() {
// Check if data is available to read
if (Serial.available() > 0) {
// Read the incoming character
char incomingChar = Serial.read();
// Process the received character
if (incomingChar == '1') { // If '1' is received, read and send light sensor data
int adcValue = analogRead(lightSensorPin); // Read the analog value (0-1023)
float voltage = adcValue * (5.0 / 1023.0); // Convert to voltage
// Send ADC value and voltage over UART
Serial.print("ADC Value: ");
Serial.print(adcValue);
Serial.print(" Voltage: ");
Serial.print(voltage, 2);
Serial.println(" V");
}
}
}
// Timer1 interrupt service routine
ISR(TIMER1_COMPA_vect) {
ledState = !ledState; // Toggle the LED pin to indicate the interrupt
digitalWrite(ledPin, ledState); // Set the LED state to LED pin
}