Oled with encoder do no turn on

I got a problem wit my esp32 and the next divices, oled display (128*32), rotary encoder, num pad 4x4, and relay module 5v when im trying to turn on the circuit with all connected the oled display didnt turn on, but when i disconnect the circuit and take off the encoder the oled turns on.

#include <Wire.h> 
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Keypad.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 32
#define OLED_RESET    -1

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

// Credenciales de WiFi



// Configuración del teclado
const byte ROWS = 4; 
const byte COLS = 4; 
char keys[ROWS][COLS] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};

byte rowPins[ROWS] = {33, 25, 26, 27}; 
byte colPins[COLS] = {32, 14, 12, 13}; 

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

//const int outputPin = 2; 
const int clkPin = 0;   
const int dtPin = 4;    
const int swPin = 16;   
const int relayPin = 2;  // Pin para controlar el relé (relé conectado al pin 24)
unsigned long relayActivationTime = 0;  // Tiempo en el que se activó el relé
const unsigned long relayDuration = 5000;  // Duración del relé en milisegundos
bool relayActive = false;  // Estado del relé

volatile int pulseCount = 0; 
const int pulsesPerMeter = 100; 
float distance = 0.0; 
volatile bool buttonPressed = false;

volatile int lastCLK = LOW;

// Variable para almacenar el nombre del ESP32
String espName = "TMXSA01";  
int serienumber = 25322813; // número de serie de la máquina 

// Datos del usuario
String pieceNumber = "";
String workerNumber = "";

// Prototipos de funciones
void handleEncoder();
void handleButton();
void resetSystem();
void registerUser();
int sendData(String pieceNumber, String workerNumber);
String getInput();
void sendEncoderData();
void resetEncoder();
void relayOn();

bool userRegistered = false; // Variable para controlar el registro

void IRAM_ATTR handleEncoder() {
  int currentCLK = digitalRead(clkPin);
  if (currentCLK != lastCLK) {
    if (digitalRead(dtPin) != currentCLK) {
      pulseCount++; 
    } else {
      pulseCount--; 
    }
  }
  lastCLK = currentCLK; 
}

void IRAM_ATTR handleButton() {
  buttonPressed = true; 
}


void setup() {
  Serial.begin(115200);
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  display.clearDisplay();

  // Configuración del pin 24 como salida para controlar el relé
  pinMode(relayPin, OUTPUT);
  digitalWrite(relayPin, LOW);  // Inicialmente apagado

  // Pantalla de bienvenida
  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 0);
  display.println("Bienvenido al");
  display.println("Sistema TEMSA");
  display.println("Maquina 019");
  display.display();
  delay(2000);
  display.clearDisplay();

  // Conectar a WiFi
  display.setCursor(0, 0);
  display.println("Conectando a WiFi...");
  display.display();
  WiFi.begin(ssid, password);

  int attempts = 0;
  while (WiFi.status() != WL_CONNECTED && attempts < 20) {
    delay(500);
    display.print(".");
    display.display();
    attempts++;
  }

  if (WiFi.status() != WL_CONNECTED) {
    display.clearDisplay();
    display.setCursor(0, 0);
    display.println("Fallo en la");
    display.println("conexion WiFi!");
    display.display();
    delay(3000);
    ESP.restart();
  } else {
    display.clearDisplay();
    display.setCursor(0, 0);
    display.println("Conectado!");
    display.print("IP: ");
    display.println(WiFi.localIP());
    display.display();
    delay(2000);
    display.clearDisplay();
  }

 // pinMode(outputPin, OUTPUT);
//  digitalWrite(outputPin, LOW);

  pinMode(clkPin, INPUT_PULLUP);
  pinMode(dtPin, INPUT_PULLUP);
  pinMode(swPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(clkPin), handleEncoder, CHANGE);
  attachInterrupt(digitalPinToInterrupt(swPin), handleButton, FALLING);

  registerUser();
}

void loop() {
  

  if (userRegistered) {
    distance = pulseCount / (float)pulsesPerMeter;

    display.clearDisplay();
    display.setCursor(0, 0);
    display.print("Distancia: ");
    display.print(distance);
    display.println(" m");
    display.display();

    char key = keypad.getKey();
    if (key == '*') {
      resetSystem();
    } else if (key == 'D') {
      sendEncoderData();
      resetEncoder();
      ESP.restart();
    }
  }
}

void relayOn() {
  digitalWrite(relayPin, HIGH);  // Encender el relé
  relayActivationTime = millis();  // Registrar el tiempo de activación
  relayActive = true;  // Marcar el relé como activo
  Serial.println("rele activado");
  delay(2000);
}


void registerUser() {
  // Obtener número de pieza
  while (true) {
    display.clearDisplay();
    display.setCursor(0, 0);
    display.println("Num. de pieza:");
    display.display();

    pieceNumber = getInput();  
    if (pieceNumber.length() > 0) break; // Salir del bucle si se ingresa algo
  }

  // Obtener número de trabajador
  while (true) {
    display.clearDisplay();
    display.setCursor(0, 0);
    display.println("Num. de trabajador:");
    display.display();

    workerNumber = getInput();  
    if (workerNumber.length() > 0) break; // Salir del bucle si se ingresa algo
  }

  // Enviar datos
  int responseCode = sendData(pieceNumber, workerNumber);
  if (responseCode == 201) {
    userRegistered = true; // Establecer que el usuario está registrado
    display.clearDisplay();
    display.setCursor(0, 0);
    display.println("Registrado!");
    display.println("ESP32: " + espName);  
    display.println("Pieza: " + pieceNumber);  
    display.println("Trabajador: " + workerNumber);  
    
    relayOn();


    if (WiFi.status() == WL_CONNECTED) {
      display.println("Conectado!");
    }
    display.display();
    delay(2000);
  } else {
    display.clearDisplay();
    display.setCursor(0, 0);
    display.println("Error en los datos reiniciando sistema");
    display.display();
    delay(2000);
    ESP.restart();  // Reiniciar el ESP32
  }
}

int sendData(String pieceNumber, String workerNumber) {
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    http.begin("https");
    http.addHeader("Content-Type", "application/json");

    String jsonData = "{\"pieceNumber\":\"" + pieceNumber + "\",\"workerNumber\":\"" + workerNumber + "\",\"serienumber\":" + (serienumber) + "}";

    Serial.println("Enviando JSON: " + jsonData); // Imprimir el JSON

    // Agregar un pequeño retraso
    delay(1000);

    int httpResponseCode = http.POST(jsonData);
    String response = http.getString(); // Obtener respuesta
    Serial.println("Código de respuesta: " + String(httpResponseCode));
    Serial.println("Respuesta del servidor: " + response);


    // Verificar si la respuesta es -1 y reiniciar el sistema
    if (httpResponseCode == 200 && response == "-1") {
      Serial.println("Código de respuesta -1 recibido, reiniciando el sistema...");
      resetSystem(); // Reiniciar el sistema si la respuesta es -1
      ESP.restart();  // Reiniciar el ESP32
    }

    http.end();
    return httpResponseCode; // Retornar el código de respuesta
  } else {
    display.clearDisplay();
    display.setCursor(0, 0);
    display.println("Sin conexión");
    display.display();
    return 500; // Código de error para indicar falta de conexión
  }
}

String getInput() {
  String input = "";
  char key;
  while (true) {
    key = keypad.getKey();
    if (key) {
      if (key == '#') {
        break;
      } else {
        input += key;
        display.setCursor(0, 10);
        display.println(input);
        display.display();
      }
    }
  }
  return input;
}

void sendEncoderData() {
  // Aquí puedes construir el JSON para enviar la distancia
  String jsonData = "{\"pieceNumber\":\"" + pieceNumber + "\",\"workerNumber\":\"" + workerNumber + "\",\"serienumber\":" + String(serienumber) + ",\"distance\":" + String(distance) + "}";

  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    http.begin("https"); // Cambia la URL según tu API
    http.addHeader("Content-Type", "application/json");

    int httpResponseCode = http.POST(jsonData);
    String response = http.getString();

    Serial.println("Código de respuesta: " + String(httpResponseCode));
    Serial.println("Respuesta del servidor: " + response); 


    http.end();
  } else {
    Serial.println("Error: Sin conexión a WiFi");
    display.clearDisplay();
    display.setCursor(0, 0);
    display.println("Error: Sin conexión");
    display.display();
    delay(2000);
  }
}

void resetEncoder() {
  pulseCount = 0; 
  distance = 0.0; 
  lastCLK = LOW;
}

void resetSystem() {
  display.clearDisplay();
  display.setCursor(0, 0);
  display.println("Reiniciando...");
  display.display();
  delay(1000);
  
  pulseCount = 0; 
  distance = 0.0; 
  buttonPressed = false; 
  lastCLK = LOW; 
  userRegistered = false; // Reiniciar el estado de registro
  
  display.clearDisplay();
  display.setCursor(0, 0);
  display.println("");
  display.display();
  delay(2000); 
  display.clearDisplay();
}

Please post schematics and code here. Links are not the way forum requests.

Your wiring and power supply are not good. Correct them.

sorry for the question but how can i upload those things here.
Trough a photo? of the schematics?

i also checked that thx

After creating the schematic, click the "upload file" icon in your message box.

1 Like

Pen, paper, foto and upload, yes.

I already post thx

You need to show pin numbers of the pins being used on every device.

Fritzing type pictures are not appreciated as too much is missing, circuit pin numbers unreadable, missing power supplies etc.

It's probably tanking more than the OLED.

Lots of 5V stuff wired to 3V I/O.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.