//***************************************
// ATtiny202 Project
// elekey for practice
// programmed with Copilot
// XRQTechLab 2024.08
//***************************************

#include <EEPROM.h>

#define DIT_PIN 0
#define DAH_PIN 1
#define LED_PIN 2
#define PIEZO_PIN 3
#define BUTTON_PIN 4

int wpm = 10;
int ditLength;
int dahLength;
bool ditPressed = false;
bool dahPressed = false;
bool squeezeMode = false;
bool lastWasDit = false; // 追加

void setup() {
pinMode(DIT_PIN, INPUT_PULLUP);
pinMode(DAH_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
pinMode(PIEZO_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);

// EEPROMから速度設定を読み込む
wpm = EEPROM.read(0);
if (wpm < 10 || wpm > 30) {
wpm = 10;
}
updateSpeed();
playOpeningMessage();
}

void loop() {
if (digitalRead(BUTTON_PIN) == LOW) {
delay(50); // デバウンス
if (digitalRead(BUTTON_PIN) == LOW) {
wpm++;
if (wpm > 30) {
wpm = 10;
}
EEPROM.write(0, wpm);
updateSpeed();
playSpeedSignal();
}
}

if (digitalRead(DIT_PIN) == LOW) {
ditPressed = true;
}

if (digitalRead(DAH_PIN) == LOW) {
dahPressed = true;
}

if (ditPressed && dahPressed) {
squeezeMode = true;
}

if (squeezeMode) {
sendSqueeze();
squeezeMode = false;
} else {
if (ditPressed) {
sendDit();
}

if (dahPressed) {
sendDah();
}
}
}

void updateSpeed() {
ditLength = 1200 / wpm;
dahLength = ditLength * 3;
}

void sendDit() {
digitalWrite(LED_PIN, HIGH);
tone(PIEZO_PIN, 800);
delay(ditLength);
digitalWrite(LED_PIN, LOW);
noTone(PIEZO_PIN);
delay(ditLength);
ditPressed = false; // ここでリセット
lastWasDit = true; // 追加
}

void sendDah() {
digitalWrite(LED_PIN, HIGH);
tone(PIEZO_PIN, 800);
delay(dahLength);
digitalWrite(LED_PIN, LOW);
noTone(PIEZO_PIN);
delay(ditLength);
dahPressed = false; // ここでリセット
lastWasDit = false; // 追加
}

void sendSqueeze() {
while (digitalRead(DIT_PIN) == LOW && digitalRead(DAH_PIN) == LOW) {
if (lastWasDit) {
sendDah();
} else {
sendDit();
}
}
}

void playSpeedSignal() {
for (int i = 0; i < 3; i++) {
tone(PIEZO_PIN, 800);
delay(ditLength);
noTone(PIEZO_PIN);
delay(ditLength);
}
}

void playOpeningMessage() {
tone(PIEZO_PIN, 800);
delay(ditLength);
noTone(PIEZO_PIN);
delay(ditLength);
tone(PIEZO_PIN, 800);
delay(dahLength);
noTone(PIEZO_PIN);
delay(ditLength);
tone(PIEZO_PIN, 800);
delay(ditLength);
noTone(PIEZO_PIN);
delay(ditLength);
}