Control car with iPhone's acceleration sensor

このエントリーをはてなブックマークに追加

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

Using it, the code of control car is here.

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>

You will Get in Few Days

Circuit for Starter “obniz Board” is available on Amazon and other online stores.
You can get it at below

Our products and resellers

Forum

Visit our developer’s forum to discuss and discover technologies.

Forum

Contact

Feel free to contact out support and technical team.

Contact us