Serial read problem

Hi guys!

Working with Serial for the first time and having a problem. I'm sending strings like '554$' or '1500$' from my PC to arduino. Arduino code is:

    char buffer[] = {' ',' ',' ',' ',' '}; 
    while (!Serial.available());     // Wait for characters
    Serial.readBytesUntil(control, buffer, 5);
    pos = atoi(buffer);
    Serial.readBytes(buffer, 1);
    Serial.println(pos, DEC);

In my opinion, on my PC, I should receive data like '554' or '1500', but I have weird random chars (for example '8ie#' etc.)
Baud rate is checked. I'm not sure, if I understand readBytesUntil right...

Can anyone, please, tell me what I do wrong?

Thanks a lot.

Hi - you could just add one more element to that array, a zero to terminate it, then your existing code will work. You are getting trash because there's no end to the string.

eg. char buffer[] = {' ',' ',' ',' ',' ',0};

Alan

thanks :slight_smile: However I found out I probably have mistake on the PC side of communication.

Simple serial capture code you can try using the serial monitor.

//zoomkat 3-5-12 simple delimited ',' string parse 
//from serial port input (via serial monitor)
//and print result out serial port

String readString;
#include <Servo.h> 
Servo myservo;  // create servo object to control a servo 

void setup() {
  Serial.begin(9600);

  myservo.writeMicroseconds(1500); //set initial servo position if desired
  myservo.attach(7);  //the pin for the servo control 
  Serial.println("servo-delomit-test-22-dual-input"); // so I can keep track of what is loaded
}

void loop() {

  //expect a string like 700, or 1500, or 2000,
  //or like 30, or 90, or 180,

  if (Serial.available())  {
    char c = Serial.read();  //gets one byte from serial buffer
    if (c == ',') {
      if (readString.length() >0) {
        Serial.println(readString); //prints string to serial port out

        int n = readString.toInt();  //convert readString into a number

        // auto select appropriate value, copied from someone elses code.
        if(n >= 500)
        {
          Serial.print("writing Microseconds: ");
          Serial.println(n);
          myservo.writeMicroseconds(n);
        }
        else
        {   
          Serial.print("writing Angle: ");
          Serial.println(n);
          myservo.write(n);
        }

        //do stuff with the captured readString 
        readString=""; //clears variable for new input
      }
    }  
    else {     
      readString += c; //makes the string readString
    }
  }
}