0

I'm working on a arduino proyect, but I encountered a problem that I dont know how to solve.

The only thing I have done in the hardware part is connect the arduino nano to a power source (phone charger) through the 5v and Ground pins, but the built-in leds tell me that the code isn't running as it should be.
The TX led (Serial output) should be constantly on (because the code is always printing out things to the monitor), but instead it turns on and off in a longer interval of time, the code is running slower than it should be.
This stops when I touch ground with my finger or when the arduino is connected to a computer.

When I searched for a solution I found that most of the time this problem was related to missing connections to ground, and here seems to be the same, but the only thing I have connected is the arduino.

Any idea of what's happening and how to solve it?

To give more context, what I'm trying to do is a thermostat that can take a value of temperature and time, and turn on or off a relay. This relay is the one that opens or closes the electrical circuit of the lab's stove depending on the temperature and the time.
There are 4 buttons:
AUMENTAR ("increase" in english): increases the value selected in 5 (when pressed has a delay of 0.5 seconds).
DISMINUIR ("decrease"): decreases the value selected in 5 (when pressed has a delay of 0.5 seconds).
SIGUIENTE ("next"): changes the value you are editing (has no delay).
INI_DET ("start/stop"): starts or stops the machine (has no delay).

Code:

#include <max6675.h>
#include <LiquidCrystal.h>

//
// VARIABLES
//

// Machine's phisical state
int temperatura = 0; // en °C
int temperatura_prev;
// int humedad;
bool maquina_en_funcionamiento = false;

// User's variables (con la maquina no funcionando)
int array_de_valores[] = {20,10};     // valores editables por el usuario
int valor_seleccionado = 0;             // valor que se esta editando (por defecto, temperatura): 0=Temperatura, 1=Tiempo, 2=Humedad
// Variables visibles para el usuario (con la maquina funcionando)
int array_de_opciones[] = {0, 0};       // opciones visibles para el usuario
int opcion_seleccionada = 0;            // opcion visible (por defecto, maquina): 0=Maquina, 1=Operacion

// Process' variables
int temp_bus, tiempo_bus, hum_bus;  // copias de array_de_valores que se mantendran fijas hasta el final del proceso
int reloj = 0;                      // tiempo transcurrido en minutos desde que comenzo el proceso
int reloj_prev;
unsigned long reloj_milis;          // tiempo transcurrido en milisegundos desde que comenzo el proceso
unsigned long inicio_milis;         // milisegundos al comienzo de la operacion
int tiempo_restante;
bool resistencia_en_funcionamiento = false; // estado actual de la resistencia (por defecto, apagada)

// Phisical components
LiquidCrystal lcd(6,7, 2,3,4,5);
MAX6675 sensor_temp(16,15,14);
#define RELE 13
  // botones
#define AUMENTAR 8 // Aumentar valor
#define DISMINUIR 9 // Disminuir valor
#define SIGUIENTE 10 // Cambiar valor
bool sig_pres = false;
#define INI_DET 11 // Iniciar o Detener maquina
bool ini_det_pres = false;

//
// FUNCTIONS
//

// Funciones para control de lcd
void actualizarLCD() {
  if (!maquina_en_funcionamiento) { // si la maquina no esta en funcionamiento
    switch (valor_seleccionado){
      case 0: // temperatura
        lcd.home();
        lcd.print("»TEMP TIEMPO HUM");
        lcd.setCursor(5,1);
        lcd.print(array_de_valores[0]);
        lcd.setCursor(8,1);
        lcd.print("°C");
        break;
      case 1: // tiempo
        lcd.home();
        lcd.print(" TEMP»TIEMPO HUM");
        lcd.setCursor(5,1);
        lcd.print(array_de_valores[1]);
        lcd.setCursor(8,1);
        lcd.print("min");
        break;
      case 2: // humedad
        lcd.home();
        lcd.print(" TEMP TIEMPO»HUM");
        lcd.setCursor(5,1);
        lcd.print(array_de_valores[2]);
        lcd.setCursor(8,1);
        lcd.print("%");
        break;
    }
  }
  else { // si la maquina esta en funcionamiento
    switch (opcion_seleccionada){
      case 0:
        lcd.home();
        lcd.print("»MAQUINA  OPERAC");
        lcd.setCursor(0,1);
        lcd.print("TEMP");
        lcd.setCursor(5,1);
        lcd.print(temperatura);
        lcd.setCursor(9,1);
        lcd.print("TIE");
        lcd.setCursor(13,1);
        lcd.print(tiempo_restante);
        break;
      case 1:
        lcd.home();
        lcd.print(" MAQUINA »OPERAC");
        lcd.setCursor(0,1);
        lcd.print("TEMP");
        lcd.setCursor(5,1);
        lcd.print(temp_bus);
        lcd.setCursor(9,1);
        lcd.print("TIE");
        lcd.setCursor(13,1);
        lcd.print(tiempo_bus);
        break;
    }
  }
}

