LoginSignup
0
0

ELEGOO Mega 2560 (Arduino Mega互換) と MH-Z19C

Posted at

ELEGOO Mega 2560 (Arduino Mega互換) と MH-Z19C

ArduinoとMH-Z19Cの接続

注意事項

Serial Class

On older boards (Uno, Nano, Mini, and Mega), pins 0 and 1 are used for communication with the computer. Connecting anything to these pins can interfere with that communication, including causing failed uploads to the board.

古いボードだと0ピン/1ピン(RX/TX)使うとスケッチのアップロードに失敗することがあるよ的なことが書いてありますが、Serial.print系でプリントデバッグする場合はSerial(Serial0)に吐き出すので衝突防止のためにSerial1以降にセンサーをつないでおいたほうが安全です。

配線

Mega 2560 <---> MH-Z19C <---> NJM7805FA
GND <---> <---> <---> Pin 2
GND <---> Pin 2
VIN <---> Pin 3
TX1(18) <---> RX
RX1(19) <---> TX

Elegoo Mega 2560はMega互換で複数のSerial用ピンがあります。今回はSerial1(RX1/TX1)を使用します。

コード

Arduino IDEから以下のコードを書き込みます。

// Varb
const byte readCommand[] = {0xFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79};
const size_t commandLength = sizeof(readCommand);

// setup method
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial1.setTimeout(3000);
  pinMode(LED_BUILTIN, OUTPUT);
  //
  while(!Serial1){
    ;
  }
}

// main loop
void loop() {
  // put your main code here, to run repeatedly:
  // local verb
  byte returnValue[9];
  int arrayPosition = 0;
  int Co2Value = 0;
  // send command
  Serial1.write(readCommand, commandLength);
  Serial1.flush();
  // read result
  while(Serial1.available()){
    returnValue[arrayPosition++] = Serial1.read();
    if(arrayPosition >= 9){
      break;
    }
  }
  // check
  if(returnValue[0] == 0xFF && returnValue[1] == 0x86){
    // led blink
    digitalWrite(LED_BUILTIN, HIGH);
    // execute
    Co2Value = returnValue[2]*256 + returnValue[3];
    Serial.print("Co2: "); Serial.println(Co2Value);
  }
  // 
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
}

地味にはまる恐れがある点

普通に考えると「まとめてデータを取得できる関数があるんだからそっちを使ったほうが楽」と考えて以下のようなコードを書くと思います。

byte returnValue[9];
size_t returnLength = sizeof(returnValue);
Serial1.readBytes(returnValue, returnLength);

ところが、Serial.readBytes()で読もうとすると読めません。
読めませんというか、以下のようなフォーマットで返ってきます。

Byte[0] Byte[1] Byte[2] Byte[3] Byte[4] Byte[5] Byte[6] Byte[7] Byte[8] Byte[9]
本来のByte[0] ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ
本来のByte[1] ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ
本来のByte[2] ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ
本来のByte[3] ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ
本来のByte[4] ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ
本来のByte[5] ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ
本来のByte[6] ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ
本来のByte[7] ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ
本来のByte[8] ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ
本来のByte[9] ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ ノイズ

このまましばらく読み続けると、0xFFしか返ってこなくなります。

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