0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

はじめに

p5.toio を使った toio の制御を行う際に、複数台の処理を時間差で実行するという話です。

試した内容の動作確認中の様子

先に、今回試した内容の結果を掲載します。

以下では、ボタンを押下すると 250ミリ秒の時間差で、8台の toio が順番に動き出します(一定時間、回転する動作を行います)。

時間差での動作

時間差で動作させる部分では、以下の記事などで書かれている方法を活用します。

●ES2017 async/await で sleep 処理を書く - Qiita
 ttps://qiita.com/asa-taka/items/888bc5a1d7f30ee7eda2

記事内で出てくる以下の内容です。

const sleep = msec => new Promise(resolve => setTimeout(resolve, msec));

(async () => {
  await sleep(1000);
})();

p5.toio の処理をまじえた実装

具体的な実装内容は以下のとおりです。

const gCubes = [];

let angle;

function setup() {
  createCanvas(400, 400);
  background(220);
}

function mouseClicked() {
  P5tCube.connectNewP5tCube().then((cube) => {
    gCubes.push(cube);
    cube.turnLightOnRGB(random(255), random(255), random(255), 0);
  });
}

function keyPressed() {
  rotateCubes();
}

const sleep = (msec) => new Promise((resolve) => setTimeout(resolve, msec));

function rotateCubes() {
  if (gCubes.length > 0) {
    (async () => {
      for (const cube of gCubes) {
        cube.rotate(50, 50);
        await sleep(250);
      }
    })();
  }
}

上で少し書いていた sleep を利用している部分は以下です。
その実装部分では、即時実行関数式を使いました。

function rotateCubes() {
  if (gCubes.length > 0) {
    (async () => {
      for (const cube of gCubes) {
        cube.rotate(50, 50);
        await sleep(250);
      }
    })();
  }
}

これで、意図通りの動作をさせられました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?