March 23: Code-a-palooza
March 23, 2011
Two different sketches today. Click “read more” to see them, starting with the random movement sketch, and then continuing with our limit switch demo.
// PROJECT 18: MOTOR MAYHEM! // This sketch makes our motor rotate in a random direction, at a random speed, for a random duration. // It uses the motor controller chip included in your class kit. #define A_IN1 5 // motor controller pins #define A_IN2 4 #define A_PWM 3
#define H_SPEED 200 #define L_SPEED 40
#define H_DELAY 200 #define L_DELAY 10
#define speed_pot 0 // potentiometer
void setup(){
pinMode(A_IN1, OUTPUT);
pinMode(A_IN2, OUTPUT);
pinMode(A_PWM, OUTPUT);
}
void loop(){
random_speed(L_SPEED, H_SPEED); // choose a random speed
random_direction(); // choose a random direction
random_delay(L_DELAY, H_DELAY); // wait a random amount
a_brake(); // stop
random_delay(L_DELAY, H_DELAY); // wait a random amount
}
void a_cw(){
digitalWrite(A_IN1, HIGH);
digitalWrite(A_IN2, LOW);
}
void a_ccw(){
digitalWrite(A_IN1, LOW);
digitalWrite(A_IN2, HIGH);
}
void a_brake(){
digitalWrite(A_IN1, HIGH);
digitalWrite(A_IN2, HIGH);
}
void a_off(){
digitalWrite(A_IN1, LOW);
digitalWrite(A_IN2, LOW);
}
void random_speed(int low_val, int high_val){
int r_val;
r_val = random(low_val, high_val); analogWrite(A_PWM, r_val); }
void random_direction(){
int r_val;
r_val = random(2);
if (r_val ==0){
a_cw();
}
else{
a_ccw();
}
}
void random_delay(int low_val, int high_val){
int r_val;
r_val = random(low_val, high_val); delay(r_val); } //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // THE WORLD'S MOST BORING TENNIS MATCH // This sketch uses inputs from limit switches to send a motor back and forth, switching directions once // it hits the switch at the terminus of either direction. #define A_IN1 5 // motor controller pins #define A_IN2 4 #define A_PWM 3
#define LS 7 #define RS 8
#define speed_pot 0 // potentiometer
void setup(){
pinMode(A_IN1, OUTPUT);
pinMode(A_IN2, OUTPUT);
pinMode(A_PWM, OUTPUT);
pinMode(LS, INPUT);
pinMode(RS, INPUT);
pinMode(speed_pot, INPUT);
}
void loop(){
int a_speed;
int switch_a, switch_b;
pot_val = analogRead(speed_pot); a_speed = map(pot_val, 0, 1024, 20, 230);
analogWrite(A_PWM, a_speed); // set speed switch_a = digitalRead(LS); switch_b = digitalRead(RS);
if (switch_a == 0){
a_cw();
}
else if(switch_b == 0){
a_ccw():
}
}
}
void a_cw(){
digitalWrite(A_IN1, HIGH);
digitalWrite(A_IN2, LOW);
}
void a_ccw(){
digitalWrite(A_IN1, LOW);
digitalWrite(A_IN2, HIGH);
}
void a_brake(){
digitalWrite(A_IN1, HIGH);
digitalWrite(A_IN2, HIGH);
}
void a_off(){
digitalWrite(A_IN1, LOW);
digitalWrite(A_IN2, LOW);
}
Advertisement
No comments yet