
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include <splash.h>
#include <Arduino.h>
#include <U8g2lib.h>

#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif
U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* reset=*/ 8);

int sen1=A0;
int sen2=A3;
unsigned long t1=0;
unsigned long t2=0; 
float velocity;
float velocity_real;
float timeFirst;
float timeScnd;
float diff;
float speedConst=7;  //in cm.
char velstr[6];

void setup()
{
  Serial.begin(9600);
  pinMode(sen1,INPUT);
  pinMode(sen2,INPUT);
  timeFirst = 0;
  u8g2.begin();
}
void loop()
{
  if (timeFirst == 0 && analogRead(sen1)<500)
  {
    timeFirst = millis();
  }

  if (timeFirst > 0 && analogRead(sen2)<500)
  {
    timeScnd = millis();
    diff = timeScnd - timeFirst; 
    velocity = speedConst / diff;
    velocity_real = (velocity*10);     // cm/ms to m/s.
    delay(30);
    timeFirst = 0;
    dtostrf(velocity_real, 6, 4, velstr);
  Serial.print("\n the velocity is : ");
  Serial.println(velstr);
  Serial.println(velocity_real);
  
  u8g2.clearBuffer();          // clear the internal memory
  u8g2.setFont(u8g2_font_ncenB08_tr); // choose a suitable font
  u8g2.drawStr(0,10,"Velocity:");  // write something to the internal memory
  u8g2.drawStr(0,30,velstr);  // write something to the internal memory
  u8g2.drawStr(50,30,"(m/s)");  // write something to the internal memory
  u8g2.sendBuffer();          // transfer internal memory to the display
  delay(500);  
  }
  }
