I am using this to sense when a magnet passes the hall effect sensors. They are both trying to do the same thing. The below code works:
const float kDistance = 0.063;
unsigned long timeStarted;
void setup() {
pinMode(2, INPUT);
pinMode(3, INPUT);
digitalWrite(2, HIGH);
digitalWrite(3, HIGH);
Serial.begin(9600);
timeStarted = 0;
}
void loop() {
// put your main code here, to run repeatedly:
if (!digitalRead(2) && !timeStarted)
{
timeStarted = millis();
Serial.println("Start time");
}
if (!digitalRead(3) && timeStarted)
{
float deltaTime = (millis()-timeStarted)/1000.0;
float velocity = kDistance/deltaTime;
Serial.print("Velocity = ");
Serial.println(velocity, DEC);
Serial.print("Time = ");
Serial.println(deltaTime, DEC);
timeStarted = 0;
Serial.println("End time");
}
}
However this code does not - It is using attachinterrupts which would work much better, especially if I added more to my code and made it more complex.
const float kDistance = 0.063;
unsigned long timeStarted;
void setup() {
timeStarted = 0;
pinMode(2, INPUT);
pinMode(3, INPUT);
digitalWrite (2, HIGH);
digitalWrite (3, HIGH);
attachInterrupt(0, startTime, FALLING);
attachInterrupt(1, endTime, FALLING);
Serial.begin(9600);
}
void loop() {
}
void startTime()
{
Serial.println("Start time");
if (!timeStarted)
{
timeStarted = millis();
}
}
void endTime()
{
Serial.println("End time");
if (timeStarted)
{
float deltaTime = (millis()-timeStarted)/1000.0;
float velocity = kDistance/deltaTime;
Serial.print("Velocity = ");
Serial.println(velocity, DEC);
Serial.print("Time = ");
Serial.println(deltaTime, DEC);
timeStarted = 0;
}
else
{
Serial.println("Testing Error!");
}
}
Thanks in advance!