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?

やっとできた!Arduinoに文字列を送信して操作するよ

Last updated at Posted at 2023-03-26

 Arduinoは、Serial通信で1文字受信しか出来ないんだと思い込んでましたが出来るんですね。他にも教えてくださるところがありましたが
https://rabbitprogram.com/archives/1325
次のサイトを参考にしました。
https://www.delftstack.com/ja/howto/arduino/arduino-serial-read-string/
 シリアル通信で受信した文字列を分割させて4つのLEDの明るさと点灯時間を操作するようにしてみました。今回使ったArduino互換ボードは、良く分かりませんが格安で購入したLGT8F32P(Nano互換品)です。TypeCコネクタで使い易いです。
文字操作1.jpg
ポイントは

while (Serial.available() == 0) {}   // wait for data available
String input = Serial.readString();  // read until timeout

ですね。これだけで一連の文字列の受信を待って格納してくれます。その文字列を

input.trim();
Serial.println(input);
n = input.substring(0).toInt();
l = input.substring(2, 5).toInt();
m = input.substring(6).toInt();

のように分割して、LED番号・明るさ(On,Off)・点灯時間(秒)としています。
なお、ここでのLED2番・4番ピンはdigitalWriteしかできないので、Onは0以上の3桁、Offは「000」と入力します。起動直後はこんな感じです。
文字操作2.jpg
ここでArduinoIDE内蔵のモニターを開いて、文字列(数字とスペース)を打ち込みます。「Tera Term」では、設定なのか終端文字の送信の関係か、うまくいかないです。
文字操作3.jpg
 以下が Arduino IDE 1.8 でのスケッチです。

int n, l, m, q;
char *data = "3 100 1"; // 例として。3番、明るさ100、1秒間点灯

void setup() {
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  Serial.begin(9600);
  Serial.println(data);
  digitalWrite(2, HIGH);
  analogWrite(3, 10);
  digitalWrite(4, HIGH);
  analogWrite(5, 10);
}

void loop() {
  l = 0;
  m = 0;
  n = 0;
  Serial.println("Input No. Brightness delay(%1d %3d %1d):");
  while (Serial.available() == 0) {}   //wait for data available
  String input = Serial.readString();  //read until timeout
  input.trim();
  Serial.println(input);
  n = input.substring(0).toInt();
  l = input.substring(2, 5).toInt();
  m = input.substring(6).toInt();
  Serial.print(n);
  Serial.print(" ");
  Serial.print(l);
  Serial.print(" ");
  Serial.println(m);

  if ((n > 1 && n < 6) && (l >= 0 && l < 256)) {
    if (n == 2 || n == 4) {
      if (l > 0) {
        digitalWrite(n, HIGH);
        delay(m * 1000);
        digitalWrite(n, LOW);
      } else {
        digitalWrite(n, LOW);
      }
    } else {
      analogWrite(n, l);
      delay(m * 1000);
      analogWrite(n, 0);
    }
  } else {
    Serial.println("incorrect Input");
  }
}

文字列分割の部分はもう少し改良したいですが、かえって長くなるので今のところはこれで。
 Arduinoをシリアル通信の文字列で操作可能だと、プログラミングの幅が増えるので色々試したくなりますね。

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?