Arduino Nano ESP32 - Semáforo

Neste tutorial, vamos explorar como usar o Arduino Nano ESP32 para controlar um módulo de semáforo. Em detalhes, vamos aprender:

Hardware Necessário

1×Arduino Nano ESP32
1×Cabo USB Tipo-A para Tipo-C (para PC com USB-A)
1×Cabo USB Tipo-C para Tipo-C (para PC com USB-C)
1×Módulo de Semáforo
1×Fios Jumper
1×(Recomendado) Placa de Expansão com Bornes de Parafuso para Arduino Nano
1×(Recomendado) Placa de Expansão Breakout para Arduino Nano
1×(Recomendado) Divisor de Alimentação para Arduino Nano ESP32

Or you can buy the following kits:

1×DIYables Sensor Kit (18 sensors/displays)
Divulgação: Alguns dos links desta seção são links de afiliado da Amazon. Podemos receber uma comissão pelas compras feitas por meio desses links, sem custo adicional para você. Agradecemos o seu apoio.

Sobre o Módulo de Semáforo

Pinagem

Um módulo de semáforo possui 4 pinos:

  • Pino GND: O pino de terra, conecte este pino ao GND do Arduino Nano ESP32.
  • Pino R: O pino para controlar a luz vermelha, conecte este pino a uma saída digital do Arduino Nano ESP32.
  • Pino Y: O pino para controlar a luz amarela, conecte este pino a uma saída digital do Arduino Nano ESP32.
  • Pino G: O pino para controlar a luz verde, conecte este pino a uma saída digital do Arduino Nano ESP32.
Traffic Light Pinout

Como Funciona

Diagrama de Ligação

The wiring diagram between Arduino Nano ESP32 and traffic light

This image is created using Fritzing. Click to enlarge image

Como Programar o Módulo de Semáforo

  • Configure os pinos do ESP32 no modo de saída digital usando a função pinMode()
pinMode(PIN_RED, OUTPUT); pinMode(PIN_YELLOW, OUTPUT); pinMode(PIN_GREEN, OUTPUT);
  • Programe para ligar a luz vermelha usando a função digitalWrite():
digitalWrite(PIN_RED, HIGH); // turn on RED digitalWrite(PIN_YELLOW, LOW); // digitalWrite(PIN_GREEN, LOW); delay(RED_TIME); // keep red led on during a period of time

Código Arduino Nano ESP32

/* * Este código de Arduino Nano ESP32 foi desenvolvido por pt.newbiely.com * Este código de Arduino Nano ESP32 é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/arduino-nano-esp32/arduino-nano-esp32-traffic-light */ #define PIN_RED D3 // The Arduino Nano ESP32 pin connected to R pin of traffic light module #define PIN_YELLOW D4 // The Arduino Nano ESP32 pin connected to Y pin of traffic light module #define PIN_GREEN D5 // The Arduino Nano ESP32 pin connected to G pin of traffic light module #define RED_TIME 4000 // RED time in millisecond #define YELLOW_TIME 4000 // YELLOW time in millisecond #define GREEN_TIME 4000 // GREEN time in millisecond void setup() { pinMode(PIN_RED, OUTPUT); pinMode(PIN_YELLOW, OUTPUT); pinMode(PIN_GREEN, OUTPUT); } // The loop function repeats indefinitely void loop() { // red light on digitalWrite(PIN_RED, HIGH); // turn on digitalWrite(PIN_YELLOW, LOW); // turn off digitalWrite(PIN_GREEN, LOW); // turn off delay(RED_TIME); // keep red light on during a period of time // yellow light on digitalWrite(PIN_RED, LOW); // turn off digitalWrite(PIN_YELLOW, HIGH); // turn on digitalWrite(PIN_GREEN, LOW); // turn off delay(YELLOW_TIME); // keep yellow light on during a period of time // green light on digitalWrite(PIN_RED, LOW); // turn off digitalWrite(PIN_YELLOW, LOW); // turn off digitalWrite(PIN_GREEN, HIGH); // turn on delay(GREEN_TIME); // keep green light on during a period of time }

Passos Rápidos

Para começar com o Arduino Nano ESP32, siga estes passos:

  • Se você é novo no Arduino Nano ESP32, consulte o tutorial sobre como configurar o ambiente do Arduino Nano ESP32 no Arduino IDE.
  • Ligue os componentes de acordo com o diagrama fornecido.
  • Conecte a placa Arduino Nano ESP32 ao seu computador usando um cabo USB.
  • Abra o Arduino IDE no seu computador.
  • Selecione a placa Arduino Nano ESP32 e a porta COM correspondente.
  • Copie o código acima e abra no Arduino IDE
  • Clique no botão Upload do Arduino IDE para fazer o upload do código para o Arduino Nano ESP32
  • Confira o módulo de semáforo

É importante observar que o funcionamento exato de um semáforo pode variar dependendo do projeto e da tecnologia usados em diferentes regiões e cruzamentos. Os princípios descritos acima oferecem uma compreensão geral de como os semáforos operam para gerenciar o trânsito e aumentar a segurança nas vias.

O código acima demonstra o controle individual das luzes. Agora, vamos melhorar o código para uma melhor otimização.

Otimização do Código Arduino Nano ESP32

  • Vamos melhorar o código implementando uma função para o controle das luzes.
