Advertisement
AbstractBeliefs

Stepper

May 5th, 2011
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | None | 0 0
  1. int steps = 0;      // set variable to hold our step position.
  2. int sensorVal = 0;  // set variable to hold our sensor value, and later our delay.
  3.  
  4. byte coil1 = 4;     // set alias' for the coil pins.
  5. byte coil2 = 5;
  6. byte coil3 = 6;
  7. byte coil4 = 7;
  8.  
  9. void setup(){
  10.   pinMode(coil1, OUTPUT);  // set coil pins as outputs.
  11.   pinMode(coil2, OUTPUT);
  12.   pinMode(coil3, OUTPUT);
  13.   pinMode(coil4, OUTPUT);
  14.  
  15.   pinMode(A0, INPUT);      // set analog read pin as an input.
  16. }
  17.  
  18. void loop(){
  19.   // Lets take a sensor reading, and turn it to a polarised
  20.   // speed between 0 and ~1000 ms.
  21.   sensorVal = analogRead(A0);  //     0 -> 1023
  22.   sensorVal -= 512;            //  -512 -> 511
  23.   sensorVal *= 2;              // -1024 -> 1022
  24.   // so now we have a value, where +ve/-ve holds direction,
  25.   // and absolute value holds the speed.
  26.  
  27.   // currently, we have a high delay value for high speeds, when we want the opposite. lets flip this,
  28.   // and delay the needed time.
  29.   delay(1023 - abs(sensorVal));
  30.  
  31.   digitalWrite(coil1, steps==0?HIGH:LOW);  // Now set the coil pins as appropriate:
  32.   digitalWrite(coil2, steps==1?HIGH:LOW);  // the number of the pin to be written
  33.   digitalWrite(coil3, steps==2?HIGH:LOW);  // high is stored in steps.
  34.   digitalWrite(coil4, steps==3?HIGH:LOW);
  35.  
  36.   // lets set the next pin to come on. this is in the range 0-3, so we will do a modulo-4 to
  37.   // keep this in range.
  38.   if (sensorVal > 0){steps = (steps+1)%4;}  // if the sensor +ve, increase the step by one.
  39.   if (sensorVal < 0){steps = (steps-1)%4;}  // sensor -ve, so decrease the count.
  40.   if (sensorVal == 0) {}  // the sensor was 0, we will neither increase nor decrease the stepper.
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement