LoginSignup
0
0

More than 3 years have passed since last update.

ラズパイとArduino(BluePill)をUARTで接続(GPIO)してJSONでやりとりする

Last updated at Posted at 2020-07-19

自分メモ

Arduino側

#include <ArduinoJson.h>
String rs;

void setup() {
  Serial1.begin(115200);
}

void loop() {
  if (rs = receiveUart())
  {
    // 数字はJSONで確保するサイズ。あまり大きいとメモリを食うので注意
    StaticJsonDocument<1000> doc;

    // 変数 rs に配列に変換したJSONデータを代入
    DeserializationError err = deserializeJson(doc, rs);
    if (err == DeserializationError::Ok) 
    {
      // UART取得OK、msgデータを取得
      String message = doc["msg"].as<String>();

      // messageをなんやかんやする処理
      // 省略


      // 配列を追加する
      doc["result"] = true;
      String ws;
      // 配列をJSON形式に変換
      serializeJson(doc, ws);
      // JSONデータを送信
      Serial1.println(ws);
      rs = "";

    }
  }

  delay(100);
}

String receiveUart() {
  String rs;
  if (Serial1.available())
  {
    while (Serial1.available()) {
      delay(1);
      if (Serial1.available() > 0) {
        char c = Serial1.read();
        rs += c;
      }
    }
  }
  return rs;
}
Raspberry Pi側

import serial
import traceback
import time
import json

class UART:

        def __init__(self):
                try:

                        self.uartport = serial.Serial(
                                port="/dev/ttyAMA1",
                                baudrate=115200,
                                bytesize=serial.EIGHTBITS,
                                parity=serial.PARITY_NONE,
                                stopbits=serial.STOPBITS_ONE,
                                timeout=None,
                        )
                except serial.SerialException:
                        print(traceback.format_exec())

                self.uartport.reset_input_buffer()
                self.uartport.reset_output_buffer()
                time.sleep(1)

        def send_serial(self, cmd):
                print("send data : {0}".format(cmd))
                try:
                        cmd = cmd.rstrip()

                        self.uartport.write((cmd + "\n").encode("utf-8"))
                        self.uartport.flush()

                except serial.SerialException:
                        print(traceback.format_exec())

        def receive_serial(self):
                try:
                        rcvdata = self.uartport.readline()
                        self.uartport.flushInput()

                except serial.SerialException:
                        print(traceback.format_exec())

                return rcvdata.decode("utf-8").rstrip()

if __name__ == '__main__':
    uart = UART()
    while True:
        input_data = input(input data:)

        send_data = {msg : input_data}
        json_data = json.dumps(send_data)
        uart.send_serial(json_data)
        receive_data = uart.receive_serial()
        print("receive data : {0}".format(receive_data))

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