簡體   English   中英

通過串口發送多個值

[英]Sending multiple values through serial port

我正在使用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);
}

因此,有沒有辦法做到這一點? 我需要像子串一樣的東西嗎?

提前謝謝,任何建議將不勝感激。

是的,你需要一個子串。

幸運的是,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...
       }
   }
#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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM