通过串口

时间:2017-08-17 23:48:07

标签: c++ c arduino arduino-uno arduino-ide

我正在使用Arduino UNO进行项目,但我不知道如何实现我想要的目标。我也是初学者,因此我有时候不知道如何使用某些功能来做我想做的事。

我基本上想要一次通过串行监视器发送3个值。

第一个值是一个指向运算符的字符串(A,S,M,D,P),然后我想再获取2个值。例如,如果我输入'A012556,它应该添加12和556,这将给我568。

目前我正在这样做,但是它要求分别输入每个输入。例如,它会要求操作符(我只能输入int,因为我不能让它接受字符串/字符),我将输入1(应该是A用于添加),然后它要求输入第一个数字,然后是第二个数字,然后将它们加在一起并输出结果。这很好,但这不是我想要实现的。

  Serial.println ("Enter your chosen operator");
  Serial.println ("A for Addition, S for Subtraction, M for Multiplication,");
  Serial.println ("D for Division, and P for Potentiometer: ");

  // Takes an input from the user
  int theOperator = dataInput();

  if (theOperator == 1) {
    // If input is equal to 1, carry out function 'addition()'
    addition();
  } else if ..............

上面是循环函数,它指向下面的函数。对于减法/乘法/除/等等,这是相同的。

  void addition() {

  Serial.println ("A");
  Serial.println ("Please enter first number in format nnn: ");
  firstNumber = dataInput(); // Asks the user to input the first set of numbers

  /* Message must be in format cnnnnnn
     therefore first number must be greater than or equal to -99 and less than or equal to 999*/
  if (firstNumber >= -99 && firstNumber <= 999) {
    Serial.println (firstNumber); // Prints the first set of numbers for the user to view
  }
  else {
    /* If the data input does not match the format cnnnnnn then this error message will display
       if the input is invalid the red LED will also turn on */
    digitalWrite(LED_RED, HIGH);
    Serial.println ("--------------- ERROR ---------------");
  }

  Serial.println ("Please enter second number in format nnn: ");
  secondNumber = dataInput(); // Asks the user to input the second set of numbers

  /* Message must be in format cnnnnnn
     therefore second number must be greater than or equal to -99 and less than or equal to 999*/
  if (secondNumber >= -99 && secondNumber <= 999) {
    // The LED will turn off if it was previously on because this is a valid input
    digitalWrite(LED_RED, LOW);
    Serial.println (secondNumber); // Prints the second set of numbers for the user to view
  }
  else {
    digitalWrite(LED_RED, HIGH);
    Serial.println ("--------------- ERROR ---------------");
  }

  /* Give time for the red error LED to stay on
     for the user to notice he/she has made an invalid input */
  delay(500);
  digitalWrite(LED_RED, LOW);

  // As this case is for addition, it will add the first and second numbers
  value = (firstNumber + secondNumber);

  Serial.print("Value: ");
  // Prints the value of the two sets of numbers so that the user can see the value of their message
  Serial.println(value);
}

因此,有没有办法做到这一点?我需要像子串这样的东西吗?

提前感谢您,任何建议都将不胜感激。

2 个答案:

答案 0 :(得分:1)

是的,你需要一个子字符串。

幸运的是,String提供了一个子字符串函数。

https://www.arduino.cc/en/Reference/StringSubstring

您的代码看起来有点像这样:

// expecting operation in for "oxxxyyy" where o is the operator, xxx, yyy operands.

   bool ParseOperation(String& strInput, char& op, int& x, int& y)
   {
       if (strInput.length() != 7)
           return false;

       op = strInput[0];
       x = atoi(strInput.substring(1, 4).c_str());
       y = atoi(strInput.substring(4).c_str());
       return true;
   }

   // call as:

   void loop()
   {
       String str;
       char op;
       int r, x, y;

       // read user input into str...

       if (ParseOperation(str, op, x, y))
       {
           switch(op)
           {
           case 'A': case 'a': 
               op = '+'; 
               r = x + y; 
               break;

           // etc...

           default:
                // print some error message...
                break;
           }
           // print x op y = r
       }
       else
       {
            // print error message...
       }
   }

答案 1 :(得分:1)

#include <string.h>
#include <SoftwareSerial.h>

#define RX_TIMEOUT = 5000; // wait until 5 second

void initSerial() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect
  }
}

int hex2int(char *hexStr) {
    int v = 0;
    while (*hexStr) {
        char c = *hexStr++; 

        if (c >= '0' && c <= '9') c = c - '0';
        else if (c >= 'a' && c <='f') c = c - 'a' + 10;
        else if (c >= 'A' && c <='F') c = c - 'A' + 10;    

        v = (v << 4) | (c & 0xF);
    }
    return v;
}

int main(){
    char data[128];

    initSerial();

    while (1) {
          // operator A
          // value1 ranges = 0x0000 - 0xFFFF (hex 2 bytes);
          // value2 ranges = 0x0000 - 0xFFFF (hex 2 bytes);
          // 
          // value1 = 10 (decimal) = 00 0A (hex 2 bytes)
          // value2 = 20 (decimal) = 00 14 (hex 2 bytes)
          // A  00 0A  00 14 
          Serial.println ("Enter A000A0014");

          unsigned long startTime = millis();
          int i = 0;
          do {
            int length = Serial.available();
            if(length > 0) {
                if(i >= 128) {
                    break;
                }
                data[i++] = Serial.read();
            }
          } while ( millis() - startTime < RX_TIMEOUT);              
          data[i] = '\0';

          if(data[0]== '\0') {
            Serial.println ("Time out.., try again!");
            continue;
          }

          char c1[2], c2[2];
          int v1, v2, v3;

          memcpy(c1, &data[1], 2); // data[1], data[2]
          v1 = hex2int(c1);

          memcpy(c2, &data[3], 2);  // data[3], data[4]
          v2 = hex2int(c2);

          switch(data[0]){
            case 'A':                   
                v3 = v1 + v2;
                Serial.write(v3);
                break;

            case 'S':                   
                v3 = v1 - v2;
                Serial.write(v3);
                break;

            case 'M':
                v3 = v1 * v2;
                Serial.write(v3);
                break;

            case 'D':
                v3 = v1 / v2;
                Serial.write(v3);
                break;

            case 'P':
                // todo
                break;

            default:
                // else
                break;
          }
    }
    return 0;
}