Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

GNU OctaveとArduinoを連携する その2:ArduinoからOctaveに信号をおくる

前回はLチカで疎通できる事を確認しました
色々インターフェイスがついてるM5stackをつかって遊んでみます

実際のところ

M5stack(Arduino環境側)コード

ABCのボタンに対応して、画面の文字が変更され、かつその内容がシリアル経由で送信される内容になってます。

#include <M5Core2.h>

void setup() {
  M5.begin();
  Serial.begin(115200);
  
  M5.Lcd.setTextSize(2);
  M5.Lcd.setCursor(10, 10);
  M5.Lcd.println("Button Monitor");
  M5.Lcd.println("Press A, B, or C");
}

void loop() {
  M5.update();  // ボタンの状態を更新
  
  // ボタンAが押されたとき
  if (M5.BtnA.wasPressed()) {
    Serial.println("A");
    M5.Lcd.fillRect(10, 80, 300, 30, BLACK);
    M5.Lcd.setCursor(10, 80);
    M5.Lcd.print("Button A Pressed");
  }
  
  // ボタンBが押されたとき
  if (M5.BtnB.wasPressed()) {
    Serial.println("B");
    M5.Lcd.fillRect(10, 80, 300, 30, BLACK);
    M5.Lcd.setCursor(10, 80);
    M5.Lcd.print("Button B Pressed");
  }
  
  // ボタンCが押されたとき
  if (M5.BtnC.wasPressed()) {
    Serial.println("C");
    M5.Lcd.fillRect(10, 80, 300, 30, BLACK);
    M5.Lcd.setCursor(10, 80);
    M5.Lcd.print("Button C Pressed");
  }
  
  delay(10);
}

Octave側コード

先ほどのをうけて

pkg load arduino

% シリアルポートの設定(環境に応じて変更してください)
serialPort = "/dev/ttyUSB0";  % Linuxの場合
% serialPort = "COM3";        % Windowsの場合

% シリアルポートを開く
s = serial(serialPort, 115200);
srl_flush(s);

% グラフ用のデータ初期化
data = zeros(1, 100);
h = figure;
plot(data);
ylim([-0.5, 3.5]);
yticks([0 1 2 3]);
yticklabels({'None', 'A', 'B', 'C'});
grid on;
title('Button Press History');

try
    while (1)
        % シリアルポートからデータを読み取る
        if (srl_data_available(s))
            button = fgets(s);
            button = strtrim(button);  % 改行文字を削除
            
            % ボタンに応じた処理
            switch button
                case "A"
                    val = 1;
                    disp("Button A pressed");
                case "B"
                    val = 2;
                    disp("Button B pressed");
                case "C"
                    val = 3;
                    disp("Button C pressed");
                otherwise
                    val = 0;
            end
            
            % グラフの更新
            data = [data(2:end), val];
            figure(h);
            plot(data);
            ylim([-0.5, 3.5]);
            yticks([0 1 2 3]);
            yticklabels({'None', 'A', 'B', 'C'});
            grid on;
            title('Button Press History');
            drawnow;
        end
        
        pause(0.01);
    end
catch
    % エラー時やCtrl+Cで終了時の処理
    disp("Closing serial port...");
    fclose(s);
    delete(s);
    close all;
end