Convert serial.read() into a useable string using Arduino?

后端 未结 15 1062
盖世英雄少女心
盖世英雄少女心 2020-11-29 15:27

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

相关标签:
15条回答
  • 2020-11-29 16:28

    Many great answers, here is my 2 cents with exact functionality as requested in the question.

    Plus it should be a bit easier to read and debug.

    Code is tested up to 128 chars of input.

    Tested on Arduino uno r3 (Arduino IDE 1.6.8)

    Functionality:

    • Turns Arduino onboard led (pin 13) on or off using serial command input.

    Commands:

    • LED.ON
    • LED.OFF

    Note: Remember to change baud rate based on your board speed.

    // Turns Arduino onboard led (pin 13) on or off using serial command input.
    
    // Pin 13, a LED connected on most Arduino boards.
    int const LED = 13;
    
    // Serial Input Variables
    int intLoopCounter = 0;
    String strSerialInput = "";
    
    // the setup routine runs once when you press reset:
    void setup() 
    {
      // initialize the digital pin as an output.
      pinMode(LED, OUTPUT);
    
      // initialize serial port
      Serial.begin(250000); // CHANGE BAUD RATE based on the board speed.
    
      // initialized
      Serial.println("Initialized.");
    }
    
    // the loop routine runs over and over again forever:
    void loop() 
    {
      // Slow down a bit. 
      // Note: This may have to be increased for longer strings or increase the iteration in GetPossibleSerialData() function.
      delay(1);
      CheckAndExecuteSerialCommand();  
    }
    
    void CheckAndExecuteSerialCommand()
    {
      //Get Data from Serial
      String serialData = GetPossibleSerialData();
      bool commandAccepted = false;
    
      if (serialData.startsWith("LED.ON"))
      {
        commandAccepted = true;
        digitalWrite(LED, HIGH);   // turn the LED on (HIGH is the voltage level)
      }
      else if  (serialData.startsWith("LED.OFF"))
      {
        commandAccepted = true;
        digitalWrite(LED, LOW);    // turn the LED off by making the voltage LOW
      }
      else if (serialData != "")
      {
        Serial.println();
        Serial.println("*** Command Failed ***");
        Serial.println("\t" + serialData);
        Serial.println();
        Serial.println();
        Serial.println("*** Invalid Command ***");
        Serial.println();
        Serial.println("Try:");
        Serial.println("\tLED.ON");
        Serial.println("\tLED.OFF");
        Serial.println();
      }
    
      if (commandAccepted)
      {
        Serial.println();
        Serial.println("*** Command Executed ***");
        Serial.println("\t" + serialData);
        Serial.println();
      }
    }
    
    String GetPossibleSerialData()
    {
      String retVal;
      int iteration = 10; // 10 times the time it takes to do the main loop
      if (strSerialInput.length() > 0)
      {
        // Print the retreived string after looping 10(iteration) ex times
        if (intLoopCounter > strSerialInput.length() + iteration)
        {
            retVal = strSerialInput;
            strSerialInput = "";
            intLoopCounter = 0;
        } 
        intLoopCounter++;
      }
    
      return retVal;
    }
    
    void serialEvent()
    {  
      while (Serial.available())
      {    
        strSerialInput.concat((char) Serial.read());
      } 
    }
    
    0 讨论(0)
  • 2020-11-29 16:32

    This would be way easier:

     char data [21];
     int number_of_bytes_received;
    
     if(Serial.available() > 0)
     {
       number_of_bytes_received = Serial.readBytesUntil (13,data,20); // read bytes (max. 20) from buffer, untill <CR> (13). store bytes in data. count the bytes recieved.
       data[number_of_bytes_received] = 0; // add a 0 terminator to the char array
     } 
    
     bool result = strcmp (data, "whatever");
     // strcmp returns 0; if inputs match.
     // http://en.cppreference.com/w/c/string/byte/strcmp
    
    
     if (result == 0)
     {
       Serial.println("data matches whatever");
     } 
     else 
     {
       Serial.println("data does not match whatever");
     }
    
    0 讨论(0)
  • 2020-11-29 16:33

    Use string append operator on the serial.read(). It works better than string.concat()

    char r;
    string mystring = "";
    
    while(serial.available()) 
       {
        r = serial.read();
        mystring = mystring + r; 
       }
    

    After you are done saving the stream in a string(mystring, in this case), use SubString functions to extract what you are looking for.

    0 讨论(0)
提交回复
热议问题