Skip to content

Instantly share code, notes, and snippets.

@bertbalcaen
Created August 1, 2013 21:42
Show Gist options
  • Save bertbalcaen/6135623 to your computer and use it in GitHub Desktop.
Save bertbalcaen/6135623 to your computer and use it in GitHub Desktop.
Control motors over serial using an Arduino
// 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 MIN_MOTOR_SPEED 40
#define MAX_MOTOR_SPEED 30
#define NUM_MOTORS 6
#define MESSAGE_ID_ALL_MOTORS_ON 6
#define MESSAGE_ID_ALL_MOTORS_OFF 7
int currentMotorId;
int motorPins[] = {
MOTOR1,
MOTOR2,
MOTOR3,
MOTOR4,
MOTOR5,
MOTOR6
};
void setup(){
Serial.begin(9600);
for(int i = 0; i < NUM_MOTORS; i++){
pinMode(motorPins[i], OUTPUT);
}
// turn everything off when starting
vibeAll(false);
}
void loop(){
while(Serial.available() > 0){
byte val = Serial.read();
Serial.print("Receiving value from Bluetooth: ");
Serial.println(val);
if(val == MESSAGE_ID_ALL_MOTORS_OFF){
vibeAll(false);
} else if(val == MESSAGE_ID_ALL_MOTORS_ON){
vibeAll(true);
} else if(val < NUM_MOTORS){
currentMotorId = val;
} else {
vibeMotor(currentMotorId, val);
}
}
}
void vibeAll(boolean isOn){
int speed = MAX_MOTOR_SPEED;
if(!isOn){
speed = 0;
Serial.print("Setting all motors off");
} else {
Serial.print("Setting all motors on");
}
Serial.print("Setting speed of all motors to: ");
Serial.println(speed);
for(int i = 0; i < NUM_MOTORS; i++){
analogWrite(motorPins[i], speed);
}
}
void vibeMotor(int motorId, unsigned char speed){
unsigned char speedMapped = map(speed, 10, 255, 0, MAX_MOTOR_SPEED);
analogWrite(motorPins[motorId], speedMapped);
Serial.print("Setting motor ");
Serial.print(motorId);
Serial.print(" to speed ");
Serial.println(speedMapped);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment