\ AmazonにてArduino UNO R4 発売中!! /

Processing 入門 Lesson 04 【Arduino連携編 その4】

processing-lesson04-00 Processing入門編
記事に広告(アフィリエイト広告)が含まれています。
スポンサーリンク
Processing 入門
Lesson 04
【Arduino連携編 その4】

こんにちは、管理人のomoroyaです。

 

補足情報
Arduino用のスケッチが間違えていいたため修正

Lesson 01、02にてサンプルスケッチを利用してProcessingとArduinoを連携して遊びました。

 

Lesson 04も引き続きサンプルスケッチを利用して遊んでいきます。

しばらくは、どんなことができるのか体験です。

もう少しProcessingの構文の学習はおいておきます!

 

本日も内容理解は全て吹っ飛ばし、まずはどんなことができるのか体験です。

では、さっそく行って見ましょう。

 

Processingを始めようと考えている方。

ネット情報のみでも十分に学習可能です。

手元に参考書がほしいと考えている場合は下記の2冊程度で十分と考えます。

 

スポンサーリンク

はじめに

本LessonでもLesson 01Lesson 02Lesson 03同様にArduinoの「スケッチ例」にあるサンプルを利用します。
※統合環境であるIDEには、いくつかのサンプルスケッチがあります。

 

サンプルスケッチを読み出して実行するだけで、

「Arduino」と「Processing」を連携して遊ぶことができます。

どんなことができるのか確認するにはちょうど良い内容です。

 

公式ホームページのチュートリアルに説明があります。

上記ページの「Built-In Examples」⇒「4. Communication」と移動してください。

Communication用のTutorialが色々あります。

 

この中から、Processingと連携できるサンプルスケッチを選んで遊びます。

1.サンプルスケッチで遊ぶ。

2.どんなことができるのか体験する。

3.やってみたいことを想像する。

その後、本格的に学習していきます。

 

本Lessonでは、「4. Communication」にある「Serial Call Response」で遊びます。

このチュートリアルは「スイッチとポテンショメータ(可変抵抗器)2つ」使用します。

 

手持ちがない方は以下からどうぞ。

スイッチ1つだけ購入は、なかなか難しいです。

 

ポテンションメータも単品での購入はできないです。

そのため、購入される場合は種類が異なる物が入ったセットをおすすめします。

後々使い勝手が良いです。

タイプは好みで、つまみあり、なし。

 

上記が在庫切れの場合は下記なども。

 

「Serial Call Response」で遊ぶための回路

公式の英語サイトを読まなくてもできるように本Lessonでは解説していきます。

英語が気にならない場合、公式ページを読んでいただいて遊ぶことができます。

先ほどの公式ページに実体配線図も記載されています。

 

公式ホームページでは、スイッチ1つと抵抗1つ。

ポテンションメータ?2つと抵抗2つを使用している実体配線図になっています。

本Lessonではスイッチ1つ、抵抗1つ、ポテンショメータ2つのみとします。

部品が少なくて済みますし、これでも支障ありません。

 

スケッチは以下の動作をしています。

  1. 起動時のみArduinoからASCIIコードの”A”を送信
  2. パソコン側から応答が得られるまで待つ
  3. 3つのセンサ値を1バイトとして送信し、コンピュータからの応答を待つ

 

3つのセンサとは以下のことです。

  1. スイッチのオン、オフ検出(デジタル入力2番ピン)
  2. ポテンショメータ、X軸検出(アナログ入力A0ピン)
  3. ポテンショメータ、Y軸検出(アナログ入力A1ピン)

 

ブレッドボード上の電子部品の動作で説明すると・・・

  • スイッチを押すと、画面に白丸が現れる
  • A0に繋がった可変抵抗器を動かすとX方向⇆に動く
  • A1に繋がった可変抵抗器を動かすとY方向⇅に動く

という動作をしており、Arduinoのスケッチはデジタルピンとアナログピンを制御するスケッチとなっています。

 

もう少し、詳細に説明します。

デジタル入力の2番ピンを使ってスイッチのオン、オフを認識し、白丸の表示、非表示をする。

ポテンショメータの出力をアナログ入力(A0、A1使用)に入れて、アナログデジタル変換する。
※ポテンショメータを動かすことで、出力の電圧値が変わります。

 

デジタル値に変換された値ををProcessingの実行画面のX軸、Y軸となるように処理をして白丸を動かす。

といった内容のチュートリアルとなります。

 

