#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels


const int chart_margin = 10;
const int chart_size = (SCREEN_WIDTH - chart_margin * 2);
const int buffer_size = chart_size +1;
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);




int buffer[buffer_size]; 
int new_reading;
int start_intermediate;
int intermediate;

void setup() {


  Serial.begin(9600);

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3D)) { // Address 0x3D for 128x64
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }

  display.setRotation(2);

  // Show initial display buffer contents on the screen --
  // the library initializes this with an Adafruit splash screen.
  // display.display();

  // Clear the buffer
  display.clearDisplay();
 

   display.display();

}


void loop() {
  // int reading = map(analogRead(0), 0, 1024, 64, 0);
  for (int j = 0 ; j < chart_size   ; j++)
  {
  buffer[j] =  buffer[j+1];
  }
  //display.clearDisplay();
 
  // set the value at last array to new reading
  buffer[chart_size]= map(analogRead(0), 0, 1024, 64, 0);
  // draw it
  for (int j =0 ; j < chart_size; j++)
  {
  display.drawPixel(j + chart_margin +1, buffer[j], BLACK);
  display.drawPixel(j +chart_margin , buffer[j], WHITE);
  }
  display.display();

}



void staticLines(void) {
  int8_t start_x;
  int8_t start_y;
  int8_t end_x;
  int8_t end_y;

  int a = random();
  int b = random();
  int c = random();
  int d = random();

  start_x = map(a, -32767, 32768, 0, SCREEN_WIDTH);
  start_y = map(b, -32767, 32768, 0, SCREEN_HEIGHT);
  end_x = map(c, -32767, 32768, 0, SCREEN_WIDTH);
  end_y = map(d, -32767, 32768, 0, SCREEN_HEIGHT);

  // Serial.println("Line from ("+ String(start_x) + "," + String(start_y) + ") to (" + String(end_x) + "," + String(end_y)+")");

  display.drawLine(start_x, start_y, end_x, end_y, INVERSE);
  display.display();
  // delay(2);
}