Receiving RX data with circuit powered off/Issue reading digital sensor

Hello, i have a ultrasonic sensor from maxbotix (mb7060) which output delivers asynchronous serial with an RS232 format, except voltages are 0-Vcc. The output is an ASCII capital “R”, followed by three ASCII character digits representing the range in centimeters up to a maximum of 765, followed by a carriage return (ASCII 13). The baud rate is 9600, 8 bits, no parity, with one stop bit.
Because of RS232 format with TTL level (5 volts its a '0' and 0 volts its a '1') i have to put an TTL inverter to invert this voltages to arduino to understand it when it receives the readings on RX pin.
At this time, everything works great, but when i power off the circuit (inverter and sensor) and look at serial monitor of arduino it keeps reading zeros and sometimes 1 or 3!
My code is

#include <SPI.h>
#include <VirtualWire.h>

//DECLARAÇÃO DAS VARIÁVEIS GLOBAIS
//ENABLE/DISABLE PARA O SENSOR
const int sensor = 7;

//LED'S
const int ledTransmissao = 4;
const int ledActivacao = 5;

//ENABLE/DISABLE DO TRANSMISSOR E PINO DE TRANSMISSÃO
const int pinoTransmissao = 8;
const int pinoActTransm = 3;

//VARIÁVEL QUE GUARDA A MENSAGEM A TRANSMITIR
char mensagem[5];

//VARIÁVEIS PARA DADOS LIDOS DO SENSOR
int dados;
char buffer[4];

void setup(){
  
//DEFINIÇÃO DOS PINOS DE ENTRADA E DE SAÍDA
  pinMode(sensor, OUTPUT);
  pinMode(ledTransmissao, OUTPUT);
  pinMode(ledActivacao, OUTPUT);
  digitalWrite(sensor, LOW);
  //digitalWrite(pinoActTransm, LOW);
  digitalWrite(ledTransmissao, LOW);
  digitalWrite(ledActivacao, LOW);
  
//INICIAR A UART PARA DEBUG
  Serial.begin(9600);
  delay(100);
  
//CONFIGURAÇÃO DO VIRTUALWIRE -TRANSMISSÃO-
  vw_set_tx_pin(pinoTransmissao);
  vw_set_ptt_pin(pinoActTransm);
  vw_setup(2000);  //VELOCIDADE DE TRANSMISSÃO DE 2000 BITS POR SEGUNDO
}

void loop() {
 
//ENABLE DO SENSOR E LED DE ACTIVAÇÃO LIGADO
  digitalWrite(sensor, HIGH);
  digitalWrite(ledActivacao, HIGH);
  delay(100);
  
//LEITURA DOS DADOS ENVIADOS PELO SENSOR
  if ( Serial.available () > 0 ) {
    char c = Serial.read();
    if (c == 'R') {
     Serial.readBytesUntil ('\r', &buffer[0], 4);
  //mensagem = buffer;  //GUARDA DADOS RECEBIDOS DO SENSOR -ASCII--RXXX\R--
 
 //DISABLE DO SENSOR E LED DE ACTIVAÇÃO DESLIGADO
  digitalWrite(sensor, LOW);
  digitalWrite(ledActivacao, LOW);
  
  dados = atoi (buffer);  //CONVERSÃO DOS DADOS RECEBIDOS PARA VALORES INTEIROS
  Serial.print("BUFFER: ");
  Serial.println(buffer);

  
//ENVIO PARA A SÉRIE DO VALOR, PARA DEPURAÇÃO
  Serial.print("Valor recebido:");
  Serial.println(dados);
  memset(&buffer, 0, sizeof(buffer)); //LIMPEZA DO BUFFER
  Serial.print("Limpar buffer:");
  Serial.print(buffer);
  Serial.println("Em branco depois dos : SUCESSO!!!");
  
/*VERIFICAÇÃO SE OS DADOS RECEBIDOS DO SENSOR SÃO VÁLIDOS. O MÁXIMO
VALOR É 465 -ALTURA MÁXIMA DA ÁGUA- E O MÍNIMO É ZERO -TANQUE VAZIO-*/
  if(dados >= 1 && dados <= 465) {
    mensagem[0] = 'R';
    itoa (dados, &mensagem[1], 10);
    Serial.print("Mensagem a transmitir:");
    Serial.println(mensagem);
    
//LED DE TRANSMISSÃO ACTIVA LIGADO
    digitalWrite(ledTransmissao, HIGH);

//ENVIO DA MENSAGEM 2 VEZES PARA GARANTIR QUE É RECEBIDA   
    //for (int i = 0; i<2; i++){
    vw_send ((uint8_t*)mensagem, strlen(mensagem)); //ENVIO DA MENSAGEM
    vw_wait_tx(); //ESPERA QUE MENSAGEM SEJA TOTALMENTE ENVIADA
    delay(1);
   }
   
//LED DE TRANSMISSÃO ACTIVA DESLIGADO
    digitalWrite(ledTransmissao, LOW);
    memset(&mensagem, 0, sizeof(mensagem)); //LIMPA O BUFFER DA MENSAGEM ENVIADA
    Serial.print("Limpar mensagem:");
    Serial.print(mensagem);
    Serial.println("Em branco depois dos : SUCESSO!!!");
    delay(5000);
  }
   }
  }
//}

/*FIM DO PROGRAMA*/

I'm trying to get the values from reading, see if they are between 1 and 465 (the minimum and maximum distance i want) and then send by RF 433MHz to another arduino, that can't get any message because i thing something is making conflict with readings (like when sensor and inverter are powered off it should stay "paused" in serial monitor and not keep telling me it is reading like R0 or R1, R3 ?!?

Thanks for any help with this problem

It sounds like a floating input to me.

Can you explain a little more? :blush:

An input that is not tied to a specific voltage, usually ground or 5V, may pick up stray voltages and is said to be 'floating'

You turn off the sensor and inverter, and you get weird numbers. That is to be expected when the pin is essentially open. Your inverter is off but the pin is looking for any possible electrical activity. This is usually noise or outside EMF, and the only way to stop it, would be to let the arduino know the inverter is off. Now you wont be able to actually pause the readings unless you change your program to have a timer or look for the inverter to be off. However you can avoid numbers like 3 or 9 etc. with a pull down resistor. This pull down resistor will make the output read "R0" until the inverter tells it otherwise.

For the timer, if you want to use it. You can look at the incoming data from the inverter and if the data does NOT change after a certain time has passed, you can set the output to 0. This timer can also, (if coded correctly) can "pause" your readings and output nothing at all, or display your readings when a signal is found.

But i expected as i have in my program that only data started with an capital R must be looked at, and avoid any other data that could get in. if inverter and sensor are powered off any data that arduino can receive in RX pin must be all of thet you've said before. It's strange as it must be an R to arduino look at it. Am i right?

I too think an external resistor is a possible answer, however I think it should be of the pull-up variety as that is the idle/stopped state of a TTL serial data stream.

Lefty

When the power to the inverter is off, you have nothing to clear or reset "c" back to NULL. So Rxxx will stay inside the buffer until new data is available, to overwrite it.

When the power to the inverter is off, you have nothing to clear or reset "c" back to NULL. So Rxxx will stay inside the buffer until new data is available, to overwrite it.

but, memset(&buffer, 0, sizeof(buffer)); makes buffer cleared isn't it? (just trying to understand this :cold_sweat:)

Well when in doubt, debug! Use the serial monitor to see exactly what your getting, and im sure you will find your answer.

Yes, i've degub it, and keep getting readings of R0 and sometimes R1 or R3 with inverter and sensor powered off, and i'm trying to understand why, if my code only look at serial input starting with an 'R'. And i'm thinking if this can messed up with readings when sensor and inverter are working, because i'm trying to use virtualwires to send this value to another arduino by RF 433MHz, but i couldn't get any message received...
Thanks for being helping me :wink:

Could a pull-up resistor be a solution to this? Or maybe i can add something to my code to prevent it (I think serial data waiting state is 5v isn't it?)

blastboot:
Could a pull-up resistor be a solution to this? Or maybe i can add something to my code to prevent it (I think serial data waiting state is 5v isn't it?)

Isn't that what I stated in reply #6?

Lefty

Ok that is something i will test tomorrow. So at program level there's nothing that i could do (because current consumption minimize if i use the pull-up resister solution).

I've tested the pull-up resistor today and it worked. With inverter and sensor powered off it just stops getting data (as expected).
I've experienced another problem with my circuit as it sometimes, with everything working (powered on), reads strange values like some strange character, sometimes RRR or 70R ?!?
Can you check my code on the first post and check if i'm doing something wrong? Today i've tried many other possibilities and changed some parts of the code (essencially the serial read part) and keeps getting this issue sometimes and it is an intermittent issue. :~