write to serial immediately after receiving

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

void loop()

{
	if (Serial.available()) {

		if (Serial.read() == 0x0D) {
			Serial.println("SENT");
			Serial.flush();

		}
				
	}
	delay(46);
	Serial.write(0x05);
	Serial.flush();
}

It writes SENT only after the delay and 0x45. How can i have it write immediately?

if (Serial.available())

only tests for one character. You need to change that to while (Serial.available()).

I don't understand the delay and what printing 0x05 accomplishes, but if you comment these out for testing, you'll find the "SENT" is printed immediately after receiving 0x0D. You might want to think about changing that test to == 0x0D || 0x0A as both are common line terminators.

same thing with while().

I need the delay because i need to send 0x05 every 46 ms.
Why is "SENT" only being sent after the delay? Even If I add a delay()/[code] write after [code]Serial.println("SENT"); it still only writes "SENT" after 0x05.

Can you provide proof of that?

Your continously writing ENQs. Somewhere in between the arduino receives a CR and writes "SENT\r\n". No way of seeing what is going on exactly.

It's not the same thing. Look at your code. When you first enter loop() (upon system reset) the serial buffer is empty. You'll be zipping around loop every 46ms printing 0x05 until there's something in the input buffer. When something is there, your while(Serial.available()) will continue to Serial.read() until it detects the terminator at which time "SENT" is printed. No delays, no 0x05. If you don't trust that, throw a Serial.println(millis()); in there and see for yourself.

Is the following that you want to achieve?

1. If (and only if) the data byte 0x0D comes from the InputBox of the Serial Monitor into the UNO, the UNO will send the message "SENT" to the Serial Monitor which will appear on the OutputBox of the Serial Monitor. To send 0x0D (ASCII code for Carriage Return) from the InputBox, you activate the option Carriage return in the formatting box (bottom of the InputBox) and click on the Send button.

2. If nothing is sent from the InputBox of the Serial Monitor, the UNO will keep sending 0x05 to the Serial Monitor. Because, 0x05 is an ASCII code for a non-printable character; so, change it to 0x35 and insert a delay of 1000 ms. You will be able to see that character 5 is being printed at 1-sec interval on the OutputBox of the Serial Monitor. You may remove the line (s) Serial.flush().

The slightly modified codes:

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

void loop()

{
  if (Serial.available()) 
  {

    if (Serial.read() == 0x0D) 
    {
      Serial.println();
      Serial.println("SENT");
   //   Serial.flush();

    }
        
  }
  //delay(46);
  Serial.write(0x35);//(0x05);
  //Serial.flush();
  delay(1000);
}