アナログ入力、アナログデジタル変換に関しては下記を参照ください。

 

Serial Call Response」に対応した回路図とブレッドボード図がこちらとなります。

管理人がFrizingを使って描いた回路図となります。

processing-lesson04-01.JPG

 

processing-lesson04-02.JPG

 

「Serial Call Response」サンプルスケッチ 読み出し

Arduinoの「IDE」を立ち上げてください。

以下で「Serial Call Response」のサンプルスケッチが読み出されます。

ファイル」⇒「スケッチ例」⇒「04.Communication」⇒「SerialCallResponse

 

こちらが読み出したサンプルスケッチ。

下記サンプルスケッチはArduino用のスケッチとProcessing用のスケッチが両方記載されています。

Processing用のスケッチはコメントアウトされていますので、Processingの「IDE」にコメントアウトされた部分を記載すればよいだけとなります。

/*
  Serial Call and Response
  Language: Wiring/Arduino

  This program sends an ASCII A (byte of value 65) on startup and repeats that
  until it gets some data in. Then it waits for a byte in the serial port, and
  sends three sensor values whenever it gets a byte in.

  The circuit:
  - potentiometers attached to analog inputs 0 and 1
  - pushbutton attached to digital I/O 2

  created 26 Sep 2005
  by Tom Igoe
  modified 24 Apr 2012
  by Tom Igoe and Scott Fitzgerald
  Thanks to Greg Shakar and Scott Fitzgerald for the improvements

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/SerialCallResponse
*/

int firstSensor = 0;    // first analog sensor
int secondSensor = 0;   // second analog sensor
int thirdSensor = 0;    // digital sensor
int inByte = 0;         // incoming serial byte

void setup() {
  // start serial port at 9600 bps:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  pinMode(2, INPUT);   // digital sensor is on digital pin 2
  establishContact();  // send a byte to establish contact until receiver responds
}

void loop() {
  // if we get a valid byte, read analog ins:
  if (Serial.available() > 0) {
    // get incoming byte:
    inByte = Serial.read();
    // read first analog input, divide by 4 to make the range 0-255:
    firstSensor = analogRead(A0) / 4;
    // delay 10ms to let the ADC recover:
    delay(10);
    // read second analog input, divide by 4 to make the range 0-255:
    secondSensor = analogRead(1) / 4;
    // read switch, map it to 0 or 255L
    thirdSensor = map(digitalRead(2), 0, 1, 0, 255);
    // send sensor values:
    Serial.write(firstSensor);
    Serial.write(secondSensor);
    Serial.write(thirdSensor);
  }
}

void establishContact() {
  while (Serial.available() <= 0) {
    Serial.print('A');   // send a capital A
    delay(300);
  }
}

/* Processing sketch to run with this example:

  // This example code is in the public domain.

  import processing.serial.*;

  int bgcolor;           // Background color
  int fgcolor;           // Fill color
  Serial myPort;                       // The serial port
  int[] serialInArray = new int[3];    // Where we'll put what we receive
  int serialCount = 0;                 // A count of how many bytes we receive
  int xpos, ypos;                // Starting position of the ball
  boolean firstContact = false;        // Whether we've heard from the microcontroller

  void setup() {
    size(256, 256);  // Stage size
    noStroke();      // No border on the next thing drawn

    // Set the starting position of the ball (middle of the stage)
    xpos = width / 2;
    ypos = height / 2;

    // Print a list of the serial ports for debugging purposes
    // if using Processing 2.1 or later, use Serial.printArray()
    println(Serial.list());

    // I know that the first port in the serial list on my Mac is always my FTDI
    // adaptor, so I open Serial.list()[0].
    // On Windows machines, this generally opens COM1.
    // Open whatever port is the one you're using.
    String portName = Serial.list()[0];
    myPort = new Serial(this, portName, 9600);
  }

  void draw() {
    background(bgcolor);
    fill(fgcolor);
    // Draw the shape
    ellipse(xpos, ypos, 20, 20);
  }

  void serialEvent(Serial myPort) {
    // read a byte from the serial port:
    int inByte = myPort.read();
    // if this is the first byte received, and it's an A, clear the serial
    // buffer and note that you've had first contact from the microcontroller.
    // Otherwise, add the incoming byte to the array:
    if (firstContact == false) {
      if (inByte == 'A') {
        myPort.clear();          // clear the serial port buffer
        firstContact = true;     // you've had first contact from the microcontroller
        myPort.write('A');       // ask for more
      }
    }
    else {
      // Add the latest byte from the serial port to array:
      serialInArray[serialCount] = inByte;
      serialCount++;

      // If we have 3 bytes:
      if (serialCount > 2 ) {
        xpos = serialInArray[0];
        ypos = serialInArray[1];
        fgcolor = serialInArray[2];

        // print the values (for debugging purposes only):
        println(xpos + "\t" + ypos + "\t" + fgcolor);

        // Send a capital A to request new sensor readings:
        myPort.write('A');
        // Reset serialCount:
        serialCount = 0;
      }
    }
  }

*/

 

