Skip to content

Instantly share code, notes, and snippets.

@hugs
Created October 15, 2010 03:59
Show Gist options
  • Select an option

  • Save hugs/627588 to your computer and use it in GitHub Desktop.

Select an option

Save hugs/627588 to your computer and use it in GitHub Desktop.
Arduino code for the PinMachine demo.
const int goUpPin = 2; // up input
const int goDownPin = 5; // down input
const int motor1Pin = 3; // H-bridge leg 1 (pin 2, 1A)
const int motor2Pin = 4; // H-bridge leg 2 (pin 7, 2A)
const int enablePin = 9; // H-bridge enable pin (PWM)
const int ledPin = 13; // LED
const int UP = 1;
const int DOWN = 0;
void setup() {
// set the switch as an input:
pinMode(goUpPin, INPUT);
pinMode(goDownPin, INPUT);
// set all the other pins you're using as outputs:
pinMode(motor1Pin, OUTPUT);
pinMode(motor2Pin, OUTPUT);
pinMode(enablePin, OUTPUT);
pinMode(ledPin, OUTPUT);
// set enablePin high so that motor can turn on:
analogWrite(enablePin, 200);
// blink the LED 3 times. This should happen only once.
// if you see the LED blink three times, it means that the module
// reset itself,. probably because the motor caused a brownout
// or a short.
blink(ledPin, 3, 100);
}
void loop() {
// if the activate switch is high, motor will turn on:
if (digitalRead(goUpPin) == HIGH) {
go(UP);
}
else if (digitalRead(goDownPin) == HIGH) {
go(DOWN);
}
// if the activate switch is low, motor will turn off:
else {
digitalWrite(motor1Pin, LOW); // set leg 1 of the H-bridge low
digitalWrite(motor2Pin, LOW); // set leg 2 of the H-bridge high
}
}
/*
blinks an LED
*/
void blink(int whatPin, int howManyTimes, int milliSecs) {
int i = 0;
for ( i = 0; i < howManyTimes; i++) {
digitalWrite(whatPin, HIGH);
delay(milliSecs/2);
digitalWrite(whatPin, LOW);
delay(milliSecs/2);
}
}
/*
Makes pin go up or down for one complete cycle
*/
void go(int direction) {
// First, use "high-power" (high PWM value) to unstick ourselves.
// It's (exactly) like untightening a screw.
if (direction == UP) { step(UP, 100); }
else if (direction == DOWN) { step(DOWN, 100); }
// Now that we're unstuck, we can drop to a lower PWM power level.
int i = 0;
for ( i = 0; i < 40; i++) {
if (direction == UP) { step(UP, 70); }
else if (direction == DOWN) { step(DOWN, 70); }
}
}
/*
One small step for robot-kind
*/
void step(int direction, int power) {
analogWrite(enablePin, power);
if (direction == UP) { // Go Up
digitalWrite(motor1Pin, LOW); // set leg 1 of the H-bridge low
digitalWrite(motor2Pin, HIGH); // set leg 2 of the H-bridge high
} else { // Go Down
digitalWrite(motor1Pin, HIGH); // set leg 1 of the H-bridge high
digitalWrite(motor2Pin, LOW); // set leg 2 of the H-bridge low
}
delay(20);
digitalWrite(motor1Pin, LOW); // set leg 1 of the H-bridge low
digitalWrite(motor2Pin, LOW); // set leg 2 of the H-bridge low
delay(35);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment