main.c hw4

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

#include <stdio.

h>
#include <stdlib.h>
#include <time.h>
#include "LEDs.h" // assuming LEDs.c module exists

// Declare and initialize global variables


volatile int flag = 0;
volatile int counter = 0;

// Function prototypes
void Delay_millisec(unsigned int time_del);
void switch_ISR(void);

int main(void) {
// Initialize peripherals, including LEDs and a switch.
// Assume the switch is connected to INT0 pin
LEDs_Init();
INT0_Init(&switch_ISR);

srand(time(NULL)); // seed the random number generator

while (flag == 0) {
// Turn off all LEDs.
LEDs_Off(LED_ALL);

// Clear the counter variable to 0.


counter = 0;

// Wait for a random amount of time between 1 and 3 seconds using the rand() function.
int delay_time = (rand() % 3) + 1;
Delay_millisec(delay_time * 1000);

// Turn on one of the LEDs.


LEDs_On(LED_GREEN);

// Wait for the person to press the switch.


// The switch_ISR function will record the time it took to respond.
// The flag will be set inside the switch_ISR function.
while (flag == 0) {}

// Increment the counter variable.


counter++;

// Save the counter value in memory.


// You can save the counter value in a data structure or an array.
// Here, we will simply print the counter value to the console.
printf("Reaction Time: %d ms\n", counter);
// Wait for approximately 5 seconds.
Delay_millisec(5000);
}

// Stop the program if the event is triggered.


printf("Event Triggered. Exiting Program.\n");
return 0;
}

// Interrupt Service Routine for the switch


void switch_ISR(void) {
flag = 1; // set the flag indicating the ISR has executed
}

// Calibrated delay-loop function


void Delay_millisec(unsigned int time_del) {
// Adjust the loop count based on your microcontroller's clock speed
for (unsigned int i = 0; i < (time_del * 144); i++) {
asm("nop"); // assembly instruction to do nothing
}
}

You might also like