「Serial Call Response」 Arduino用のスケッチを抜き出し

Arduino用のスケッチ部分のみを抜き出したのがこちら。

下記をArduino用の「IDE」に記載してArduinoに書き込んでください。

/*
  Serial Call and Response in ASCII
  Language: Wiring/Arduino

  This program sends an ASCII A (byte of value 65) on startup and repeats that
  until it gets some data in. Then it waits for a byte in the serial port, and
  sends three ASCII-encoded, comma-separated sensor values, truncated by a
  linefeed and carriage return, whenever it gets a byte in.

  The circuit:
  - potentiometers attached to analog inputs 0 and 1
  - pushbutton attached to digital I/O 2

  created 26 Sep 2005
  by Tom Igoe
  modified 24 Apr 2012
  by Tom Igoe and Scott Fitzgerald
  Thanks to Greg Shakar and Scott Fitzgerald for the improvements

  This example code is in the public domain.

  https://www.arduino.cc/en/Tutorial/BuiltInExamples/SerialCallResponseASCII
*/

int firstSensor = 0;    // first analog sensor
int secondSensor = 0;   // second analog sensor
int thirdSensor = 0;    // digital sensor
int inByte = 0;         // incoming serial byte

void setup() {
  // start serial port at 9600 bps and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }


  pinMode(2, INPUT);   // digital sensor is on digital pin 2
  establishContact();  // send a byte to establish contact until receiver responds
}

void loop() {
  // if we get a valid byte, read analog ins:
  if (Serial.available() > 0) {
    // get incoming byte:
    inByte = Serial.read();
    // read first analog input:
    firstSensor = analogRead(A0);
    // read second analog input:
    secondSensor = analogRead(A1);
    // read switch, map it to 0 or 255
    thirdSensor = map(digitalRead(2), 0, 1, 0, 255);
    // send sensor values:
    Serial.print(firstSensor);
    Serial.print(",");
    Serial.print(secondSensor);
    Serial.print(",");
    Serial.println(thirdSensor);
  }
}

void establishContact() {
  while (Serial.available() <= 0) {
    Serial.println("0,0,0");   // send an initial string
    delay(300);
  }
}

 

「Serial Call Response」 Processing用のスケッチを抜き出し

Processing用のスケッチ部分のみを抜き出したのがこちら。

下記をProcessing用の「IDE」に記載してください。

/* Processing sketch to run with this example:

  // This example code is in the public domain.
*/

  import processing.serial.*;

  int bgcolor;           // Background color
  int fgcolor;           // Fill color
  Serial myPort;                       // The serial port
  int[] serialInArray = new int[3];    // Where we'll put what we receive
  int serialCount = 0;                 // A count of how many bytes we receive
  int xpos, ypos;                // Starting position of the ball
  boolean firstContact = false;        // Whether we've heard from the microcontroller

  void setup() {
    size(256, 256);  // Stage size
    noStroke();      // No border on the next thing drawn

    // Set the starting position of the ball (middle of the stage)
    xpos = width / 2;
    ypos = height / 2;

    // Print a list of the serial ports for debugging purposes
    // if using Processing 2.1 or later, use Serial.printArray()
    println(Serial.list());

    // I know that the first port in the serial list on my Mac is always my FTDI
    // adaptor, so I open Serial.list()[0].
    // On Windows machines, this generally opens COM1.
    // Open whatever port is the one you're using.
    String portName = Serial.list()[0];
    myPort = new Serial(this, portName, 9600);
  }

  void draw() {
    background(bgcolor);
    fill(fgcolor);
    // Draw the shape
    ellipse(xpos, ypos, 20, 20);
  }

  void serialEvent(Serial myPort) {
    // read a byte from the serial port:
    int inByte = myPort.read();
    // if this is the first byte received, and it's an A, clear the serial
    // buffer and note that you've had first contact from the microcontroller.
    // Otherwise, add the incoming byte to the array:
    if (firstContact == false) {
      if (inByte == 'A') {
        myPort.clear();          // clear the serial port buffer
        firstContact = true;     // you've had first contact from the microcontroller
        myPort.write('A');       // ask for more
      }
    }
    else {
      // Add the latest byte from the serial port to array:
      serialInArray[serialCount] = inByte;
      serialCount++;

      // If we have 3 bytes:
      if (serialCount > 2 ) {
        xpos = serialInArray[0];
        ypos = serialInArray[1];
        fgcolor = serialInArray[2];

        // print the values (for debugging purposes only):
        println(xpos + "\t" + ypos + "\t" + fgcolor);

        // Send a capital A to request new sensor readings:
        myPort.write('A');
        // Reset serialCount:
        serialCount = 0;
      }
    }
  }

 