// Funciones de variables editables por el usuario
void aumentarValor(int cantidad) {
  array_de_valores[valor_seleccionado] += cantidad;
  actualizarLCD();
}
void cambiarValor(){
  switch (valor_seleccionado){
    case 0:
      valor_seleccionado = 1;
      break;
    case 1:
      valor_seleccionado = 2;
      break;
    case 2:
      valor_seleccionado = 0;
      break;
  }
  actualizarLCD();
}

// Funciones de control de proceso
void iniciarResistencia() {
  digitalWrite(RELE, HIGH);
  resistencia_en_funcionamiento = true;
}
void detenerResistencia() {
  digitalWrite(RELE, LOW);
  resistencia_en_funcionamiento = false;
}

void iniciarProc() {
  // realizar una copia de los valores en array_de_valores
  temp_bus = array_de_valores[0];
  tiempo_bus = array_de_valores[1];
  inicio_milis = millis();

  // iniciar la maquina (cuando continue el ciclo)
  maquina_en_funcionamiento = true;

  actualizarLCD();
}
void detenerProc() {
  detenerResistencia();

  // borrar variables
  temp_bus = 0;
  tiempo_bus = 0;
  reloj_prev = 0;
  reloj_milis = 0;
  inicio_milis = 0;
  tiempo_restante = 0;

  maquina_en_funcionamiento = false;

  actualizarLCD();
}

//
// MAIN PROGRAM
//

void setup() {
  // codigo que se ejecuta una unica vez:
  Serial.begin(9600);
  Serial.println("INICIANDO PROGRAMA");

  // relay
  pinMode(RELE, OUTPUT);
  detenerResistencia();

  // buttons
  pinMode(AUMENTAR, INPUT);
  pinMode(DISMINUIR, INPUT);
  pinMode(SIGUIENTE, INPUT);
  pinMode(INI_DET, INPUT);

  //iniciar lcd
  lcd.begin(16,2);
  actualizarLCD();
}

