hi guys, i'm a beginner and i don't understand the code completely. for example, why do you use a "!" in front of digitalRead? can someone explain this to me? thanks.
#include <Arduino.h>
#define pinLatch 4 // Pin for latch signal of 7-segment display
#define pinClk 7 // Pin for clock signal of 7-segment display
#define pinData 8 // Pin for data signal of 7-segment display
#define mainLED 13 // Pin for main LED
#define secLED 11 // Pin for secondary LED
#define button1 A1 // Pin for button 1
#define button2 A2 // Pin for button 2
long reaction; // Variable to store the reaction start time
long reactionTime; // Variable to store the calculated reaction time
long reactionPoint; // Variable to store the random reaction point
const byte segmentMap[] = { 0xC0, 0xF9, 0xA4, 0xB0, 0x99, 0x92, 0x82, 0xF8, 0X80, 0X90 }; // Segment patterns for digits 0-9
const byte digitSegMap[] = { 0xF1, 0xF2, 0xF4, 0xF8 }; // Digit selection for each segment position
void setup() {
pinMode(pinLatch, OUTPUT);
pinMode(pinClk, OUTPUT);
pinMode(pinData, OUTPUT);
pinMode(mainLED, OUTPUT);
pinMode(secLED, OUTPUT);
randomSeed(analogRead(A5));
writeDigitToSegment(3, 0); // Display initial digit 0 on the 7-segment display
reactionPoint = random(2000, 5001); // Generate random reaction point between 2000ms and 5000ms
// Turn off all LEDs
digitalWrite(mainLED, HIGH);
digitalWrite(secLED, HIGH);
}
void loop() {
if (!digitalRead(button1)) {
digitalWrite(mainLED, LOW);
reaction = millis();
// Wait for the reaction time or until button2 is pressed
while (reaction + reactionPoint > millis() && digitalRead(button2)) {}
if (!digitalRead(button2)) {
// Calculate the reaction time and make it positive
reactionTime = ((millis() - reaction) - reactionPoint) * -1;
// Display the negative reaction time indefinitely (before the LED turned ON)
while (true) {
writeDigitToSegment(0, reactionTime / 1000);
writeDigitToSegment(1, (reactionTime / 100) % 10);
writeDigitToSegment(2, (reactionTime / 10) % 10);
writeDigitToSegment(3, reactionTime % 10);
}
}
digitalWrite(mainLED, HIGH);
digitalWrite(secLED, LOW);
reactionTime = millis();
// Wait until button2 is pressed
while (digitalRead(button2)) {}
// Calculate the reaction time (after the LED turned ON)
reactionTime = millis() - reactionTime;
// Display the positive reaction time indefinitely
while (true) {
writeDigitToSegment(0, reactionTime / 1000);
writeDigitToSegment(1, (reactionTime / 100) % 10);
writeDigitToSegment(2, (reactionTime / 10) % 10);
writeDigitToSegment(3, reactionTime % 10);
}
} else {
return;
}
}
void writeDigitToSegment(byte segment, byte value) {
digitalWrite(pinLatch, LOW);
// Shift out the segment pattern and digit selection to the 7-segment display
shiftOut(pinData, pinClk, MSBFIRST, segmentMap[value]);
shiftOut(pinData, pinClk, MSBFIRST, digitSegMap[segment]);
digitalWrite(pinLatch, HIGH);
}