#include "Arduino.h"

//definePort
#define PortKey 9
#define PortBuzzOut 11
#define PortDCOut 7
#define LED 13

//define User Memory
static unsigned char FlagBuzz = false;
static unsigned int SigLen = 0x0000;
static unsigned int SpaceLen = 0x0000;
static unsigned char SigFlag = false;
//int Value;
char input;
//───────────────────────────────────
// Buzzer 1msec
//───────────────────────────────────
void buzz_1msec( void )
{
  static boolean sts = LOW;
  
  if( FlagBuzz )
  {
    sts = !sts;
    digitalWrite(PortBuzzOut, sts);
  }
  else
  {
    digitalWrite(PortBuzzOut, LOW);
  }
}

//───────────────────────────────────
// Here be interrupt function
//───────────────────────────────────
void interrupt_1msec( void )
{
 
  buzz_1msec();
}

void setup()
{
  // put your setup code here, to run once:
    Serial.begin(115200); //,SERIAL_8N1);
    while (!Serial);         // 準備が終わるのを待つ
    Serial.println("開始");   // シリアル通信でメッセージをPCに送信
    pinMode(PortBuzzOut, OUTPUT);
    pinMode(LED, OUTPUT);
    pinMode(PortKey, INPUT_PULLUP);
    digitalWrite(PortDCOut,LOW);
    FlagBuzz = false;
    noTone(PortBuzzOut);
}

boolean ChkKeyPort(void)
{
  if (digitalRead(PortKey) == LOW)
  {
    return true;
  }
  else {
    return false;
  }
}
void loop() 
{
  // put your main code here, to run repeatedly:
 if (Serial.available() > 0)
  {
    //digitalWrite(LED, HIGH);
    input = Serial.read();
    if (input == 'a')
    {
      tone(PortBuzzOut, 600);
      digitalWrite(PortDCOut, HIGH);
    }
    else
    {
      if (input == 'b')
      {
        digitalWrite(LED, LOW);
        noTone(PortBuzzOut);
        digitalWrite(PortDCOut, LOW);
      }
      else 
      {
        if (input == 'c')
        {
          tone(PortBuzzOut, 780);
          digitalWrite(PortDCOut, HIGH);
        }
      }
    }
  }
  if (ChkKeyPort()){// キーが押されていた
   digitalWrite(LED, HIGH);
    if (SigFlag == false)
    {//  その前はキーは押されていなかった
     if (SpaceLen > 4) 
     {
       Serial.print('S');
       Serial.print(':');
       Serial.println(SpaceLen);
       Serial.flush();
       SigFlag = true;
       SigLen = 1;
       FlagBuzz = true;
       tone(PortBuzzOut, 600);
       digitalWrite(PortDCOut, HIGH);
     }
     else
     {
       SpaceLen++;
     }
   }
   else 
   {// キーは連続して押されている
     SigLen++;
     if (SigLen > 5000) SigLen = 4000;
   }
  }
  else
  {// キーは押されていなかった
    digitalWrite(LED, LOW);
    if (SigFlag == true)
    {//　その前は押されていた
      if (SigLen > 4) 
      {
        Serial.print('M');
        Serial.print(':');
        Serial.println(SigLen);
        Serial.flush();
        SigFlag = false;
        SpaceLen = 1;
        FlagBuzz = false;
        noTone(PortBuzzOut);
        digitalWrite(PortDCOut, LOW);
      }
      else
      {
        SigLen++;
      }
    }
    else 
    {
      SpaceLen++;
      if (SpaceLen > 5000) SpaceLen = 4000;
    }
  }
  delay(2);
}

