Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int steps = 0; // set variable to hold our step position.
- int sensorVal = 0; // set variable to hold our sensor value, and later our delay.
- byte coil1 = 4; // set alias' for the coil pins.
- byte coil2 = 5;
- byte coil3 = 6;
- byte coil4 = 7;
- void setup(){
- pinMode(coil1, OUTPUT); // set coil pins as outputs.
- pinMode(coil2, OUTPUT);
- pinMode(coil3, OUTPUT);
- pinMode(coil4, OUTPUT);
- pinMode(A0, INPUT); // set analog read pin as an input.
- }
- void loop(){
- // Lets take a sensor reading, and turn it to a polarised
- // speed between 0 and ~1000 ms.
- sensorVal = analogRead(A0); // 0 -> 1023
- sensorVal -= 512; // -512 -> 511
- sensorVal *= 2; // -1024 -> 1022
- // so now we have a value, where +ve/-ve holds direction,
- // and absolute value holds the speed.
- // currently, we have a high delay value for high speeds, when we want the opposite. lets flip this,
- // and delay the needed time.
- delay(1023 - abs(sensorVal));
- digitalWrite(coil1, steps==0?HIGH:LOW); // Now set the coil pins as appropriate:
- digitalWrite(coil2, steps==1?HIGH:LOW); // the number of the pin to be written
- digitalWrite(coil3, steps==2?HIGH:LOW); // high is stored in steps.
- digitalWrite(coil4, steps==3?HIGH:LOW);
- // lets set the next pin to come on. this is in the range 0-3, so we will do a modulo-4 to
- // keep this in range.
- if (sensorVal > 0){steps = (steps+1)%4;} // if the sensor +ve, increase the step by one.
- if (sensorVal < 0){steps = (steps-1)%4;} // sensor -ve, so decrease the count.
- if (sensorVal == 0) {} // the sensor was 0, we will neither increase nor decrease the stepper.
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement