Ian St. Louis
Created November 9, 2015

Second Project: Functioning car

Final design for remote controlled car.

Showcase (no instructions)27
Second Project: Functioning car

Story

Read more

Schematics

Motor control

Controls two DC motors and a servo.

Code

Motor control

C/C++
I found most of this code online. I adapted it to my specific needs, including adding the switch and the potentiometer.
// connect motor controller pins to Arduino digital pins
// motor one
int enA = 10;
int in1 = 9;
int in2 = 8;
// motor two
int enB = 5;
int in3 = 7;
int in4 = 6;
// for the potentiometer
#include <Servo.h>

Servo myservo;  // create servo object to control a servo

int potpin = 0;  // analog pin used to connect the potentiometer
int val;    // variable to read the value from the analog pin

void setup()
{
  // set all the motor control pins to outputs
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
  // attaches the servo on pin 9 to the servo object
  myservo.attach(3);
}
void loop()
{
  // this function will run the motors in both directions at a fixed speed
  // turn on motor A
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  // set speed to 200 out of possible range 0~255
  analogWrite(enA, 250);
  // turn on motor B
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  // set speed to 200 out of possible range 0~255
  analogWrite(enB, 250);
  while (digitalRead(2) == HIGH) {
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  // set speed to 200 out of possible range 0~255
  analogWrite(enB, 250);
  }
  //potentiometer
 // reads the value of the potentiometer (value between 0 and 1023)
  val = map(analogRead(potpin), 0, 1023, 0, 180);     // scale it to use it with the servo (value between 0 and 180)
  myservo.write(val);                  // sets the servo position according to the scaled value
  delay(2);                           // waits for the servo to get there
}

Credits

Ian St. Louis

Ian St. Louis

12 projects • 5 followers

Comments