serial problem

Hello guys,
finally today I got arduino one and I could stop doing tests with the simulator.
I tried the following sketch

char t[2];
int a=0;
void setup()
{
  Serial.begin(9600); 
  Serial.flush();


}
void loop()
{   
  if (Serial.available()>0)
  {
    for (int i=0;i<2;i++){

      t[i]=Serial.read();
      a++;
      
    }
    if (a>0){
      
    Serial.print(t[0]);
    Serial.print(t[1]);
    a=0;
    }
    delay (2000);

  }
}

I just tried to read two numbers from the serial and rewrite them.
sending 50 to the serial port
The output I got is as follows:

5
-49
0
-35

thanks to all who will help me :slight_smile:

What have you got the line ending option set to in the Serial monitor ?

thanks for the reply
I have however solved by changing so:

char t[2];
int a=0;
void setup()
{
  Serial.begin(9600); 
  Serial.flush();


}
void loop()
{   
  if (Serial.available()>0)
  {
    for (int i=0;i<2;i++){
if (Serial.available()>0){
      t[i]=Serial.read();
      a++;
}
    }
    if (a>0){
      
    Serial.print(t[0]);
    Serial.print(t[1]);
    a=0;
    }
    delay (2000);

  }
}

Now I have a new problem,
I read the number 50 I would use it in a variable for the operations.
how to do it?

  Serial.flush();

Why? You've just opened the serial port. You've sent nothing. Why are you waiting for that nothing to be shifted out?

PaulS:

  Serial.flush();

Why? You've just opened the serial port. You've sent nothing. Why are you waiting for that nothing to be shifted out?

