0

I have a L298 motor driver, which I coded with an Arduino Nano. The code is very simple at the moment:

// 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;
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);
}

void demoTwo()
{
  // this function will run the motors across the range of possible speeds
  // note that maximum speed is determined by the motor itself and the operating voltage
  // the PWM values sent by analogWrite() are fractions of the maximum speed possible 
  // by your hardware
  // turn on motors
  Motors_FWD_PWM_Initialize();

  // accelerate from zero to maximum speed
  for (int i = 0; i < 256; i++)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  } 
  // decelerate from maximum speed to zero
  for (int i = 255; i >= 0; --i)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  } 
  // now turn off motors
  MotorsOff();
}
void loop()
{
  demoTwo();
  delay(1000);
}

void Motors_FWD_PWM_Initialize()
{
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);  
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);  
}

void MotorsOff()
{
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);  
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);  
}

Currently I have two questions:

Q1: I have an ultrasonic sensor, how can I write the code so that the motors work and 'keep an eye out' with the ultrasonic sensor simultaneously? i.e. When a certain proximity is reached I would like the robot to stop.

Q2: Also I would like my robot to 'rove' around. How can I make it so? I was thinking having a number of subroutines, and making the arduino randomly choose one.

1

For the first question, you could simply implement an interrupt routine to regularly check the status of your sensor and when it achieves the desired threshold it triggers the action to stop the motor.

You can achieve this by setting timer1. There is a library here for example, where you set the period to execute a desired function, when some distance is detected you just stop the motors.

The second question could be done exactly like you said. Say you have some paths saved in memory, you can just create some options for them and execute whenever you want using switch/case command.

http://playground.arduino.cc/code/timer1

  • Nope. Not going to be that simple. Find someone or some project that has done it. Do not try to recreate the wheel yourself. Spend more time on google rather than here. instructables.com/id/… – user6569 May 2 '15 at 2:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.