Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.
  }
}

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading