Question about the Serial.

Hello everyone. I'm a newbie with arduino and I have a little problem with the Serial. This is my code, very very simple:

int x=0;

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

}

void loop() {

  
  if(Serial.available()>0)
  {
    x=Serial.read();
   
  }

  Serial.print(x); Serial.println();
  
  delay(500);
}

The problem is that if I send a number through the Serial monitor the x has that value only for one iteration, it then changes to another. I dont really understand whats happening.

Perhaps you are sending a line ending character?

You should probably only print out 'x' when you read a new 'x', not every half second regardless:

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

void loop()
{
  if (Serial.available() > 0)
  {
    int x = Serial.read();
    Serial.println(x);
    delay(500);
  }
}

When I type "123(return)" into Serial Monitor set for "Newline" line endings, I get:

49
50
51
10

49 is the character code for '1'.
50 is the character code for '2'.
51 is the character code for '3'.
10 is the character code for '\n' (ASCII New Line)

Have a look at the examples in Serial Input Basics - simple reliable ways to receive data.

...R

Keep it on track.

When we open a circuit for analog (voice) communications, we carry a modulated signal independent of the language being spoken. Similarly, when a channel is opened for digital communications, a serial bit-stream is processed, independent of the protocol.