I have successfully made a RC Car with Arduino, L298N Motor driver and HC-06. The next step is I am working on is to use HMC5883L compass module as well and control the RC Car by passing strings like "N" so that car can go towards North direction. I found a library for using the Compass module from github which already does calibration. The issue I am having is in the code. Here is the sample of the code:

#include <Arduino.h>
#include <Wire.h>
#include <HMC5883L_Simple.h>

// Create a compass
HMC5883L_Simple Compass;
char D;
void setup()

  Compass.SetDeclination(10, 17, 'W');  //Declination for TORONTO, CANADA



// Our main program loop.
void loop() { 
    D = Serial.read();
   int heading = Compass.GetHeadingDegrees();
   Serial.print("Heading: \t");
   Serial.println( heading );   

    if(D == 'N'){
      if(heading >180){
          digitalWrite(10,HIGH); //Turns the car towards left
        }while(!(heading >=350));
      }else if(heading <=180){
          digitalWrite(13,HIGH); //Turns the car towards right
        }while(!(heading <=10));

For now, I am just trying the correct the direction of the car which it is pointing towards. Like by trying to make it point to North direction given where-ever it is pointing. I would really appreciate any help.

Thank you

  • please rotate the car slowly ... copy the serial monitor content and paste the text into your question above
    – jsotola
    Jun 5 at 18:30
  • what is the reason for the delay(1000);? ... the car stops "thinking" for a whole second ... that is a really long time for a computer
    – jsotola
    Jun 5 at 18:37
  • you may be forgetting that loop() function can repeat thousands of times per second ... your code is overly complicated ... there is no reason to wait while the car adjusts its heading ... all you have to do is to check the heading and steer accordingly ... do not wait for anything ... the heading is checked again at next iteration of loop() and steering is adjusted ... you are missing do not turn when car heading is north option
    – jsotola
    Jun 5 at 18:44
  • also, you use digitalWrite(10,HIGH); to turn left and you expect the car to somehow magically do digitalWrite(10,LOW);..... same with the digitalWrite(13,HIGH); ... right now GPIOs 10 and 13 stay high until you reset the Arduino
    – jsotola
    Jun 5 at 19:07
  • FYI, most compass phone applications use a magnetometer, accelerometer and gyroscope to create the compass. The HMC5883L looks to be only a magnetometer. So will likely not work as well. Also, even if calibration is automatic, you still have to turn any magnetometer around its 3 axis in the location you expect to use it. Preferably outside away from metal objects.
    – st2000
    Jun 6 at 12:49


Your Answer

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

Browse other questions tagged or ask your own question.