/*
   FM Radio
   --------
   v 1.00 2018/06/15
   Programmed 2018 By gijin77@gmail.com
*/
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <TEA5767.h>

#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);

#define LOGO16_GLCD_HEIGHT 16 
#define LOGO16_GLCD_WIDTH  16 
static const unsigned char PROGMEM logo16_glcd_bmp[] =
{ B00000000, B11000000,
  B00000001, B11000000,
  B00000001, B11000000,
  B00000011, B11100000,
  B11110011, B11100000,
  B11111110, B11111000,
  B01111110, B11111111,
  B00110011, B10011111,
  B00011111, B11111100,
  B00001101, B01110000,
  B00011011, B10100000,
  B00111111, B11100000,
  B00111111, B11110000,
  B01111100, B11110000,
  B01110000, B01110000,
  B00000000, B00110000 };

#if (SSD1306_LCDHEIGHT != 64)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif


TEA5767 Radio;
double old_frequency;
double frequency=84.7;
//          J-WAVE,放送大学,横須賀,FM東京,NHK横浜,FM横浜,家内,TBS,文化,ニッポン
double m_frq[11]={ 76.5,77.1,78.5,80.0,81.3,81.9,84.7,88.1,90.5,91.6,93.0 };
int m_no=6;
int m_flg=0;

#define BUTTON_M_PIN 4
#define BUTTON_U_PIN 3
#define BUTTON_D_PIN 2

void setup() {  
  display.begin(SSD1306_SWITCHCAPVCC, 0x3c); 
  Wire.begin();
  Radio.init();
  Radio.set_frequency(84.7); 
  Serial.begin(115200);
  pinMode(BUTTON_M_PIN, INPUT_PULLUP);
  pinMode(BUTTON_U_PIN, INPUT_PULLUP);
  pinMode(BUTTON_D_PIN, INPUT_PULLUP);
  display.display();
  delay(2000);

  // Clear the buffer.
  display.clearDisplay();
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(0,0);
  display.println("Start");
  display.println("FM Radio.");
  display.display();
  delay(2000);
}

void loop() {

  unsigned char buf[5];
  int stereo;
  int signal_level;
  double current_freq;

  if (Radio.read_status(buf) == 1) {
    current_freq =  double(Radio.frequency_available (buf) / 1000000);
    stereo = Radio.stereo(buf);
    signal_level = Radio.signal_level(buf);
    display.clearDisplay();
    display.setCursor(0,0);
    if (m_flg) {
      display.println("M"+String(m_no+1)+":"+String(current_freq,1)+"MHz");
    } else {
      display.println("FM:"+String(current_freq,1)+"MHz");
    }
    if (stereo) display.println("STEREO "); else display.println("MONO ");
    display.println("Level="+String(signal_level));
    display.display();
  }
  if(digitalRead(BUTTON_U_PIN) == 0)  {
    m_flg=0;
    frequency=frequency+0.1;
    if (frequency>107.0) frequency=76.0;
    Radio.set_frequency(frequency); 
    delay(300);
  }
  if(digitalRead(BUTTON_D_PIN) == 0) {
    m_flg=0;
    frequency=frequency-0.1;
    if (frequency<76.0) frequency=107.0;
    Radio.set_frequency(frequency); 
    delay(300);
  }
   if(digitalRead(BUTTON_M_PIN) == 0) {
    m_flg=1;
    m_no=m_no+1;
    if (m_no>10) m_no=0;
    frequency=m_frq[m_no];
    Radio.set_frequency(frequency); 
    delay(300);
  }

  delay(50);
}