   /* 
  12/09/2022
*/
//Defintions statements:
#define Hall_Sensor_Pin A0
#define PI 3.1415926535897932384626433832795
#define HALF_PI 1.5707963267948966192313216916398
#define TWO_PI 6.283185307179586476925286766559
#define DEG_TO_RAD 0.017453292519943295769236907684886
#define RAD_TO_DEG 57.295779513082320876798154814105
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,20,4);
float voltage;

extern volatile unsigned long timer0_millis;

void setup() {
  pinMode(Hall_Sensor_Pin,INPUT);
  lcd.init();
  lcd.backlight();
  Serial.begin(9600);
}

  
void loop(){
voltage = analogRead(Hall_Sensor_Pin);
Serial.print("New measurement starts, ");
Serial.print("Starting voltage: ");
Serial.print(voltage);
Serial.print('\n');
delay(10);

noInterrupts ();
timer0_millis = 0;
interrupts ();




// allocate values:
int hall_count = 0;
float start = millis();
bool on_state = false;
int hall_threshold = 20;

//counting number of times the hall sensor is tripped
//but without double ounting during the same trip
while(true){
  if (analogRead(Hall_Sensor_Pin)>600 or analogRead(Hall_Sensor_Pin)<420){
    if (on_state==false){on_state = true;
    hall_count+=1;
  }
 }else{
  on_state = false;
 }

  if (hall_count>=hall_threshold){
    break;
  }
}

//print information about Time and RPM
float end_time = millis();
float time_passed = ((end_time)/1000.0);
Serial.print("Time Passed: ");
Serial.print(time_passed);
Serial.print("s");
Serial.print('\n');
float rpm_val = (hall_count/time_passed)*60.0;
Serial.print(rpm_val);
Serial.println("RPM");
delay(1);        // delay in between reads for stability

//Velocity calculations:
float radius = 0.10; //m 
float circumference = 2 * PI * radius;
float velocity = (circumference * hall_threshold) / time_passed;

lcd.clear();
lcd.setCursor(0,0);
lcd.print("Velocity: ");
lcd.setCursor(11,0);
lcd.print(velocity);
lcd.setCursor(11,1);
lcd.print("[m/s]");



Serial.print("Velocity is: ");
Serial.print(velocity);
Serial.print("m/s");
Serial.print("\n");

}







  
