Problem with Serial.read and bigger numbers

Hey guys,

I've got a problem with my code...
The code should read a frequency and generate a square-wave signal but I can't read numbers bigger than 9.

int Ausgangspin = 13;  
double Frequenz;

void setup(){
  pinMode(Ausgangspin, OUTPUT);
  Serial.begin(9600);
  Serial.println("Bitte angeben wieviel Hz ausgegeben werden sollen:");

}

void loop(){
  Frequenz = Eingabe();	                                                 //Eingabe-Funktion, gibt die Frequenz zurück.
  Serial.print("Es wird gesetzt: ");
  Serial.print(Frequenz,DEC);
  Serial.println("Hz!");
  //tone(Ausgangspin, Frequenz);	                                 // Ausgabe der frequenz ohne abhängigkeit der Zeit
}

int Eingabe(){
 int  i = 0;                                                            //Ziffern-Zähler rücksetzen
 unsigned char Data[6];			                                         // String zum einlesen der Zahlen

  do 
  {
    if (Serial.available())                                              // Wenn Daten verfügbar 5 Zeichen in Data schreiben
    {
      Data[i] = Serial.read() - '0';	                                 //umwandlung zu DEC
      i++;
    }
  } 
  while (i<5);
  
  return atof(Data);                                                    //return Zeichenkette -> Zahl (DEC)
}