:stuck_out_tongue:
a test that I forgot to delete :stuck_out_tongue:

  if (Serial.available()>0)
  {
    for (int i=0;i<2;i++){

      t[i]=Serial.read();
      a++;
      
    }

You check if there is one or more characters to read, then immediately read two characters - this won't work, never
read characters before they have arrived, you need to change the test to:

  if (Serial.available () >= 2)

Super simple string capture and return to serial monitor.

// zoomkat 7-30-11 serial I/O string test
// type a string in serial monitor. then send or enter
// for IDE 0019 and later

String readString;

void setup() {
  Serial.begin(9600);
  Serial.println("serial test 0021"); // so I can keep track of what is loaded
}

void loop() {

  while (Serial.available()) {
    delay(2);  //delay to allow byte to arrive in input buffer
    char c = Serial.read();
    readString += c;
  }

  if (readString.length() >0) {
    Serial.println(readString);

    readString="";
  } 
}

zoomkat:

/void loop() {

while (Serial.available()) {
    delay(2);  //delay to allow byte to arrive in input buffer
    char c = Serial.read();

You shouldn't ever need delays in serial code. Either the byte is there or not (which you test by Serial.available). Adding a delay fails in multiple ways, for example if the sender added a delay between sending each byte, or if you change the baud rate.

//delay to allow byte to arrive in input buffer

If Serial.available is non-zero then there is a byte in the input buffer.

You shouldn't ever need delays in serial code. Either the byte is there or not (which you test by Serial.available). Adding a delay fails in multiple ways, for example if the sender added a delay between sending each byte, or if you change the baud rate.

Surprising. :roll_eyes: Load the code I posted with the delay removed, then copy/paste "You shouldn't ever need delays in serial code. Either the byte is there or not (which you test by Serial.available)" into the serial monitor and send it to the arduino. Do you get back what you expected?

Do you get back what you expected?

Yes. A nasty mess to be sure, but delay isn't the right way of preventing it.

wildbill:

Do you get back what you expected?

Yes. A nasty mess to be sure, but delay isn't the right way of preventing it.

Did you get the nasty mess with the delay included? The "right way" is sometimes context dependent, and in this case if it gets the OP started with the project, then it is more appropriate than a lot of so far non productive "guidance".

it is more appropriate than a lot of so far non productive "guidance".

Is that aimed at me? I gave a comprehensive guide above, I'll just repeat it:

Building in delays just papers over the fact that the code is doing it the wrong way. To save you the trouble of going to that page I'll reproduce the first example here:

// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;

void setup ()
{
  Serial.begin(9600);
} // end of setup

// here to process incoming serial data after a terminator received
void process_data (char * data)
  {
  // for now just display it
  Serial.println (data);
  }  // end of process_data

void loop()
{
static char input_line [MAX_INPUT];
static unsigned int input_pos = 0;

  if (Serial.available () > 0) 
    {
    char inByte = Serial.read ();

    switch (inByte)
      {
      case '\n':   // end of text
        input_line [input_pos] = 0;  // terminating null byte
        
        // terminator reached! process input_line here ...
        process_data (input_line);
        
        // reset buffer for next time
        input_pos = 0;  
        break;
  
      case '\r':   // discard carriage return
        break;
  
      default:
        // keep adding if not full ... allow for terminating null byte
        if (input_pos < (MAX_INPUT - 1))
          input_line [input_pos++] = inByte;
        break;

      }  // end of switch

  }  // end of incoming data

  // do other stuff here like testing digital input (button presses) ...

}  // end of loop

That echoes back what you type in, without using delays. It's not "non productive "guidance" ", it's code that works, doesn't need tweaking for different baud rates, doesn't fail if the sending end slows down for some reason, and doesn't slow down the main loop with delays, which would therefore slow down other things you might want to do, like test button presses, adjust motors, etc.

That echoes back what you type in, without using delays. It's not "non productive "guidance" ", it's code that works, doesn't need tweaking for different baud rates, doesn't fail if the sending end slows down for some reason, and doesn't slow down the main loop with delays, which would therefore slow down other things you might want to do, like test button presses, adjust motors, etc.

Well, I loaded the code you posted into the arduino, copy/pasted "That echoes back what you type in, without using delays. It's not "non productive "guidance" ", it's code that works," in the serial monitor, and sent it to the arduino, and nothing came back. So is your "guidance" productive or more confusing for the OP? Did you tell the OP that the serial monitor default settings will need to be changed for your code to work? :roll_eyes:

zoomkat:
So is your "guidance" productive or more confusing for the OP?

It's productive, IMO, and represents best practice for handling serial port input.

zoomkat:
Well, I loaded the code you posted into the arduino, copy/pasted ... in the serial monitor, and sent it to the arduino, and nothing came back..

Yes, well you exceeded the buffer size, didn't you? In the original post the poster was looking for two characters.

However you raise an interesting point. My code as published looks for a newline, which it will never get if the buffer fills up. I'll amend it to allow for that situation.

Yes, you'll need to change the serial monitor settings to send a newline, but having text terminated by just "waiting a while" really isn't good practice, and you don't want to encourage it.

Well, I was wrong. The published code does work, regardless of the buffer size (it just discards the excess) so that's OK.

However, yes, you need to set the monitor to send a newline. You need to learn that, and this is a good place to teach it.

It is better to teach "set the line terminator in the serial monitor" rather than "build in delays and hope for the best".

You are teaching something one way or the other, and the way that works properly is the better thing to teach.

And the end-user needs to learn something. They need to learn how to use the IDE, to plug in the USB cable, etc. You can't insulate them from the need to learn things.

zoomkat:
Super simple string capture and return to serial monitor.

// zoomkat 7-30-11 serial I/O string test

// type a string in serial monitor. then send or enter
// for IDE 0019 and later

String readString;

...

Please note that in versions of the IDE up to and including 1.0.3, the String library has bugs as discussed here and here.

In particular, the dynamic memory allocation used by the String class may fail and cause random crashes.

I recommend reworking your code to manage without String. Use C-style strings instead (strcpy, strcat, strcmp, etc.), as described here for example.

Alternatively, install the fix described here: Fixing String Crashes

Preferably upgrade your IDE to version 1.0.4 or above at: http://arduino.cc/en/Main/Software


@whteice: Please read my thread: Gammon Forum : Electronics : Microprocessors : How to process incoming serial data without blocking

That covers getting serial data without using delay, and without blocking. It also covers extracting numbers from serial input. The stuff described there works, and works reliably.

thanks for the guide,
is truly complete :slight_smile: