Here is my arduino code, I have a photomicro-sensor which connected to arduino nano pin3. And I use the attachInterrupt function to access encoderTick function as soon as the digital pin changed. In the encoderTick, I print time taken from last time the digital pin changed. In the test, I can see two issues. all the data is print in encoderTick, which means print when sensor changed it situation.
1:
The data is below. The first one the count which added every time it calls. second is time takes every time it calls. third is digital pin state. I just cover the sensor to test. I didn't understand that why the time will equal to 0 in the end of test, because it must be >0, the rate I cover is slow. something wrong just happen, the arduino seems dead. because all the remain data is like that.
50 130 1
51 60 0
52 129 1
53 27 0
54 132 1
55 38 0
56 990 1
57 3 0
58 2 1
59 0 0
60 1 1
61 0 0
62 0 1
63 0 0
64 0 1
65 0 0
66 0 1
67 0 0
68 0 1
69 0 0
70 0 1
2:
Every time it calls, the state should be changed to previous, because that how the attachInterrupt works, the state changed, then calls to encoderTick.
45 97 0
46 191 1
47 95 0
48 190 1
49 76 0
50 178 1
51 800 0
52 322 0
53 0 0
54 5 1
55 1 0
56 452 1
Any suggestions will be appreciated. thx all.
#include <Arduino.h>
#include <Wire.h>
#include "LIDARLite.h"
#include "TimerOne.h"
LIDARLite myLidarLite;
volatile int angle = 0;
volatile float ratio = 0;
volatile bool zeroPos = false;
volatile int HightickDuration = 0;
volatile int LowtickDuration = 0;
volatile int tickAngle = 0;
volatile unsigned long LastTime = 0;
volatile int Duration =0;
volatile byte state = 0;
volatile int count = 0;
volatile unsigned long Time =0;
void timer(){
angle++;
}
void encoderTick(){
count++;
tickAngle+=12;
state = digitalRead(3);
Time = millis();
Duration = Time-LastTime;
LastTime = Time;
Serial.print(count);
Serial.print(" ");
Serial.print(Duration);
Serial.print(" ");
Serial.println(state);
// compute transition time
if (state == LOW){
LowtickDuration = Duration; //record duration in which sensor go throgh for a low stick
ratio = ((float)HightickDuration)/((float)LowtickDuration);
if (ratio >= 0.125 && ratio <= 0.5 ){
zeroPos = true;
tickAngle=0;
angle = tickAngle;
}
else {
angle = tickAngle;
Timer1.setPeriod(Duration*1000/12); // set degree timer based on transition time
}
}
else {
HightickDuration = Duration; //record duration in wdhich sensor go throgh for a low stick
}
}
void setup() {
pinMode(3, INPUT);//monitor optical sensor read
Timer1.initialize(1000000); // 1 second
Timer1.attachInterrupt(timer);
attachInterrupt(digitalPinToInterrupt(3), encoderTick, CHANGE);
Serial.begin(115200);
}
//Serial stream loop to send angle and range
void loop() {
...
}