/* * Este código de Arduino Nano ESP32 foi desenvolvido por pt.newbiely.com * Este código de Arduino Nano ESP32 é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/arduino-nano-esp32/arduino-nano-esp32-traffic-light */ #define PIN_RED D3 // The Arduino Nano ESP32 pin connected to R pin of traffic light module #define PIN_YELLOW D4 // The Arduino Nano ESP32 pin connected to Y pin of traffic light module #define PIN_GREEN D5 // The Arduino Nano ESP32 pin connected to G pin of traffic light module #define RED_TIME 2000 // RED time in millisecond #define YELLOW_TIME 1000 // YELLOW time in millisecond #define GREEN_TIME 2000 // GREEN time in millisecond #define RED 0 // Index in array #define YELLOW 1 // Index in array #define GREEN 2 // Index in array const int pins[] = { PIN_RED, PIN_YELLOW, PIN_GREEN }; const int times[] = { RED_TIME, YELLOW_TIME, GREEN_TIME }; void setup() { pinMode(PIN_RED, OUTPUT); pinMode(PIN_YELLOW, OUTPUT); pinMode(PIN_GREEN, OUTPUT); } // The loop function repeats indefinitely void loop() { // red light on trafic_light_on(RED); delay(times[RED]); // keep red light on during a period of time // yellow light on trafic_light_on(YELLOW); delay(times[YELLOW]); // keep yellow light on during a period of time // green light on trafic_light_on(GREEN); delay(times[GREEN]); // keep green light on during a period of time } void trafic_light_on(int light) { for (int i = RED; i <= GREEN; i++) { if (i == light) digitalWrite(pins[i], HIGH); // turn on else digitalWrite(pins[i], LOW); // turn off } }
  • Vamos melhorar o código usando um laço for.
/* * Este código de Arduino Nano ESP32 foi desenvolvido por pt.newbiely.com * Este código de Arduino Nano ESP32 é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/arduino-nano-esp32/arduino-nano-esp32-traffic-light */ #define PIN_RED D3 // The Arduino Nano ESP32 pin connected to R pin of traffic light module #define PIN_YELLOW D4 // The Arduino Nano ESP32 pin connected to Y pin of traffic light module #define PIN_GREEN D5 // The Arduino Nano ESP32 pin connected to G pin of traffic light module #define RED_TIME 2000 // RED time in millisecond #define YELLOW_TIME 1000 // YELLOW time in millisecond #define GREEN_TIME 2000 // GREEN time in millisecond #define RED 0 // Index in array #define YELLOW 1 // Index in array #define GREEN 2 // Index in array const int pins[] = {PIN_RED, PIN_YELLOW, PIN_GREEN}; const int times[] = {RED_TIME, YELLOW_TIME, GREEN_TIME}; void setup() { pinMode(PIN_RED, OUTPUT); pinMode(PIN_YELLOW, OUTPUT); pinMode(PIN_GREEN, OUTPUT); } // The loop function repeats indefinitely void loop() { for (int light = RED; light <= GREEN; light ++) { trafic_light_on(light); delay(times[light]); // keep light on during a period of time } } void trafic_light_on(int light) { for (int i = RED; i <= GREEN; i ++) { if (i == light) digitalWrite(pins[i], HIGH); // turn on else digitalWrite(pins[i], LOW); // turn off } }
  • Vamos melhorar o código usando a função millis() em vez de delay().
/* * Este código de Arduino Nano ESP32 foi desenvolvido por pt.newbiely.com * Este código de Arduino Nano ESP32 é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/arduino-nano-esp32/arduino-nano-esp32-traffic-light */ #define PIN_RED D3 // The Arduino Nano ESP32 pin connected to R pin of traffic light module #define PIN_YELLOW D4 // The Arduino Nano ESP32 pin connected to Y pin of traffic light module #define PIN_GREEN D5 // The Arduino Nano ESP32 pin connected to G pin of traffic light module #define RED_TIME 2000 // RED time in millisecond #define YELLOW_TIME 1000 // YELLOW time in millisecond #define GREEN_TIME 2000 // GREEN time in millisecond #define RED 0 // Index in array #define YELLOW 1 // Index in array #define GREEN 2 // Index in array const int pins[] = { PIN_RED, PIN_YELLOW, PIN_GREEN }; const int times[] = { RED_TIME, YELLOW_TIME, GREEN_TIME }; unsigned long last_time = 0; int light = RED; // start with RED light void setup() { pinMode(PIN_RED, OUTPUT); pinMode(PIN_YELLOW, OUTPUT); pinMode(PIN_GREEN, OUTPUT); trafic_light_on(light); last_time = millis(); } // The loop function repeats indefinitely void loop() { if ((millis() - last_time) > times[light]) { light++; if (light >= 3) light = RED; // new circle trafic_light_on(light); last_time = millis(); } // TO DO: your other code } void trafic_light_on(int light) { for (int i = RED; i <= GREEN; i++) { if (i == light) digitalWrite(pins[i], HIGH); // turn on else digitalWrite(pins[i], LOW); // turn off } }

Vídeo

Referências de Funções

※ NOSSAS MENSAGENS

  • Fique à vontade para compartilhar o link deste tutorial. Porém, por favor, não use nosso conteúdo em outros sites. Investimos muito esforço e tempo para criar este conteúdo, por favor respeite nosso trabalho!