#include <Arduino.h>
// Definir os pinos do ESP32 conectados aos 74HC595
#define DATA_PIN 27 // Pin DS
#define CLOCK_PIN 25 // Pin SHCP
#define LATCH_PIN 26 // Pin STCP
// Mapeamento dos dígitos para os segmentos dos displays de 7 segmentos (assume-se segmentos de ânodo comum)
const byte digitToSegment[10] = {
0xC0, // 0
0xF9, // 1
0xA4, // 2
0xB0, // 3
0x99, // 4
0x92, // 5
0x82, // 6
0xF8, // 7
0x80, // 8
0x90 // 9
};
void setup() {
pinMode(DATA_PIN, OUTPUT);
pinMode(CLOCK_PIN, OUTPUT);
pinMode(LATCH_PIN, OUTPUT);
Serial.begin(115200);
}
void loop() {
int speed = random(100); // Gerar um número aleatório de 0 a 99
displaySpeed(speed);
delay(1000); // Atualiza a velocidade a cada segundo
}
void displaySpeed(int speed) {
byte highDigit = speed / 10; // Dígito das dezenas
byte lowDigit = speed % 10; // Dígito das unidades
// Preparar o estado dos segmentos para envio (Invertendo a ordem de envio)
byte highSegments = digitToSegment[highDigit];
byte lowSegments = digitToSegment[lowDigit];
// Enviar os dados para os 74HC595 (Agora enviando primeiro o dígito das unidades)
digitalWrite(LATCH_PIN, LOW);
shiftOut(DATA_PIN, CLOCK_PIN, MSBFIRST, lowSegments);
shiftOut(DATA_PIN, CLOCK_PIN, MSBFIRST, highSegments);
digitalWrite(LATCH_PIN, HIGH);
// Debugging via Serial Monitor
Serial.print("Velocidade: ");
Serial.println(speed);
}
void shiftOut(byte myDataPin, byte myClockPin, byte myOrder, byte myDataOut) {
int i=0;
int pinState;
pinMode(myClockPin, OUTPUT);
pinMode(myDataPin, OUTPUT);
//define a ordem dos dados
if (myOrder == LSBFIRST) {
for (i=0; i<8; i++) {
if (myDataOut & (1<<i)) {
pinState= HIGH;
} else {
pinState= LOW;
}
digitalWrite(myDataPin, pinState);
digitalWrite(myClockPin, HIGH);
digitalWrite(myClockPin, LOW);
}
} else {
for (i=7; i>=0; i--) {
if (myDataOut & (1<<i)) {
pinState= HIGH;
} else {
pinState= LOW;
}
digitalWrite(myDataPin, pinState);
digitalWrite(myClockPin, HIGH);
digitalWrite(myClockPin, LOW);
}
}
}