but I already tried something else (Well it didn't work either)

int  i = 0, f = 0; //Ziffern-Zähler rücksetzen
char Data[6];			                                         // String zum einlesen der Zahlen

 if (Serial.available()>0)
 {
    for (i=0 ; Serial.available() >0&& i<5 ; i++)
    { 
    Data[i] = Serial.read();
    
    }
    Serial.flush();
    
    Serial.println(atof(Data));
    
 }

If I want to get a numeric output of the number 50 I get it as 5.00 and 0.00

thanks for any kind of help
Raavgo

for (i=0 ; Serial.available() >0&& i<5 ; i++)
    { 
    Data[i] = Serial.read();
    
    }

When you get to the start of this for loop, you will probably have just one character available to read.
After one iteration of the for loop, you will probably have no more characters available to read.
How many times will the loop iterate?

A clue as to what is sending the data would be useful.

considered this variation?

 if (Serial.available() >= 5)  // <<<<<<<< 
 {
    for (i = 0 ; i < 5; i++)
    { 
       Data[i] = Serial.read();
    }
    Serial.flush();
    Serial.println(atof(Data));
 }

considered this variation?

I'd be more likely to consider that if the useless Serial.flush() was removed.

My Problem is I want to read numbers from the Serial Monitor.
The range should be from 1 to 99999 but I'm messing up somehow.,
I'm able to only read 5 digit numbers so if I want to write 10 I'd have to write 00010.

thank you
for any kind of help
Raavgo

I'm able to only read 5 digit numbers so if I want to write 10 I'd have to write 00010.

That wouldn't be the case if you used end of packet markers. The Serial Monitor can even add them for you.

I'm able to only read 5 digit numbers so if I want to write 10 I'd have to write 00010.

There are a couple of things to bear in mind here:

  1. An Arduino "int" holds at most only five decimal digits. To hold more, you need a "long" or unsigned long". Or even a "long long"
  2. Some methods of converting ASCII to "int" will consider "00010" to have the decimal value 8 - a leading '0' denotes an octal value.

AWOL:

I'm able to only read 5 digit numbers so if I want to write 10 I'd have to write 00010.

There are a couple of things to bear in mind here:

  1. An Arduino "int" holds at most only five decimal digits. To hold more, you need a "long" or unsigned long". Or even a "long long"
  2. Some methods of converting ASCII to "int" will consider "00010" to have the decimal value 8 - a leading '0' denotes an octal value.

an int can also hold a - sign ==> in theory in 50% of the cases (in practice probably less)
an unsigned int will hold 5

Signed or unsigned, a sixteen bit "int" will only ever hold five decimal digits.

PaulS:

I'm able to only read 5 digit numbers so if I want to write 10 I'd have to write 00010.

That wouldn't be the case if you used end of packet markers. The Serial Monitor can even add them for you.

Could you give me a example how to read the number 50000 out of a serial Monitor and store it in a int or unsigned int?

There are plenty of examples out there, but one hint would be to set the line-ending in the serial monitor to "Newline", instead of the default "No line ending"

This code uses start and end of packet markers:

#define SOP '<'
#define EOP '>'

bool started = false;
bool ended = false;

char inData[80];
byte index;

void setup()
{
   Serial.begin(57600);
   // Other stuff...
}

void loop()
{
  // Read all serial data available, as fast as possible
  while(Serial.available() > 0)
  {
    char inChar = Serial.read();
    if(inChar == SOP)
    {
       index = 0;
       inData[index] = '\0';
       started = true;
       ended = false;
    }
    else if(inChar == EOP)
    {
       ended = true;
       break;
    }
    else
    {
      if(index < 79)
      {
        inData[index] = inChar;
        index++;
        inData[index] = '\0';
      }
    }
  }

  // We are here either because all pending serial
  // data has been read OR because an end of
  // packet marker arrived. Which is it?
  if(started && ended)
  {
    // The end of packet marker arrived. Process the packet

    // Reset for the next packet
    started = false;
    ended = false;
    index = 0;
    inData[index] = '\0';
  }
}

Where it says "Process the packet"., you do whatever you need to do with the serial data, stored in inData. You could remove SOP and the started flag (and related code) if you only want to use an end-of-packet marker.

No need to muck about with character arrays or strings, or packet monitors for that matter.

You can simply multiply what you already have by 10 and then add the new digit.
But you have to start from 0.
So if I type the number 753:
It sees 7 and figures (010)+7 to get 7.
Then it sees 5 and figures (7
10)+5 to get 75.
Then is sees 3 and figures (75*10)+3 to get 753.

Here is my version of Eingabe(). Note its simplicity.
Please test it and tell me if it works correctly for you.

unsigned long Eingabe(){
  unsigned long value = 0;
  char char_in = -1;
  while (Serial.available())   // just keep reading characters
  {
    char_in = Serial.read();
    if (char_in != -1) {       // check to make sure there is a character
      if ((char_in >= '0') && (char_in <= '9')) {  // is it a digit?
        value *= 10;                               // multiply total by 10
        value += (char_in - '0');                  // add numeric value of new character
      }
      else return value;   // if the new character is not a digit, then we are done
    }
  }
  return 0; // in case Serial doesn't seem to be working  
}

(Oops! I just corrected a typo.)

Odometer: There's a problem with your code - it assumes all the data it needs to read from the serial line is already there.

My mistake! Here's the corrected version:

unsigned long Eingabe(){
  unsigned long value = 0;
  char char_in = -1;
  while (true) {
    char_in = Serial.read();
    if (char_in != -1) {       // check to make sure there is a character
      if ((char_in >= '0') && (char_in <= '9')) {  // is it a digit?
        value *= 10;                               // multiply total by 10
        value += (char_in - '0');                  // add numeric value of new character
      }
      else return value;   // if the new character is not a digit, then we are done
    }
  } 
}

NOTE: I fixed another stupid bug. And another.
I can't see shit with this new layout.

That still doesn't address the issue of serial data trickling in slowly. It still assumes that the entire packet is available to be read when the function is called.

PaulS:
That still doesn't address the issue of serial data trickling in slowly. It still assumes that the entire packet is available to be read when the function is called.

It's not really a problem if you can type way faster than the arduino can read.

Some terminal programs send stuff only after a linefeed is entered, it will mostly work in that case.
I agree checking for an end of transmission marker of some sorts is always a good idea, packing data in a verifiable format an even better one. It makes for a less challenging debugging experience, although it does take away the surprise factor.

Pieter

It's not really a problem if you can type way faster than the arduino can read.

It is a problem UNLESS you can get serial data in faster than the Arduino can read it. And, that is not possible.

Some terminal programs send stuff only after a linefeed is entered, it will mostly work in that case.

So? Data is still sent, and received, one character at a time. Sssslllloooowwwwllllyyyy. Way slower than the Arduino can read it.

although it does take away the surprise factor.

You say that like that's a bad thing. 8)

So? Data is still sent, and received, one character at a time. Sssslllloooowwwwllllyyyy. Way slower than the Arduino can read it.

Try it, you'll be surprised! (I guess there's some buffering going on, make sure the loop function has something to do or build in a delay)

You say that like that's a bad thing. smiley-cool

It is. Writing / testing software that works as specified is really boring. Bugs create some excitement, especially if they come with bangs, flashes, sparks or smoke (or upset marketing people)!

Pieter