const int BUTTONPin = 2;
const int ledPin = 9;
volatile bool ButtonPressed = false;
int i = 0;
char receivedChar;
//interupt funtion to check if button has been pressed
void ButtonInterupt() {
ButtonPressed = true;
}
void setup() {
pinMode(ledPin, OUTPUT);
attachInterrupt(digitalPinToInterrupt(BUTTONPin), ButtonInterupt, SHIFT);
Serial.begin(800);
}
void loop() {
if (Serial.available() > 0) {
receivedChar = Serial.read()
if (receivedChar == 'a'){
Serial.println("");
}
else if (receivedChar == 'b') {
// do something
}
else {
//
//
//
const int BUTTONPin = 2;
const int ledPin = 9;
volatile bool buttonInterruptTriggered = false;
bool buttonMode = false;
bool ledState = false;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(BUTTONPin, INPUT);
attachInterrupt(digitalPinToInterrupt(BUTTONPin), ButtonPress, RISING);
Serial.begin(9600);
Serial.println("Type 1 or 2 to select mode.");
}
void loop() {
// Handle serial input
if (Serial.available() > 0) {
char receivedChar = Serial.read();
if (receivedChar == '\n' || receivedChar == '\r') return;
if (receivedChar == '1') {
Serial.println("Mode 1");
Serial.println("Type 1 or 2 to select mode.");
buttonMode = false;
for (int i = 0; i < 5; i++) {
digitalWrite(ledPin, HIGH);
delay(250);
digitalWrite(ledPin, LOW);
delay(250);
}
}
else if (receivedChar == '2') {
Serial.println("Mode 2");
Serial.println("Type 1 or 2 to select mode.");
buttonMode = true;
}
else {
Serial.println("Invalid character");
Serial.println("Type 1 or 2 to select mode.");
buttonMode = false;
}
}
// Handle button press from interrupt
if (buttonInterruptTriggered && buttonMode) {
ledState = !ledState;
digitalWrite(ledPin, ledState);
buttonInterruptTriggered = false;
}
}
// Interrupt service routine
void ButtonPress() {
static unsigned long lastInterruptTime = 0;
unsigned long interruptTime = millis();
// Simple debounce: ignore triggers within 200ms
if (interruptTime - lastInterruptTime > 200) {
buttonInterruptTriggered = true;
lastInterruptTime = interruptTime;
}
}
Posted code has two loop() , so I suspect cut and paste oops.
Go to IDE, ctrl-t for format, then "copy for forum" and paste into new message here.
Voce postou seu tópico na categoria International Portugues, mas escreveu o titulo em Ingles.
Escreva também uma breve descrição de como deveria funcionar on seu projeto e o que não está funcionando.
Olá orangerat34
A que se destina o programa na vida real?
I suspect you're an English-speaking person.
If so, please change the category of your post to the appropriate language category.