Advertisement
Fido488

Inertial Calculator

Dec 4th, 2013
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.44 KB | None | 0 0
  1. #define ENCODER_PIN_A  2
  2. #define ENCODER_PIN_B  3
  3. #define TRIGGER_PIN 18
  4.  
  5. volatile long encoder0Pos = 0;
  6. long newposition;
  7. long oldposition = 0;
  8. unsigned long newtime;
  9. unsigned long oldtime = 0;
  10. double vel = 0;
  11.  
  12. boolean timerRunning = false;
  13. boolean calcStarted = false;
  14. long startTime = 0;
  15.  
  16. void setup(){
  17.   Serial.begin (9600);
  18.   Serial.println("start");                // a personal quirk
  19.  
  20.   pinMode(ENCODER_PIN_A, INPUT);
  21.   digitalWrite(ENCODER_PIN_A, HIGH);       // turn on pullup resistor
  22.   pinMode(ENCODER_PIN_B, INPUT);
  23.   digitalWrite(ENCODER_PIN_B, HIGH);       // turn on pullup resistor
  24.   pinMode(TRIGGER_PIN, INPUT);
  25.   attachInterrupt(0, encodeCount, CHANGE);
  26.  
  27.   attachInterrupt(5, beginTiming, FALLING);
  28.  
  29.  
  30. }
  31.  
  32. void loop(){
  33.   noInterrupts();
  34.   newtime = millis();
  35.   newposition = encoder0Pos;
  36.   interrupts();
  37.   vel = (double(newposition-oldposition)) /(double(newtime-oldtime));
  38.   oldposition = newposition;
  39.   oldtime = newtime;
  40.   Serial.print(vel);
  41.   Serial.print(", ");
  42.   Serial.print(millis()-startTime);
  43.   if(timerRunning){
  44.     if(vel == 0.00){
  45.        Serial.print(", ");
  46.        Serial.print("Stopped Here");
  47.      }
  48.   }
  49.   Serial.println();
  50.  
  51. }
  52.  
  53. void beginTiming(){
  54.   if(!timerRunning){
  55.     //startTime = millis();
  56.   }
  57.   timerRunning = true;
  58. }
  59.  
  60. void encodeCount(){
  61.   if (digitalRead(ENCODER_PIN_A) == digitalRead(ENCODER_PIN_B)) {
  62.     encoder0Pos++;
  63.   } else {
  64.     encoder0Pos--;
  65.   }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement