Skip to content

Instantly share code, notes, and snippets.

@KeitetsuWorks
Created February 14, 2021 07:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KeitetsuWorks/86de00fbad889d649937b94235ef4d0d to your computer and use it in GitHub Desktop.
Save KeitetsuWorks/86de00fbad889d649937b94235ef4d0d to your computer and use it in GitHub Desktop.
Arduino Sample Code
/**
* @file qiita_6a18249a31a87dad84e2.ino
* @brief Arduino Sample Code
* @author Keitetsu
* @date 2021/02/14
* @copyright Copyright (c) 2021 Keitetsu
* @par License
* This software is released under the MIT License.
*/
#define ELEMENTS_NUM 10 /**< カンマ区切りデータの項目数 */
/**
* @brief 受信済み文字列を格納する配列
*/
static String elements[ELEMENTS_NUM];
static int received_elements_num = 0; /**< 受信済み文字列の数 */
/**
* @brief セットアップ関数
*/
void setup()
{
Serial.begin(9600);
}
/**
* @brief ループ関数
*/
void loop()
{
String line; // 受信文字列
unsigned int beginIndex; // 要素の開始位置
// シリアルモニタやProcessingから"AB,C,DEF,12,3,45,A1,2B,-1,+127"のように
// ELEMENTS_NUM個の文字列の間にカンマを付けて送る
// 送信側の改行設定は「LFのみ」にすること
// シリアル通信で1行(改行コードまで)読み込む
line = Serial.readStringUntil('\n');
beginIndex = 0;
for (received_elements_num = 0; received_elements_num < ELEMENTS_NUM; received_elements_num++) {
// 最後の要素ではない場合
if (received_elements_num != (ELEMENTS_NUM - 1)) {
// 要素の開始位置から,カンマの位置を検索する
unsigned int endIndex;
endIndex = line.indexOf(',', beginIndex);
// カンマが見つかった場合
if (endIndex != -1) {
// 文字列を切り出して配列に格納する
elements[received_elements_num] = line.substring(beginIndex, endIndex);
// 要素の開始位置を更新する
beginIndex = endIndex + 1;
}
// カンマが見つからなかった場合はfor文を中断する
else {
break;
}
}
// 最後の要素の場合
else {
elements[received_elements_num] = line.substring(beginIndex);
}
}
// 受信済み文字列の数がELEMENTS_NUM以上の場合
if (received_elements_num >= ELEMENTS_NUM) {
// 受信済み文字列をスラッシュ区切りでシリアルモニタに送信する
for (int i = 0; i < ELEMENTS_NUM; i++) {
Serial.print(elements[i]);
Serial.print("/");
}
Serial.println();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment