Control RC Car with Acceleration Sensor on Smartphone

Controlling RC car by acceleration sensor on Smartphone.

Obniz make it easy to use smartphone sensors for electronics.

You can get acceleration sensor value using only 3 lines.

 window.addEventListener("devicemotion", function (event1) {
    let x = event1.accelerationIncludingGravity.x;
 }

Materials

  • obniz x1
  • power supply for obniz x1
  • Smartphone with acceleration sensor x1
  • DC Motor x1
  • RC car tire x2
  • cardboard and paper, etc

Steps

We are expecting to control RC car by two tires made of DC Motor in this blog.

Wire DC Motors like the table and the image below. Please adjust the direction of the DC Motors properly, because rotation direction depends on the DC Motors’ direction.

obniz DC Motors
0 [left DC Motor] OUT1
1 [left DC Motor] OUT2
2 [right DC Motor] OUT1
3 [right DC Motor] OUT2

Put DC Motors to tires and make the body of RC car with cardboard and paper, etc.

At the end, supply power to a obniz and run the program below. You can control RC car by tilting your Smartphone.

Program

<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://obniz.io/js/jquery-3.2.1.min.js"></script>
  <script src="https://unpkg.com/obniz@2.0.2/obniz.js" crossorigin="anonymous"></script>
</head>
<body>

<div id="obniz-debug"></div>
<h1>obniz robot controller </h1>
<div id="print"></div>

<script>

  let obniz = new Obniz("OBNIZ_ID_HERE");
  let motorL, motorR;
  let threshold = 1, maxAccel = 5;

  obniz.onconnect = function () {
    motorL = obniz.wired("DCMotor", {forward: 0, back: 1});
    motorR = obniz.wired("DCMotor", {forward: 2, back: 3});
  };

  window.addEventListener("devicemotion", function (event1) {
    let x = event1.accelerationIncludingGravity.x;
    let y = event1.accelerationIncludingGravity.y;

    if (!motorR || !motorL) {
      return;
    }
    if (Math.abs(y) > threshold) {
      let power = Math.min(100 * (Math.abs(y) - threshold) / (maxAccel - threshold), 100);
      motorL.power(power);
      motorR.power(power);

      let direction = y > 0;
      motorL.move(direction);
      motorR.move(direction);


    } else if (Math.abs(x) > threshold) {
      let power = Math.min(100 * (Math.abs(x) - threshold) / (maxAccel - threshold), 100);
      if (x > 0) {
        motorR.power(power);
        motorR.move(true);
        motorL.stop();
      } else {
        motorL.power(power);
        motorL.move(true);
        motorR.stop();
      }
    } else {
      motorL.stop();
      motorR.stop();

    }

  }, true);

</script>
</body>
</html>
 

 

 

Recommended