#define LED_PIN 13
#define BUTTON_PIN 2
// Definisikan status-status untuk state machine
enum State {
WAITING_PRESS,
WAITING_RELEASE,
DOT,
DASH
};
State currentState = WAITING_PRESS;
unsigned long lastPressedTime = 0;
char morseSymbol = ' ';
void setup() {
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
int buttonState = digitalRead(BUTTON_PIN);
unsigned long currentTime = millis();
switch(currentState) {
case WAITING_PRESS:
if (buttonState == LOW && currentTime - lastPressedTime > 50) {
lastPressedTime = currentTime;
currentState = WAITING_RELEASE;
}
break;
case WAITING_RELEASE:
if (buttonState == HIGH && currentTime - lastPressedTime > 50) {
unsigned long pressDuration = currentTime - lastPressedTime;
if (pressDuration < 500) {
morseSymbol = '.';
currentState = DOT;
} else {
morseSymbol = '-';
currentState = DASH;
}
lastPressedTime = currentTime;
}
break;
case DOT:
if (currentTime - lastPressedTime > 100) {
digitalWrite(LED_PIN, LOW);
lastPressedTime = currentTime;
currentState = WAITING_PRESS;
Serial.print(morseSymbol);
} else if (currentTime - lastPressedTime > 50) {
digitalWrite(LED_PIN, HIGH);
}
break;
case DASH:
if (currentTime - lastPressedTime > 500) {
digitalWrite(LED_PIN, LOW);
lastPressedTime = currentTime;
currentState = WAITING_PRESS;
Serial.print(morseSymbol);
} else if (currentTime - lastPressedTime > 50) {
digitalWrite(LED_PIN, HIGH);
}
break;
}
}