0

次のコードがあります。シリアルポート経由でデータを受信し、それをシリアルポートに出力することを意図しています。

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() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
Serial.write("Power On");
pinMode(pin, OUTPUT);
} 

char getValue()
{
index =0 ;  
int code =-1;
  while(Serial.available() > 0)
 {
  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
      code=1;
      }        
    }   
  return code;
}

メインループ:

void loop() 
{

 char response = getValue();

  if(response != -1)
  {
  Serial.println("ok");
  Serial.println( inData); 
  }

私が把握できない問題は、「45」を送信すると、次のように表示されることです。

"ok
4
ok
5"

「ok 45」ではありません

どうしてこれなの?Serial.avalible は読み取り可能なバイト数を返します。45 を送信すると 2 が返されますか?

4

1 に答える 1

0

I gett that in your loop your calling getvalue so quickly that you did not receive all the caracters already.

A simple solution for that is to send a code for the begining and the end of your message.

For instance use '\n' to say end of message.

Then modify get value to wait and continue to read until it find a '\n' as you never know how long it will take

于 2013-09-02T20:43:04.053 に答える