#include <U8glib.h>
#include "pitches.h"

// Outputs
unsigned int buzzer = 12; 
U8GLIB_SH1106_128X64  My_u8g_Panel(U8G_I2C_OPT_NONE); // I2C / TWI
// LED outputs
int red = 11; 
int green = 10;
int blue = 9; 

int lights [9] = {
  0,0,255,
  0,255,0,
  255,0,0
};

int lightKey = 0;

int tones [5] = {
  NOTE_C4,
  NOTE_D4,
  NOTE_E4,
  NOTE_F4,
  NOTE_G4
};
int noteKey = 0;

// ************************************************
void setup(void) {
 
  Serial.begin(9600);
 
  #if defined(ARDUINO)
    pinMode(13, OUTPUT);          
    digitalWrite(13, HIGH);  
  #endif

  My_u8g_Panel.setFont(u8g_font_7x13);
  My_u8g_Panel.setFontRefHeightExtendedText();
  My_u8g_Panel.setDefaultForegroundColor();
  My_u8g_Panel.setFontPosCenter();

  pinMode(red, OUTPUT);
  pinMode(green, OUTPUT);
  pinMode(blue, OUTPUT);

  analogWrite(red, 255);
  analogWrite(green, 255);
  analogWrite(blue, 255);
}

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64

char *welcome = "Hello Friend!";
char *msg = new char[strlen(welcome)+1];
unsigned int numChars = 1;

void typewriterWelcome(){
  if(numChars <= strlen(welcome)){
    strncpy(msg, welcome, numChars);
    msg[numChars] = '\0';
    Serial.println(numChars);
    numChars++;
    Serial.println(msg);
  }
  int strWidth = My_u8g_Panel.getStrWidth(msg);
  int x = (SCREEN_WIDTH-strWidth)/2;
    
  My_u8g_Panel.firstPage();  
  do {
    My_u8g_Panel.drawStr(x, 32, msg);
  } while( My_u8g_Panel.nextPage() );
}

void typewriterMelody(){
  tone(buzzer, tones[noteKey], 100);
  noteKey++;
  if(noteKey >= 5){
    noteKey = 0;
  }
}

void typewriterLight(){
  analogWrite(red, lights[lightKey]);
  analogWrite(green, lights[lightKey+1]);
  analogWrite(blue, lights[lightKey+2]);
  lightKey = lightKey+3;
  if(lightKey >= 9){
    lightKey = 0;
  }
}

void loop(void) {    
  typewriterLight();
  typewriterMelody();
  typewriterWelcome();

  // rebuild the picture after some delay
  delay(250); 
}