void loop() { // codigo que se ejecuta en bucle:
  // buttons
  if (digitalRead(AUMENTAR) == HIGH) { // if button AUMENTAR is pressed
    if (!maquina_en_funcionamiento) {  // and the machine is not working
      aumentarValor(5);                // increase the value
      delay(500);                      // and wait
    }
  }
  else if (digitalRead(DISMINUIR) == HIGH) { // si se presiona el boton DISMINUIR
    if (!maquina_en_funcionamiento) {        // IDEM AUMENTAR
      aumentarValor(-5);
      delay(500);
    }
  }
  else if (digitalRead(SIGUIENTE) == HIGH) { // si se presiona el boton SIGUIENTE
    if (!sig_pres) {                         // verificar si no se lo presiono antes
      sig_pres = true;                       // poner la var sig_pres en true para bloquear el boton
      cambiarValor();                        // y cambiar la variable
    }
  }
  else if (digitalRead(INI_DET) == HIGH) {   // si se presiona el boton INI_DET
    if (!ini_det_pres) {                     // verificar si no se lo presiono antes
      ini_det_pres = true;                   // poner la var ini_det_pres en true para bloquear el boton
      if (!maquina_en_funcionamiento) {
        iniciarProc();
      }
      else {
        detenerProc();
      }
    }
  }

  if (digitalRead(SIGUIENTE) == LOW) {    // si el boton SIGUIENTE no esta siendo presionado
    if (sig_pres) {
      sig_pres = false;                   // desbloquear el boton
    }
  }
  if (digitalRead(INI_DET) == LOW) { // si el boton INI_DET no esta siendo presionado
    if (ini_det_pres) {
      ini_det_pres = false;               // desbloquear el boton
    }
  }

  // Some output of data to the Serial monitor
  Serial.print("Valor seleccionado: ");
  Serial.println(valor_seleccionado);
  Serial.print(array_de_valores[0]);
  Serial.print(", ");
  Serial.println(array_de_valores[1]);
  Serial.print("Maquina en funcionamiento: ");
  Serial.println(maquina_en_funcionamiento);

  // PROCESS CONTROL
  if(maquina_en_funcionamiento) {

    // TEMPERATURE CONTROL
    temperatura_prev = temperatura;
    temperatura = sensor_temp.readCelsius();

    if (temperatura >= temp_bus) { // si la temperatura es igual o exede la deseada
      detenerResistencia(); // apagar la resistencia
    }
    else { // si la temperatura es menor que la deseada
      if (!resistencia_en_funcionamiento) { // y la resistencia esta apagada
        iniciarResistencia();
      }
    }

    if (temperatura_prev != temperatura) {
      actualizarLCD();
    }

    // TIME CONTROL
    unsigned long milis_ahora = millis();
    milis_ahora -= inicio_milis;
    if ( (milis_ahora - reloj_milis) >= 1000){
      reloj_milis = reloj_milis + 1000;
    }

    reloj_prev = reloj;
    reloj = reloj_milis/60000;

    tiempo_restante = tiempo_bus - reloj;
    /*
    Serial.print("Reloj de milisegundos=");
    Serial.println(reloj_milis);
    Serial.print("Reloj=");
    Serial.println(reloj);
    Serial.print("Tiempo restante=");
    Serial.println(tiempo_restante);
    */
    if (reloj >= tiempo_bus) { // si se llego al tiempo deseado
      detenerProc(); // detener
    }

    if (reloj_prev != reloj) {
      actualizarLCD();
    }

  }
}

Thanks in advance.

8
  • Have you tried powering through the USB jack? And can you try the Blink sketch from the Arduino IDE? If that sketch works, there must be something wrong with the code, in which case you need to add it to your question.
    – chrisl
    May 26, 2019 at 19:50
  • 1
    if you read your post carefully, you will find out that you used a lot of words to say nothing more than that you have an arduino nano powered by a phone charger, running some unknown code, and that you think that the code execution is affected when you touch the arduino .... first thing that you need to do is to verify that you actually are affecting the program execution and not affecting the LEDs only
    – jsotola
    May 26, 2019 at 19:54
  • @chrisl The USB jack has the same problem, it only works when its connected to the PC. The Blink sketch works fine. I'll add the code to the post. May 26, 2019 at 22:57
  • @jsotola The execution is definetly getting affected, it runs slower than it should. May 26, 2019 at 22:58
  • You can check this link store.arduino.cc/usa/arduino-uno-rev3. Open Documentation tab. 5V.This pin outputs a regulated 5V from the regulator on the board. The board can be supplied with power either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of the board (7-12V). Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.
    – Amit Ray
    May 27, 2019 at 2:04

1 Answer 1

1

This stops when I touch ground with my finger or when the arduino is connected via USB to a computer.

It sure sounds like a grounding problem, probably between the PC and the Arduino. Try connecting the Arduino ground and the PC ground - my guess is that the problem goes away.

All of the electrical components in a system need to share the same ground for any communication to take place. It sounds like one of them might not.

Is either the PC or the charger plugged into the wall with an adapter that only carries two of the three wires? Usually each one will connect to ground side of the house circuit but if one of them doesn't ...

2
  • When the arduino is connected to the computer works as expected, but I can't depend on the computer like this. And I don't know what you mean with two or three wires, there are only two wires (5v and ground). May 26, 2019 at 22:55
  • JRobert, did you read the question? or event the part you quote?
    – Juraj
    May 27, 2019 at 5:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.