「Serial Call Response」 サンプルスケッチの実行

実行手順が以下となります。

  1. Arduino用のスケッチ部分をArduino用のIDEにコピーしてArduinoに書き込み。
    ※回路接続のため電源供給を一旦止める。
  2. 回路作成しArduinoと接続。
  3. Arduinoへ電源供給
  4. Processing用のスケッチ部分をProcessing用のIDEにコピーして実行。

これで、問題なく動くはずです。

 

「Serial Call Response」 サンプルスケッチ実行結果

Processingを実行するとパソコンの画面中央に実行画面が現れます。

スイッチを押すと、白丸のグラフィックが現れます。

白丸を中央にするためには、ポテンショメータの出力を2.5Vとしてください。

  • A0接続のポテンショメータ:白丸がX軸方向⇆に移動
  • A1接続のポテンショメータ:白丸がY軸方向⇅に移動

という動作になります。

 

ほぼ中心にあわせた状態。

processing-lesson04-03.JPG

 

 

Y軸方向のポテンショメータを動かした状態。

processing-lesson04-04.JPG

 

なるほどといった感じでしょうか。

 

まとめ

Lesson 04【Arduino連携編 その4】はここまで。

次回もサンプルコード使います。

回路は、本記事と同じものを使います。

サンプルスケッチはあと、2つあります。

Processing 入門 Lesson 05 【Arduino連携編 その5】
Lesson 01~04にてArduinoとProcessingを連携して動かしました。Lesson 05も引き続きサンプルスケッチを利用して遊んでいきます。Lesson 01~04と同様にProcessingの構文の理解は後回しです。だだ…

 

Processingを始めようと考えている方。

ネット情報のみでも十分に学習可能です。

手元に参考書がほしいと考えている場合は下記の2冊程度で十分と考えます。

 

最後に

疑問点、質問などありましたら気軽にコメントください。

この電子部品の解説をしてほしい!などなどなんでもOKです。

リンク切れ、間違いなどあればコメントいただけると助かります。

 

Arduino入門編、番外編、お役立ち情報などなどサイトマップで記事一覧をぜひご確認ください。

 

Arduino入門編で使用しているUNOはAmazonにて購入可能です。

互換品とは言え、Arduinoはオープンソース。

複製して販売するのもライセンス的に問題なし。

 

そのため互換品の品質も悪くなく、それでいて値段は安いです。

正規品本体の値段程度で豊富な部品が多数ついています。

 

学習用、遊び用、お試し用には安価な互換品がおすすめです。

 

 

上記のものでも十分に多数の部品が入っていますが、最初からもっと多数の部品が入っているこちらもお勧めです。

 

Amazonでお得に買う方法

Amazonでお得に購入するなら、Amazonギフト券がおすすめです。

現金でチャージするたびに、チャージ額に応じたポイントが付与されます。

最大2.5%!!!(Amazonプライム会員ならさらにお得)

チャージ額(一回分) 一般 プライム会員
5,000円~19,999円 0.5% 1.0%
2,0000円~39,999円 1.0% 1.5%
40,000円~89,999円 1.5% 2.0%
90,000円~ 2.0% 2.5%

さらに、初回チャージで1000ポイントもらえるキャンペーンも実施中!

\Amazonギフト券 1000ポイントキャンペーン/
Amazonチャージ 初回購入で1000ポイントキャンペーン

 

補足情報
コンビニ・ATM・ネットバンクが対象
購入は1円単位で可能

コメント

タイトルとURLをコピーしました