const int buttonPin = 2; // Change to the actual pin your button is connected to
const int ledPin = 13; // Change to the actual pin your LED is connected to
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (buttonState == HIGH) {
digitalWrite(ledPin, HIGH);
delay(50);
digitalWrite(ledPin, LOW);
delay(50);
// Button is pressed, run pi_exchange_test()
int fract_area = pi_exchange_test();
// Blink the LED based on the received integer value
for (int i = 0; i < fract_area; i++) {
digitalWrite(ledPin, HIGH);
delay(500);
digitalWrite(ledPin, LOW);
delay(500);
}
}
}
int pi_exchange(){
// Button is pressed, send the exchange_string to the Pi
Serial.println("exchange_string");
// Wait for the response from the Pi
while (Serial.available() == 0) {
delay(10);
}
// Read the response as an integer
int fract_area = Serial.parseInt();
return fract_area;
}
int pi_exchange_test() {
int fract_area;
// Button is pressed, send the exchange_string to the Pi
Serial.println("exchange_string");
// Wait for the response from the Pi
while (Serial.available() == 0) {
delay(10);
}
// Read user input from Serial and handle errors
while (true) {
if (Serial.available() > 0) {
String userInput = Serial.readStringUntil('\n');
// Attempt to convert the user input to an integer
if (isdigit(userInput.charAt(0))) {
fract_area = userInput.toInt();
break; // Exit the loop if conversion is successful
} else {
// Prompt user again for valid input
Serial.println("Invalid input. Please enter a valid integer.");
}
}
}
return fract_area;
}