#include <Arduino.h>
#include "lcdControl.h"

const byte ptn[11] {// DP,G,F,E,D,C,B,A
  0b00111111, //0
  0b00000110, //1
  0b01011011, //2
  0b01001111, //3
  0b01100110, //4
  0b01101101, //5
  0b01111101, //6
  0b00000111, //7
  0b01111111, //8
  0b01101111, //9
  0b00000000  //none(12)
};

volatile byte index = 0;
volatile byte digit[4];
volatile bool fTime;

void Out0(int nKeta, byte data);

ISR(TIMER1_OVF_vect)
{
  sei();
  Out0(index % 4, digit[index % 4]);
  index++;
}

void initLCD() {
  pinMode(LATCHPIN, OUTPUT);
  pinMode(CLOCKPIN, OUTPUT);
  pinMode(DATAPIN, OUTPUT);

  TCCR1A = 0b00000010;
  TCCR1B = 0b00011011;
  TIMSK1 = 0b00000001;
  ICR1 = 0x4ff;
}

///// 7セグ表示関数
void dispInfo(byte d1, byte d2, byte d3, byte d4, bool isTime) {
  digit[0] = ptn[d1 & 0x0f] + (d1 & 0x80);
  digit[1] = ptn[d2 & 0x0f] + (d2 & 0x80);
  digit[2] = ptn[d3 & 0x0f] + (d3 & 0x80);
  digit[3] = ptn[d4 & 0x0f] + (d4 & 0x80);
  fTime = isTime;
}

void dispNone() {
  digit[0] = 0;
  digit[1] = 0;
  digit[2] = 0;
  digit[3] = 0;
  fTime = false;
}

// シフトレジスタへのデータ送信
void Out0(int nKeta, byte data) {
  byte digitInfo = ~(B00000001 << nKeta);
  if (fTime && nKeta == 0) {
    digitInfo &= B11101111;
  }
  digitalWrite(LATCHPIN, LOW);
  shiftOut(DATAPIN, CLOCKPIN, MSBFIRST, digitInfo);
  shiftOut(DATAPIN, CLOCKPIN, MSBFIRST, data);
  digitalWrite(LATCHPIN, HIGH);
}
