Last active
December 15, 2015 05:08
-
-
Save bertbalcaen/5206187 to your computer and use it in GitHub Desktop.
Control 6 motors with an accelerometer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 3, 5, 6, 9, 10, and 11 | |
#define MOTOR1 3 | |
#define MOTOR2 5 | |
#define MOTOR3 6 | |
#define MOTOR4 9 | |
#define MOTOR5 10 | |
#define MOTOR6 11 | |
#define PIN_X A0 | |
#define PIN_Y A1 | |
#define PIN_Z A2 | |
#define X_ZERO 490 | |
#define Y_ZERO 470 | |
#define Z_ZERO 512 | |
#define MIN_MOTOR_SPEED 40 | |
#define NUM_MOTORS 6 | |
int x = 0; | |
int y = 0; | |
int z = 0; | |
int motorSpeed = 0; | |
int xDiff, yDiff, zDiff; | |
int motorPins[] = { | |
MOTOR1, | |
MOTOR2, | |
MOTOR3, | |
MOTOR4, | |
MOTOR5, | |
MOTOR6 | |
}; | |
boolean leftToRightSorted = true; | |
void setup(){ | |
Serial.begin(9600); | |
pinMode(PIN_X, INPUT); | |
pinMode(PIN_Y, INPUT); | |
pinMode(PIN_Z, INPUT); | |
for(int i = 0; i < NUM_MOTORS; i++){ | |
pinMode(motorPins[i], OUTPUT); | |
} | |
} | |
void loop(){ | |
x = analogRead(PIN_X); | |
y = analogRead(PIN_Y); | |
z = analogRead(PIN_Z); | |
xDiff = abs(X_ZERO - x); | |
yDiff = abs(Y_ZERO - y); | |
zDiff = abs(Z_ZERO - z); | |
Serial.print("x: "); | |
Serial.println(x); | |
Serial.print("xDiff: "); | |
Serial.println(xDiff); | |
// Serial.print("y: "); | |
// Serial.println(y); | |
// Serial.print("yDiff: "); | |
// Serial.println(yDiff); | |
// | |
// Serial.print("z: "); | |
// Serial.println(z); | |
// Serial.print("zDiff: "); | |
// Serial.println(zDiff); | |
/* | |
if(xDiff < 0 && !leftToRightSorted){ | |
reverse_motor_list(); | |
} | |
if(xDiff > 0 && leftToRightSorted){ | |
reverse_motor_list(); | |
} | |
*/ | |
int maxSpeed = 255; | |
for(int i = 0; i < NUM_MOTORS; i++){ | |
// Serial.print("motor: "); | |
// Serial.println(i + 1); | |
maxSpeed = map(i, 0, NUM_MOTORS, MIN_MOTOR_SPEED, 255); | |
motorSpeed = map(abs(xDiff), 0, 100, 0, 255); | |
if(motorSpeed < MIN_MOTOR_SPEED){ | |
motorSpeed = 0; | |
} | |
// motorSpeed = 200; | |
// Serial.print("speed: "); | |
// Serial.println(motorSpeed); | |
analogWrite(motorPins[i], motorSpeed); | |
} | |
delay(100); | |
} | |
void reverse_motor_list(){ | |
for (int i=0, j = NUM_MOTORS - 1; i< NUM_MOTORS/2; i++, j--){ | |
int temp = motorPins[i]; | |
motorPins[i] = motorPins[j]; | |
motorPins[j] = temp; | |
} | |
leftToRightSorted = !leftToRightSorted; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment