Some wierd "Error" when using serial monitor

Hey.

First of all, i would like to say that the same "Error" comes on both my computers.

The arduino code looks like this:

#include <Servo.h>

int minPulse = 0;
int maxPulse = 180;
int center = 90;
int sdata;
int rater = 2;
int newPos;

Servo servo1;

void setup(){

servo1.attach(9);

Serial.begin(115200);
Serial.println("Vi begynder her.....");
Serial.println();

}

void loop(){

if(Serial.available() > 0){

sdata = Serial.read();
Serial.print(sdata);

do
{

if(newPos > sdata){
newPos = newPos - rater;
} else {
newPos = newPos + rater;
}

if(newPos > maxPulse){ newPos = maxPulse; }
if(newPos < minPulse){ newPos = minPulse; }

servo1.write(newPos);

Serial.print("Motoren er paa: ");
Serial.print(newPos);
Serial.print(" og forsoeager at ramme ");
Serial.print(sdata);
Serial.print("\n");
delay(1000);

} while(newPos != sdata) ;

}

}

The problem is, when open serial monitor, and what ever you type, it will change the number you entered, then it changes it to 49....

What is wrong with this picture?

Thanks in advance.

You are assuming that if you type "120" in the Serial Monitor, and press the send button, that the value in sdata will be 120. That is not the case. The string that you typed, "120" is composed of three characters, '1', '2', and '0'. The values in sdata will then be '1', '2', and '0'.

You need to include an end-of-packet marker ("45;", "8;", "129;", for example), then read serial data, as it becomes available, until the end of packet marker arrives. You need to store the data in an array (of characters), keeping the array NULL terminated, then use the atoi() function to convert the string to a number.

How esactly do i do that in code?

How should the script look like?

Thanks for the reply.

How should the script look like?

Something like this:

char inData[10];
byte index = 0;
bool ended = false;

void setup()
{
  // Whatever you need to do here...
}

void loop()
{
   while(Serial.available() > 0)
   {
      char inByte = Serial.read();
      if(inByte == ';')
      {
        ended = true;
        break;
     }

     inData[index++] = inByte;
     inData[index] = '\0';
   }

   if(ended)
   {
      int val = atoi(inData);
      // Do whatever with val

      inData[0] = '\0';
      index = 0;
      ended = false;
   }
}