User:Messi~enwikiversity/robotCar/ArduinoSmallMotor/UnoCode

Go back to the tutorial

Start Coding
You can find the original example file from Sparkfun here.

Starting Point
''The best place to start tweaking the code is the main loop function. '' void loop {                             motorGo(0, CCW, 0);        //Motor1 motorGo(1, CW, 100);      //Motor2 delay(2000);              //This delay determines the time(ms) the motor runs for.

//Turn 1
 * The first argument passed to the function motorGo can be either 0 or 1. It determines which motor on the pins A1:B1 and A2:B2 are being controlled.
 * The second argument can be CCW, or CW. Pretty self-explanatory here, it turns the motor Clockwise(CW) or Counter-clockwise(CCW).
 * The third argument that is passed to the motorGo function represent a pwm(pulse width modulation) integer value. This number has to be between 0 and 1023. The higher this number, the faster you motor will turn.

Copy to Arduino IDE
''Copy this code over to the Arduino IDE and tweaking things. be an engineer''


 * 1) define BRAKEVCC 0
 * 2) define CW  1
 * 3) define CCW 2
 * 4) define BRAKEGND 3
 * 5) define CS_THRESHOLD 100

int inApin[2] = {7, 4}; // INA: Clockwise input int inBpin[2] = {8, 9}; // INB: Counter-clockwise input int pwmpin[2] = {5, 6}; // PWM input int cspin[2] = {2, 3}; // CS: Current sense ANALOG input int enpin[2] = {0, 1}; // EN: Status of switches output (Analog pin) int statpin = 13;

void setup { Serial.begin(9600); pinMode(statpin, OUTPUT);

// Initialize digital pins as outputs for (int i=0; i<2; i++) {   pinMode(inApin[i], OUTPUT); pinMode(inBpin[i], OUTPUT); pinMode(pwmpin[i], OUTPUT); }

// Initialize braked for (int i=0; i<2; i++) {   digitalWrite(inApin[i], LOW); digitalWrite(inBpin[i], LOW); } }

/* pmw value has to be < 1023. CCW=CounterClockwise CW=ClockWise -*/ void loop {                             motorGo(0, CCW, 0);        //Motor1 motorGo(1, CW, 100);      //Motor2 delay(2000);              //This delay determines the time(ms) the motor runs for.

//Turn 1 motorGo(0, CW, 600);      // The higher the pwm value, the quicker the car turns motorGo(1, CW, 180);      // The higher the pwm value, the sharper the car turns delay(1000);

motorGo(0, CCW, 0); motorGo(1, CW, 100); delay(8000);

if ((analogRead(cspin[0]) < CS_THRESHOLD) && (analogRead(cspin[1]) < CS_THRESHOLD)) digitalWrite(statpin, HIGH); }

void motorOff(int motor) { // Initialize braked for (int i=0; i<2; i++) {   digitalWrite(inApin[i], LOW); digitalWrite(inBpin[i], LOW); } analogWrite(pwmpin[motor], 0); }

void motorGo(uint8_t motor, uint8_t direct, uint8_t pwm) { if (motor <= 1) {   if (direct <=4) {     // Set inA[motor] if (direct <=1) digitalWrite(inApin[motor], HIGH); else digitalWrite(inApin[motor], LOW);

// Set inB[motor] if ((direct==0)||(direct==2)) digitalWrite(inBpin[motor], HIGH); else digitalWrite(inBpin[motor], LOW); analogWrite(pwmpin[motor], pwm); } } }