Go Down

Topic: RC car motor control  (Read 97 times) previous topic - next topic

Cduarte0306

Hello,

I am new to coding on Arduino. I am building an RC car and I am currently working on controlling the motor speed with a Joystick. I built my own H-bridge out of BJTs. So far the forward direction works and I am able to control the speed. However, when I try the backwards direction, the motor rolls backwards but I am not able to control how fast it goes. Could anyone look at my code and tell me what could be done better?


code:


const int Joystick1 = A1;
int motorPin1 = 3;
int motorPin2 = 2;

void setup()
{
 Serial.begin(9600);

}
 
void loop()
{

  int Joy1 = analogRead(Joystick1);

  Serial.print("Joystick 1: ");

  Serial.print(Joy1);

  Serial.println();
 

  if(Joy1 > 510)
  {
    analogWrite(motorPin1, Joy1);
    Serial.print("Forward motor speed: ");
    Serial.print(Joy1);
    Serial.println();
   
  }

  else analogWrite(motorPin1, 0);

  int backspeed;
  if(Joy1 < 500 && Joy1 >=0)
  {
    analogWrite(motorPin2, 1023 - Joy1);
    Serial.print("Backward motor speed: ");
    Serial.print(1023 - Joy1);
    Serial.println();
  }
 
  else analogWrite(motorPin2, 0);

 
 
  delay(1);

 
 
}


bos1714

Hello there!

Can you post a schematic of your wiring so we can see where any wires and components are connected?
Time line? Time isn't made out of lines. It is made out of circles. That is why clocks are round.

Wawa

Code: [Select]
 if(Joy1 > 510)
  {
    analogWrite(motorPin1, Joy1);

analogWrite takes a value from 0-255, not 510 to whatever.

You must first find the A/D range that the joystick returns (e.g. 210 to 820),
and then use map() and constrain() to convert that into the values for forwards and reverse.
Use the Help>Reference tab in the IDE.
Leo..

CrossRoads

Or just take the pot reading of 0 to 1023 (0 to 0x03FF) and shift it right two bits to convert if to 0 to 255 (0 to 0xFF).

shiftPotRead = (analogRead(Ax)) >>2;
Designing & building electrical circuits for over 25 years.  Screw Shield for Mega/Due/Uno,  Bobuino with ATMega1284P, & other '328P & '1284P creations & offerings at  my website.

Wawa

What I understand is that OP wants forwards and reverse with a deadband from that joystick.
And a joystick usually doesn't go from 0-1023.

Could be something like
speedForward = map(joy1, 520, 850, 50, 255);
520-850 being the forward range of the joystick, and 50 the minimum PWM value to move the motor.
Leo..

Go Up