#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif

#include "Voicebox.h"

Voicebox::Voicebox(int Data, int Busy)
{
    _data = Data;
    _busy = Busy;
    pinMode(_data, OUTPUT);
    pinMode(_busy, INPUT);
}

void Voicebox::SendNum(int num)
{
    int val, qian, bai, shi, ge;
  val = num;
  qian = val / 1000;
  bai = val % 1000 / 100;
  shi = val % 100 / 10;
  ge = val % 10;

  if (qian > 0) {
    SendWord(34 + qian );
    SendWord(32);
  }
  if (bai > 0) {
    SendWord(34 + bai );
    SendWord(33);
  }
  if (bai == 0 && shi > 0 && qian > 0) {
    SendWord(44);
  }
  if (shi > 0) {
    SendWord(34 + shi);
    SendWord(34);
  }
  if (shi == 0 && ge > 0 && bai == 0 && qian > 0) {
    SendWord(44);
  }
  if (shi == 0 && ge > 0 && bai > 0) {
    SendWord(44);
  }
  if (ge > 0) {
    SendWord(34 + ge);
  }
  if (qian == 0 && bai ==0 && shi ==0 && ge == 0) {
    SendWord(44);
  }
}

void Voicebox::SendWord(int addr)
{
  digitalWrite(_data,LOW);
  delay(3); //>2ms
  for (int i = 0; i < 8; i++) {
    digitalWrite(_data,HIGH);
    if (addr & 1) {
      delayMicroseconds(2400); //>2400us
      digitalWrite(_data,LOW);
      delayMicroseconds(800);
    } //>800us
    else {
      delayMicroseconds(800); //>800us
      digitalWrite(_data,LOW);
      delayMicroseconds(2400);//>2400us
    } 
    addr >>= 1; //地址值右移一位
  }
  digitalWrite(_data,HIGH);
while (digitalRead(_busy) == 0);
}