problem with returning Serial.Print ();

if(SerialButton){if(Serial.print("ok") > 0){LastSerial = 0;}}
Hello, I have a problem, I am using a mega arduino (third party with an integrated esp8266 board), but when I try to use this line, with the SerialButton variable in the HIGH value it does not pass through the second if, but the second if does It works on an arduino leonardo, for what it's worth, I'm trying to read if there is a valid serial connection on the Serial port (if there is an active serial monitor)

Welcome to the forum

Please post a complete sketch that illustrates the problem

Please follow the advice given in the link below when posting code, in particular the section entitled 'Posting code and common code problems'

Use code tags (the </> icon above the compose window) to make it easier to read and copy for examination

The Serial does not know whether something is connected to its Tx output.

(Serial.print("ok") > 0) will always be true, because the print function returns the number of bytes written.

I do not know of any way for a Mega to detect if there is something receiving the serial data it is sending, that would require that the receiving device send some indication of its presence, and even then the receiver could be completely ignoring the data being sent by the Mega.

in this case, that the communication is valid means that you have an open terminal on the pc

the line described above works in a leonardo, but it does not work for me in the mega

Communication is different (bidirectional) from only writing to a communication channel.

A Mega, with a separate USB controller, has no communication protocol or other means for detecting the presence of a device or program listening to its Tx pin. Other controllers may detect at least the presence of an USB host. Detection of a BT transceiver is not implemented on an original Mega.

Leonardo and Mega are very different in respect to their connection to the PC. Leonardo has a native USB interface, which means the Leonardo 'knows' if there is a USB connection established, and it will not send anything if not.
The Mega only has a standard UART interface and a separate TTLserial-USB converter. An UART interface doesn't know if there is anything connected to its TX interface. It will send the bytes any way, no matter if there is a receiver or not.

If you send something via the UART interface of the Leonardo, it will behave the same way as the Mega.

And you know if that can be done in some way?

You must define a protokoll between the communication partners. If you send something, the other side must return some kind of acknowledge. If that isn't received in a predefined amount of time, then the other side is down.

1 Like