Hello,everyone.
I am new to arduino. I use mstimer2 with my encoder project.
I want to initial the wireDistance = 0, when encoder rotate Distance between 5-6.
But I found wireDistance can't initial to 0 in loop.
I think it is because wireDistance is caculate by "count" in mstimer2.
And encoder accuracy will lost without mstimer2 interrupt.
Any help will be appreciated.
#include <MsTimer2.h>
#define PinA 3
#define PinB 4
int encoderPinA = LOW;
int encoderPinALast = LOW;
float count=0;
const float d=10;
const float pi=3.141;
float wireDistance;
void runEncoder()
{
encoderPinA = digitalRead(PinA);
if ((encoderPinALast == LOW) && (encoderPinA == HIGH))
{
if (digitalRead(PinB) == LOW)
{
count--;
}
else
{
count++;
}
}
//wireDistance = count/1000*pi*d;
encoderPinALast = encoderPinA;
}
void checkWireDistance(){
wireDistance = count/1000*pi*d;
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
//Serial2.begin(9600);
pinMode(PinA,INPUT_PULLUP);
pinMode(PinB,INPUT_PULLUP);
MsTimer2::set(1, runEncoder);
MsTimer2::start();
//MsTimer2::stop();
}
void loop() {
// put your main code here, to run repeatedly:
checkWireDistance();
if (wireDistance < 6.0 && wireDistance > 5.0)
{
Serial.println(wireDistance);
wireDistance = 0;
delay(300);
}
Serial.println(wireDistance);
delay(2000);
}