I'm trying desperately to get my PWM-control working. Here's my code:
// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int led = 13;
int start = 2;
int inputValue = 1;
int pwmM1 = 5;
int pwmM2 = 6;
int dir1M1 = 4;
int dir2M1 = 3;
int dir1M2 = 8;
int dir2M2 = 9;
// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pin as an output.
pinMode(led, OUTPUT);
pinMode(start, INPUT);
pinMode(pwmM1, OUTPUT);
pinMode(pwmM2, OUTPUT);
pinMode(dir1M1, OUTPUT);
pinMode(dir2M1, OUTPUT);
pinMode(dir1M2, OUTPUT);
pinMode(dir2M2, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
delay(5000);
while(1){
digitalWrite(dir1M1, LOW);
digitalWrite(dir2M1, HIGH);
analogWrite(pwmM1, 255);
delay(1000);
digitalWrite(dir2M1, LOW);
digitalWrite(dir1M1, HIGH);
delay(1000);
}
}
The idea is that after 5 seconds, one motor should start rotating in one direction for 1 second and then change direction and rotate for another second and then repeat. In reality it does whatever the hell it wants. It starts out fine the first cycle but then the motor mostly rotate in the same direction all the time but not always. Can someone please tell me what the hell is going on?
Yes it should run over and over until the power is removed but it doesn't look like it does since it runs the motor in only one direction after a while and sometimes it stops completely.
Robtillaart:
How would a stop command help?
Only one analogWrite() is used but the idea is to change it. Let's say that I'll use analogWrite(full speed) in one direction and analogWrite(Low speed) in the other direction. Then I'll need to keep the analogWrite inside the loop(), or do I?
The motors are connected to a L293 H-bridge. It is lego motors that are powered with a regular 9 volt battery so there should be sufficient power to run them.
Yes, the loop() should be an eternal loop but it does not behave like that right now. Sometimes it only execute part of what's inside the loop() and sometimes it just stops. Thats why I added the while(1), to make an eternal loop of my own. No improvement though.
Problem solved, but god knows how. When was about to change the code as per your recommendations I first powered up the Arduino again. It worked like a charm. I examined why and I saw that a cable had come loose. The cable that had come loose was the cable connected from the 5V on the Arduino to pin 16 on the L293B H-bridge (since that's what the wiring diagram in the data sheet says). As far as I know, it's the power supply for the logic part of the H-brigde. Well, now it is disconnected and it works perfectly. Go figure. I reconnected it again and got the same random behavior. Can anyone explain this to me?