I am using a photoelectric sensor to measure the distance between two objects that it passes by. The sensor is going by the objects at a constant speed, so I am trying to determine the time between the objects by using millis(). I can then find the distance from the time and speed data. I am having problems when the millis gets to around 10,000 my board begins to slow and starts to freeze up. How do I fix this problem? I am very new to programming so any help is appreciated! My program is attached.
int inputPin = 2; //digital 2
int counter = 0;
int state;
int laststate = HIGH;
unsigned long time;
void setup(){
Serial.begin(9600);
pinMode(inputPin, INPUT);
}
void loop()
{
int state = digitalRead(inputPin);
if ( state != laststate)
{
laststate = state;
counter=counter+1;
Serial.println(counter);
time = millis();
//prints time since program started
Serial.println(time);
}
}
This sketch is not what you want, but it should give you some ideas:
unsigned long currentMillis;
unsigned long pin13Millis;
unsigned long StartMillis;
unsigned long time;
boolean timingMode = false; //Used to enable/disable parts of the sketch
const byte startSwitch = 2; //pushed = LOW
const byte stopSwitch = 3; //pushed = LOW
//**********************************************************************
void setup()
{
Serial.begin(9600);
pinMode(13,OUTPUT);
pinMode(startSwitch, INPUT_PULLUP); //pushed = LOW
pinMode(stopSwitch, INPUT_PULLUP); //pushed = LOW
} // >>>>>>>>>>>>>> E N D O F s e t u p ( ) <<<<<<<<<<<<<<<<<
void loop()
{
//Leave this at te top of the sketch
currentMillis = millis();
//***********************************
if(timingMode == false && digitalRead(startSwitch) == LOW)
{
StartMillis = millis();
timingMode = true;
}
if(timingMode == true && digitalRead(stopSwitch) == LOW)
{
time = millis() - StartMillis;
Serial.print("Time from Start to Stop = ");
Serial.println(time);
timingMode = false;
}
//***********************************
//Some code to check for blocking
//toggle pin 13 every 200mS
//has 200ms or more gone by?
if (currentMillis - pin13Millis >= 200UL)
{
//code here runs every 200ms
//get ready for next iteration
pin13Millis = pin13Millis + 200UL;
//toggle pin 13
digitalWrite(13,!digitalRead(13));
}
//*********************************
//put other non-blocking stuff here
//*********************************
} // >>>>>>>>>>>>>> E N D O F l o o p ( ) <<<<<<<<<<<<<<<<<
The photoelctric sensor is connected to pin 2. Yeah I am more interested in differences than time rather than absolute time. Is there a different way to do that?
gaclaassen:
The photoelctric sensor is connected to pin 2. Yeah I am more interested in differences than time rather than absolute time. Is there a different way to do that?
Pretty simple, really. Subtract one time from another. That's really it.