一个中断就可以实现正反转计数了,另外,两个中断可以读取Z相信号,实现零点定位。- #define ONE_CIRCLE 334 //pulse counts of one circle
- #define GEAR_RATIO 46.8
-
- const int APin = 2;
- const int BPin = 3;
- long PulseCounts = 0;
- long Circles = 0;
- float Angle;
- boolean Dir;
- long OldCounts;
- float Speed;
- void setup()
- {
- Serial.begin(9600);
-
- pinMode(APin,INPUT);
- pinMode(BPin,INPUT);
- attachInterrupt(0,GetPulseCounts,RISING);
- }
-
- void loop()
- {
- Speed = (PulseCounts-OldCounts)*360/15631*2; //334*46.8=15631
- OldCounts=PulseCounts;
- Angle = (PulseCounts % 15631)*360/15631;
- Serial.print(PulseCounts);
- Serial.print("---------");
- Serial.print(Angle);
- Serial.print("-------");
- Serial.println(Speed);
- delay(500);
- }
-
- void GetPulseCounts()
- {
- int tempAPin = digitalRead(APin);
- int tempBPin = digitalRead(BPin);
- if(tempAPin != tempBPin)
- {
- PulseCounts++;
- Dir = true;
- }
- else
- {
- if(PulseCounts <= 0)
- {
- PulseCounts += 15631;
- }
- PulseCounts--;
- Dir = false;
- }
-
- }
复制代码 |