#include <Wire.h>
#include <FreqCount.h>
const int PWM_PIN = 6; //6番ピンはバリキャップ制御用アナログ出力端子 5番ピンは周波数測定用
const int AFC_PIN = 2; //2番ピンはAFCのONとOFFを制御するデジタル入力端子
const int AFCLED_PIN = 10;//10番ピンにLEDをつなぎAFCのONを表示するためのデジタル出力端子
const int HT16K33_ADDR = 0x70;
const int DIGIT = 4;
const char SEG_CHAR[10] = { 0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x67 };

void sprit_num( int value, int dig, int *output ) {
  int i = 0;
  while ( i < dig ) {
    output[i] = value % 10;
    value = value / 10;
    i = i + 1;
  }
}
void setup() {
  pinMode( PWM_PIN, OUTPUT );
  pinMode( AFC_PIN, INPUT );
  pinMode( AFCLED_PIN, OUTPUT );
  Wire.begin();
  Wire.beginTransmission( HT16K33_ADDR );
  Wire.write( 0x21 );
  Wire.write( 0x01 );
  Wire.endTransmission();
  delay(10);
  Wire.beginTransmission( HT16K33_ADDR );
  Wire.write( 0x81 );
  Wire.write( 0x01 );
  Wire.endTransmission();
  Serial.begin(57600);
  FreqCount.begin(10);//10ミリ秒間パルスを数える(100Hz単位)
  delay(10);
}
void loop() {
  if (FreqCount.available()) {
  boolean afc;
  int x = 50;
  analogWrite( PWM_PIN, x );//PWM_PINの初期電圧を50に規定
  int f1 = FreqCount.read(); //制御用に100Hz単位で計測
  //受信周波数を4桁LEDに表示
  int number = f1/10; //表示用に1kHz単位に変換
  number=number-455; //局発周波数を受信周波数に変換
  int disp_val[ DIGIT ];
  int i;
  sprit_num( number, DIGIT, disp_val );
  i = 0;
  while ( i < DIGIT ) {
    Wire.beginTransmission( HT16K33_ADDR );
    Wire.write( i * 2 );
    Wire.write( SEG_CHAR[ disp_val[i] ] );
    Wire.endTransmission();
    delay(10);
    i = i + 1;
  }
  delay(200);
  afc = digitalRead( AFC_PIN );
  if (afc == HIGH)  digitalWrite( AFCLED_PIN, HIGH) ;
  if (afc == LOW)  digitalWrite( AFCLED_PIN, LOW) ;
  while (afc == HIGH){ //AFCがONの場合の動作
   int f2 = FreqCount.read(); //f1と比較するためにf2を100Hz単位で読み込む
   int diff = f2 - f1 ;
   if (x <254 & x > 1){ //これがないとvalueが255(or0)に達した後0(255)に戻ってしまう
    if ( diff < 0) x = x +1;
    if ( diff > 0) x = x -1;
    if ( diff = 0) x = x +0;
    analogWrite( PWM_PIN, x );
     }
   //その時点の周波数を4桁LEDに表示
   number = f2/10;
   number=number-455;
   sprit_num( number, DIGIT, disp_val );
   i = 0;
   while ( i < DIGIT ) {
     Wire.beginTransmission( HT16K33_ADDR );
     Wire.write( i * 2 );
     Wire.write( SEG_CHAR[ disp_val[i] ] );
     Wire.endTransmission();
     delay(10);
     i = i + 1;
      }
      delay(500);//0.5秒待つ
      afc = digitalRead( AFC_PIN );
   }
 } //AFCがOFFの場合f1を読み込むところに戻る 
}