Advertisement
belrey10

Day 10: Restoring the City’s Voice – Morse Code Device

Nov 3rd, 2024 (edited)
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const int ledPin = 8;       // Pin for the LED
  2. const int ledPinDash = 9;       // Pin for the LED
  3. const int buttonPin = 2;    // Pin for the button
  4. int buttonState = 0;        // Variable to store the current button state
  5. int lastButtonState = 0;    // Variable to store the last button state
  6. unsigned long pressStartTime = 0; // Time when the button is pressed
  7. unsigned long pressEndTime = 0;   // Time when the button is released
  8. const int shortPressTime = 200;  // Threshold for a short press (dot)
  9. const int longPressTime = 550;   // Threshold for a long press (dash)
  10.  
  11. void setup() {
  12.   pinMode(ledPin, OUTPUT);   // Initialize the LED as output
  13.   pinMode(ledPinDash, OUTPUT);   // Initialize the LED as output
  14.   pinMode(buttonPin, INPUT); // Initialize the button as input
  15.   Serial.begin(9600);        // Start serial communication for debugging
  16. }
  17.  
  18. void loop() {
  19.   // Read the button state
  20.   buttonState = digitalRead(buttonPin);
  21.  
  22.   // If button is pressed
  23.   if (buttonState == HIGH && lastButtonState == LOW) {
  24.     pressStartTime = millis();  // Record the time when the button was pressed
  25.   }
  26.  
  27.   // If button is released
  28.   if (buttonState == LOW && lastButtonState == HIGH) {
  29.     pressEndTime = millis();  // Record the time when the button was released
  30.     long pressDuration = pressEndTime - pressStartTime;
  31.     Serial.print(pressDuration);
  32.  
  33.     // If it's a short press (dot)
  34.     if (pressDuration < shortPressTime) {
  35.       sendDot();
  36.     }
  37.     // If it's a long press (dash)
  38.     else if (pressDuration >= shortPressTime && pressDuration < longPressTime) {
  39.       sendDash();
  40.     }
  41.   }
  42.   lastButtonState = buttonState;  // Update the last button state
  43.   delay(50);
  44.  
  45. }
  46.  
  47. // Function to send a dot (short flash)
  48. void sendDot() {
  49.   digitalWrite(ledPin, HIGH);  // Turn on LED
  50.   delay(200);                  // LED on for 200ms
  51.   digitalWrite(ledPin, LOW);   // Turn off LED
  52.   delay(200);                  // Small delay between signals
  53.   Serial.println(" - Dot");       // Print "Dot" to the serial monitor
  54. }
  55.  
  56. // Function to send a dash (long flash)
  57. void sendDash() {
  58.   digitalWrite(ledPinDash, HIGH);  // Turn on LED
  59.   delay(200);                  // LED on for 500ms
  60.   digitalWrite(ledPinDash, LOW);   // Turn off LED
  61.   delay(200);                  // Small delay between signals
  62.   Serial.println(" - Dash");      // Print "Dash" to the serial monitor
  63. }
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement