Serial.write(5) not able to send decimal?

487 Views Asked by At

I am trying, as a test to Serial.write the int value: 5, to serial monitor, and if received, i want to print the the text "SUCCESS!" to the serial monitor.

But when writing Serial.write((int)5); All i get in the serial monitor is: enter image description here

I have tried using Serial.println(5); which works fine, but then i am not able to read it.

My code:

enum read_states {
  Modtag_Adresse, 
  Modtag_Bit_Position_I_Adresse, 
  Modtag_Bit_Position_Vaerdi
};

enum read_states state;

void setup() {
  state = Modtag_Adresse;
  Serial.begin(9600);
}

void loop() {
  if(state == Modtag_Adresse) {
    Serial.write((int)5);
    delay(1000);

    if(Serial.available() > 0) {
      int serialReceived = Serial.read();

      if(serialReceived >= 0) {
          // Receive value 5
        Serial.print("SUCCESS!!");
      }
    }
  }

  else if(state == Modtag_Bit_Position_I_Adresse) {
    //
  }

  else if(state == Modtag_Bit_Position_Vaerdi) {
    //
  }

  else {
    // Failure.
  }
}
1

There are 1 best solutions below

0
On BEST ANSWER

Serial.write(5) sends the byte 5 to the computer. It appears as a square, because it's not an ASCII code of a letter or number or symbol.

Serial.print(5) sends the ASCII code for 5 (which is 53).

The reason you can't read what you wrote is because Serial.write sends data to the computer and Serial.read returns data received from the computer. If it read data from the Arduino program, it would be pointless because you don't need to use serial for that.