YAAPQ

YAAPQ = Yet Another Arduino Programming Question

After struggling to wrap my head around programming the Arduino in C I completely understand why Frits recommends starting out with the PICAXE...However, I am too stubborn to give up and switch to the PICAXE so I have another question.

I am basically just trying to figure out how to program the bot to react to button or switch presses by executing different bits of code accordingly (left button or right button). I have a Tamiya dual motor gearbox hooked up with an SN754410NE H-bridge which I have a grasp of thanks to Guibots tutorial and this is the code I have so far:

//- - - - - - - - - - - - - - - - - - VARIABLES

int motorSpeed = 125; // motor speed

// Motor Pins

int motor1_Pin0 = 11;
int motor1_Pin1 = 6;

int motor2_Pin0 = 5;
int motor2_Pin1 = 3;
// Switch Pin
int bump1_Pin = 2;
int val = 0;

// - - - - - - - - - - - - - - - - - - - SETUP
void setup() {

// set Arduino pins as outputs
pinMode(motor1_Pin0, OUTPUT);
pinMode(motor1_Pin1, OUTPUT);

pinMode(motor2_Pin0, OUTPUT);
pinMode(motor2_Pin1, OUTPUT);

pinMode(bump1_Pin,INPUT); //Bumper switch pins as Inputs


delay(500);

digitalWrite(motor1_Pin0, LOW); //Starts moving forward
analogWrite(motor1_Pin1, motorSpeed);

digitalWrite(motor2_Pin0, LOW);
analogWrite(motor2_Pin1, motorSpeed);
}

// - - - - - - - - - - - - - - - - - - - - LOOP
void loop() {
val = digitalRead(bump1_Pin);
if (val == HIGH){

analogWrite(motor1_Pin0, motorSpeed); //All Backwards
digitalWrite(motor1_Pin1, LOW);

analogWrite(motor2_Pin0, motorSpeed);
digitalWrite(motor2_Pin1, LOW); //All Backwards end

delay (3000);
}else{
digitalWrite(motor1_Pin0, LOW); //All Forwards
analogWrite(motor1_Pin1, motorSpeed);

digitalWrite(motor2_Pin0, LOW);
analogWrite(motor2_Pin1, motorSpeed); //All Forwards end

delay (3000);
}

}

Now this code works as a proof of concept I suppose. The bot drives backwards(dont ask) and when I hit the switch it drives forwards for the delay and then continues backwards. My problem is that the switch has to be depressed for a couple of seconds to "register" and react. Is this normal? Is it code or hardware related in you all opinions?

If any of you have a bot with say 2 bumper switches with code to turn right or left based on reading so I can just see the structure I would greatly appreciate it.

If your code is at one of
If your code is at one of the "delay(3000)" lines it will not detect your button press. What you should do is use a loop, like a for() loop, for instance. In this loop you check if the button is pressed. If it is, you break out of the loop and change direction.

As jka the delay function

As jka said, the delay function effectively puts the arduino to sleep for 3 seconds. You can push the switch as much as you like but during that 3 seconds it wont see it unless its still pushed after the delay is over.

Remove one of the delays, the one that is in your normal "go forwards until button is pushed" routine.