int Butt = 2;
int LED = 13;
int Buzz = 8;
int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button
int startPressed = 0; // the moment the button was pressed
int endPressed = 0; // the moment the button was released
int holdTime = 0; // how long the button was held
int startBreakTime = 0; // how long the button was hold
int breakTime = 0;
int time=50;
String toDecode = "";
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(Butt, INPUT);
pinMode(LED, OUTPUT);
pinMode(Buzz, OUTPUT);
}
int morseDecode(String x){
String morse[] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....",
"..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-",
".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."
};
for (int i=0; i<26 ;i++){
if (x == morse[i]){
return i;
}
}
}
void loop() {
buttonState=digitalRead(Butt);
breakTime++;
if(breakTime>time/5 && toDecode!=""){
Serial.println(morseDecode(toDecode));
Serial.println(toDecode);
toDecode = "";
}
if (buttonState && !lastButtonState){ //if the button is pressed
breakTime=0; //reset breakTime
digitalWrite(LED,HIGH); //LED on
lastButtonState=digitalRead(Butt); //change the last state of the Button to the current state
startPressed=millis(); //save start time
digitalWrite(Buzz,HIGH); //Buzzer is on
}
if(!buttonState && lastButtonState ){ //if the button is released
breakTime=0; //reset breakTime
digitalWrite(LED,LOW); //LED off
lastButtonState=digitalRead(Butt); //change the last state of the Button to the current state
endPressed = millis(); //save release time
holdTime=endPressed-startPressed;
digitalWrite(Buzz,LOW); //Buzzer off
if (time/2 < holdTime && holdTime < time*3){ //generates '.' and adds it to the current string
toDecode = toDecode + "."; //generates '-' and adds it to the current string
}
else if(time*3 < holdTime && holdTime < time*20){
toDecode = toDecode + "-";
}
}
delay(50);
}