转换serial.read()到使用Arduino的一个可用的字符串? [英] Convert serial.read() into a useable string using Arduino?

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

问题描述

我用两个Arduinos使用newsoftserial和 RF收发器对发送纯文本字符串对方。

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

每个字符串也许是长度20〜30个字符。如何转换 Serial.read()成字符串所以我可以做如果x ==测试报告等等?

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.?

推荐答案

从的与Serial.Read帮助()获取字符串 的:

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");
    }
}

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