slipstick:
You need to connect to PWM pins and use analogWrite(). PWM pins are the digital pins with a ~ next to them and they're not the same ones on all the different Arduinos.
If you have already got the motor running at full speed and off then post the code you used for that and we'll have something to help with.
Steve
I have the D0, D1, D2, and D3 pins from the motor module connected to the PWM pins of the Arduino.
Here's the code that I'm using: (I'm using it with an ultrasonic sensor)
int trigPin = 9; // trig pin of HC-SR04
int echoPin = 10; // Echo pin of HC-SR04
long duration, distance;
void setup() {
delay(random(500,2000)); // delay for random time
Serial.begin(9600);
pinMode(4, OUTPUT); // set Motor pins as output
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(trigPin, OUTPUT); // set trig pin as output
pinMode(echoPin, INPUT); //set echo pin as input to capture reflected waves
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH); // send waves for 10 us
delayMicroseconds(10);
duration = pulseIn(echoPin, HIGH); // receive reflected waves
distance = duration / 58.2; // convert to distance
delay(10);
// If you dont get proper movements of your robot then alter the pin numbers
if (distance > 16)
{
digitalWrite(4, LOW); // move forward
digitalWrite(5, HIGH);
digitalWrite(6, LOW);
digitalWrite(7, HIGH);
}
if (distance < 15)
{
digitalWrite(4, LOW); //Stop
digitalWrite(5, LOW);
digitalWrite(6, LOW);
digitalWrite(7, LOW);
delay(1500);
digitalWrite(4, HIGH); //movebackword
digitalWrite(5, LOW);
digitalWrite(6, HIGH);
digitalWrite(7, LOW);
delay(300);
digitalWrite(4, LOW); //Stop
digitalWrite(5, LOW);
digitalWrite(6, LOW);
digitalWrite(7, LOW);
delay(1500);
digitalWrite(4, LOW); //move the other direction
digitalWrite(5, HIGH);
digitalWrite(6, LOW);
digitalWrite(7, LOW);
delay(300);
digitalWrite(4, LOW); //Stop
digitalWrite(5, LOW);
digitalWrite(6, LOW);
digitalWrite(7, LOW);
delay(1500);
}
}