本文介绍了使用 Arduino 将 serial.read() 转换为可用的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用两个 Arduino,使用 newsoftserial 和一个 RF 收发器相互发送纯文本字符串.>

每个字符串的长度可能是 20-30 个字符.如何将 Serial.read() 转换为字符串,以便我可以执行 if x == "testing statements" 等?

解决方案

来自帮助 Serial.Read() 获取字符串:

char inData[20];//为字符串分配一些空间字符 inChar=-1;//在哪里存储读取的字符字节索引 = 0;//索引到数组中;在哪里存储字符无效设置(){Serial.begin(9600);Serial.write(开机");}char Comp(char* This) {while (Serial.available() > 0)//不要读,除非//你知道有数据{if(index < 19)//比数组的大小少 1{inChar = Serial.read();//读取一个字符inData[index] = inChar;//存储它指数++;//增加下一个写入的位置inData[索引] = '\0';//null 终止字符串}}如果 (strcmp(inData,This) == 0) {for (int i=0;i Online\n");}if (Comp(m1 off")==0) {Serial.write(Motor 1 -> Offline\n");}}

I'm using two Arduinos to sent plain text strings to each other using newsoftserial and an RF transceiver.

Each string is perhaps 20-30 characters in length. How do I convert Serial.read() into a string so I can do if x == "testing statements", etc.?

解决方案

From Help with Serial.Read() getting string:

char inData[20]; // Allocate some space for the string
char inChar=-1; // Where to store the character read
byte index = 0; // Index into array; where to store the character

void setup() {
    Serial.begin(9600);
    Serial.write("Power On");
}

char Comp(char* This) {
    while (Serial.available() > 0) // Don't read unless
                                       // there you know there is data
    {
       if(index < 19) // One less than the size of the array
       {
           inChar = Serial.read(); // Read a character
           inData[index] = inChar; // Store it
           index++; // Increment where to write next
           inData[index] = '\0'; // Null terminate the string
       }
    }

    if (strcmp(inData,This)  == 0) {
       for (int i=0;i<19;i++) {
            inData[i]=0;
       }
       index=0;
       return(0);
    }
    else {
       return(1);
    }
}

void loop()
{
    if (Comp("m1 on")==0) {
        Serial.write("Motor 1 -> Online\n");
    }
    if (Comp("m1 off")==0) {
       Serial.write("Motor 1 -> Offline\n");
    }
}

这篇关于使用 Arduino 将 serial.read() 转换为可用的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 06:53