Here's a sample of code. I am to use PWM with the delayMicroseconds() and analogWrite(). How would I use delayMicroseconds() and analogWrite() into the code to make it run at 40% speed, 60% speed etc?
void loop() {
// if the switch is high, motor will turn on one direction:
if (digitalRead(switchPin) == HIGH) {
digitalWrite(motor1Pin, LOW); // set leg 1 of the H-bridge low
digitalWrite(motor2Pin, HIGH); // set leg 2 of the H-bridge high
}
// if the switch is low, motor will turn in the other direction:
else {
digitalWrite(motor1Pin, HIGH); // set leg 1 of the H-bridge high
digitalWrite(motor2Pin, LOW); // set leg 2 of the H-bridge low
}
}
This is what I'm trying to do:
If the digital pulse is HIGH for 250 microseconds and LOW for 750 microseconds we have a duty cycle of Ton/T X 100 = 250/1000 X 100 = 25%.
For example an analogWrite(3, 0) outputs zero volts or fully off on digital pin 3. And analogWrite(255, 3) outputs 5 volts or fully on with digital pin 3. A value of 128 produces a a square wave that's 50% on and 50% off for a duty cycle of 50%.
Where value is the value from 0-255 which you should input to get your required PWM.
Also, be sure to use one of the PWM pins on the arduino (for the UNO, these are 3,5,6,9,10,11, dunno about the other boards) for your h-bridge inputs (motor1Pin and motor2Pin in your case). And if you are using an L293D as your motor driver/h-bridge IC, you should probably connect two capacitors (0.1 uF worked for me) across the output pins of the IC and the ground.
Where *value* is the value from 0-255 which you should input to get your required PWM.
Also, be sure to use one of the PWM pins on the arduino (for the UNO, these are 3,5,6,9,10,11, dunno about the other boards) for your h-bridge inputs (motor1Pin and motor2Pin in your case). And if you are using an L293D as your motor driver/h-bridge IC, you should probably connect two capacitors (0.1 uF worked for me) across the output pins of the IC and the ground.
Good luck. :)
Ok so how would I make it run at 40%, 60% etc using delayMicroseconds()?
You'd need to write it up in "blink without delay" style.
Basically every pass thru void loop, you'd see how much time elapsed.
If the on-time was met, you'd turn it off, and then check if the off time was elapsed.
You could probably check every 100uS if you wanted.
Then read buttons switches, whatever, to decide when to change the % being used, or turn off competely etc. during the time you are waiting for something to happen.