Skip to content

Instantly share code, notes, and snippets.

@nunesfb
Last active August 18, 2025 18:50
Show Gist options
  • Select an option

  • Save nunesfb/e5c1cc8d12bce390263a6fdd61685453 to your computer and use it in GitHub Desktop.

Select an option

Save nunesfb/e5c1cc8d12bce390263a6fdd61685453 to your computer and use it in GitHub Desktop.

Exemplos de Sensores e Módulos com Arduino

Semáforo com 3 LEDs

Exemplo da Internet

Montagem

  • LED Vermelho: Pino 13
  • LED Amarelo: Pino 12
  • LED Verde: Pino 11
  • Não esqueça do resistor para cada LED (~220Ω). Os pinos podem ser adaptados conforme necessário.

Código Arduino

// Definição dos pinos dos LEDs
const int ledVermelho = 13;
const int ledAmarelo  = 12;
const int ledVerde    = 11;

void setup() {
  pinMode(ledVermelho, OUTPUT);
  pinMode(ledAmarelo, OUTPUT);
  pinMode(ledVerde, OUTPUT);
}

void loop() {
  // Verde ligado
  digitalWrite(ledVerde, HIGH);
  digitalWrite(ledAmarelo, LOW);
  digitalWrite(ledVermelho, LOW);
  delay(5000); // 5 segundos

  // Amarelo ligado
  digitalWrite(ledVerde, LOW);
  digitalWrite(ledAmarelo, HIGH);
  digitalWrite(ledVermelho, LOW);
  delay(2000); // 2 segundos

  // Vermelho ligado
  digitalWrite(ledVerde, LOW);
  digitalWrite(ledAmarelo, LOW);
  digitalWrite(ledVermelho, HIGH);
  delay(5000); // 5 segundos
}

Funcionamento

  • Verde acende por 5 segundos
  • Amarelo acende por 2 segundos
  • Vermelho acende por 5 segundos
  • Repete o ciclo

Arduino Uno + Sensor Ultrassônico HC-SR04

Exemplo da Internet

Ligações (Wiring)

  • VCC do HC-SR04 → 5V do Arduino
  • GND do HC-SR04 → GND do Arduino
  • TRIG do HC-SR04 → Pino 9 do Arduino
  • ECHO do HC-SR04 → Pino 10 do Arduino

Código Arduino

const int trigPin = 9;
const int echoPin = 10;
long duration;
float distanceCm;

void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  // Limpa o pino TRIG
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  // Envia pulso de 10us para TRIG
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Mede o tempo de resposta do ECHO
  duration = pulseIn(echoPin, HIGH);

  // Calcula a distância em centímetros
  distanceCm = duration * 0.034 / 2;

  // Mostra no Serial Monitor
  Serial.print("Distancia: ");
  Serial.print(distanceCm);
  Serial.println(" cm");

  delay(500); // Aguarda meio segundo
}

Funcionamento

  • O sensor envia um pulso ultrassônico pelo TRIG.
  • O ECHO retorna o tempo que o pulso levou para voltar.
  • O Arduino calcula a distância e mostra no Serial Monitor (Ctrl + Shift + M no Arduino IDE).

Arduino Uno + Botão

Exemplo de Internet

Ligações (Wiring)

  • Um lado do botãoPino 7 do Arduino
  • Mesmo lado do botãoResistor de 10kΩ para o GND
  • Outro lado do botão5V do Arduino

Resumo:
O botão vai de 5V ao pino digital (7), e do mesmo pino (7) para o GND através do resistor (pull-down).

Código Arduino

const int botaoPin = 7;  // Pino em que o botão está conectado
int estadoBotao = 0;

void setup() {
  pinMode(botaoPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  estadoBotao = digitalRead(botaoPin);

  if (estadoBotao == HIGH) {
    Serial.println("Botao pressionado!");
  } else {
    Serial.println("Botao solto.");
  }
  delay(200);
}

Funcionamento

  • Pressione o botão → Serial Monitor mostra: "Botao pressionado!"
  • Solte o botão → Mostra: "Botao solto."

Arduino Uno + Potenciômetro

Exemplo de Internet

Ligações (Wiring)

  • Pino do meio do potenciômetro → A0 do Arduino
  • Um dos pinos laterais5V do Arduino
  • Outro pino lateralGND do Arduino

Código Arduino

const int potPin = A0;   // Pino analógico conectado ao potenciômetro
int valorPot = 0;

void setup() {
  Serial.begin(9600);
}

void loop() {
  valorPot = analogRead(potPin); // Lê valor (0 a 1023)
  Serial.print("Valor do potenciometro: ");
  Serial.println(valorPot);
  delay(300);
}

Funcionamento

  • Gire o potenciômetro: O valor lido vai de 0 (GND) a 1023 (5V).
  • Veja o resultado no Serial Monitor do Arduino IDE.

Arduino Uno + Buzzer

Exemplo de Internet

Ligações (Wiring)

  • Pino positivo do buzzer (geralmente maior) → Pino 8 do Arduino
  • Pino negativo do buzzerGND do Arduino

Código Arduino

Buzzer com beep simples:

const int buzzerPin = 8;

void setup() {
  pinMode(buzzerPin, OUTPUT);
}

void loop() {
  digitalWrite(buzzerPin, HIGH); // Liga o buzzer
  delay(500);                   // 0.5 segundo
  digitalWrite(buzzerPin, LOW);  // Desliga o buzzer
  delay(500);                   // 0.5 segundo
}

Buzzer com tons (usando tone()):

const int buzzerPin = 8;

void setup() {
  // Nada necessário aqui
}

void loop() {
  tone(buzzerPin, 1000); // Toca 1000Hz
  delay(300);            // Por 0.3 segundo
  noTone(buzzerPin);     // Para o som
  delay(700);            // Espera 0.7 segundo
}

Dica:

  • Use tone(pin, frequência) para emitir sons diferentes.
  • Use noTone(pin) para parar.

🌡️ Sensor DHT11/DHT22 – Temperatura e Umidade

Exemplo da Internet

Esse exemplo lê a temperatura e a umidade e mostra no Serial Monitor.

📌 Esquema de ligação

  • VCC → 5V (ou 3.3V, dependendo do módulo)
  • GND → GND do Arduino
  • DATA → Pino digital 2 (pode mudar no código)

Obs: Alguns módulos DHT têm 3 pinos (já incluem resistor pull-up), outros têm 4 pinos (nesse caso, ligar um resistor de 10kΩ entre VCC e DATA).

📌 Código Arduino

#include "DHT.h"   // Biblioteca para o sensor

#define DHTPIN 2        // Pino digital conectado ao DATA do sensor
#define DHTTYPE DHT11   // Altere para DHT22 se estiver usando o DHT22

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println("Iniciando leitura do sensor DHT...");
  dht.begin();
}

void loop() {
  float humidity = dht.readHumidity();
  float temperatureC = dht.readTemperature();
  float temperatureF = dht.readTemperature(true);

  if (isnan(humidity) || isnan(temperatureC) || isnan(temperatureF)) {
    Serial.println("Falha ao ler do sensor DHT!");
    delay(2000);
    return;
  }

  Serial.print("Umidade: ");
  Serial.print(humidity);
  Serial.print(" %	");
  Serial.print("Temperatura: ");
  Serial.print(temperatureC);
  Serial.print(" *C | ");
  Serial.print(temperatureF);
  Serial.println(" *F");

  delay(2000);
}

📌 Saída esperada

Iniciando leitura do sensor DHT...
Umidade: 58.00 %    Temperatura: 24.00 *C | 75.20 *F
Umidade: 59.00 %    Temperatura: 24.10 *C | 75.38 *F

💡 Sensor LDR (Fotocélula)

Exemplo da Internet

Esse circuito lê a intensidade da luz pelo LDR e mostra no Serial Monitor.
Também podemos acender um LED quando a luminosidade estiver baixa (simulando um poste de luz).

📌 Esquema de ligação

  • LDR + resistor 10kΩ em divisor de tensão
  • LDR → 5V
  • Outro terminal do LDR → A0 e resistor para GND
  • LED opcional:
    • Anodo (+) → D8 (com resistor 220Ω)
    • Catodo (–) → GND

📌 Código Arduino

const int ldrPin = A0;
const int ledPin = 8;
const int threshold = 500;

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  Serial.println("Leitura do sensor de luz (LDR) iniciada...");
}

void loop() {
  int ldrValue = analogRead(ldrPin);

  Serial.print("Valor LDR: ");
  Serial.println(ldrValue);

  if (ldrValue < threshold) {
    digitalWrite(ledPin, HIGH);
    Serial.println("Ambiente ESCURO → LED ON");
  } else {
    digitalWrite(ledPin, LOW);
    Serial.println("Ambiente CLARO → LED OFF");
  }

  delay(1000);
}

📌 Saída esperada

Leitura do sensor de luz (LDR) iniciada...
Valor LDR: 820
Ambiente CLARO → LED OFF
Valor LDR: 340
Ambiente ESCURO → LED ON

👀 Sensor PIR (HC-SR501) – Movimento

Exemplo da Internet

Detecta presença e acende um LED enquanto houver movimento.

📌 Ligações

  • VCC → 5V
  • GND → GND
  • OUT → D7

📌 Código Arduino

const int pirPin = 7;
const int ledPin = LED_BUILTIN;

const unsigned long holdTimeMs = 2000;
unsigned long lastMotionMs = 0;
bool motionState = false;

void setup() {
  Serial.begin(9600);
  pinMode(pirPin, INPUT);
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);

  Serial.println(F("PIR iniciado. Aguarde 30-60s para estabilizar..."));
}

void loop() {
  int pirValue = digitalRead(pirPin);

  if (pirValue == HIGH) {
    lastMotionMs = millis();
    if (!motionState) {
      motionState = true;
      Serial.println(F("Movimento DETECTADO!"));
    }
  }

  if (motionState && (millis() - lastMotionMs > holdTimeMs)) {
    motionState = false;
    Serial.println(F("Nenhum movimento."));
  }

  digitalWrite(ledPin, motionState ? HIGH : LOW);
  delay(50);
}

📺 Display LCD 16x2 (sem I2C)

Exemplo da Internet

📌 Ligações

  • VSS → GND
  • VDD → 5V
  • V0 → Potenciômetro (contraste)
  • RS → D12
  • RW → GND
  • E → D11
  • D4–D7 → D5, D4, D3, D2
  • A/K → 5V / GND (backlight, com resistor se necessário)

✅ Sketch 1 — Hello World

#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  lcd.begin(16, 2);
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("LCD 16x2 (4-bit)");
  lcd.setCursor(0, 1);
  lcd.print("Sem I2C - OK!");
}

void loop() {}

✅ Sketch 2 — LDR no LCD

#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int ldrPin = A0;

void setup() {
  lcd.begin(16, 2);
  lcd.clear();
  lcd.print("LDR leitura:");
}

void loop() {
  int value = analogRead(ldrPin);
  int bar = map(value, 0, 1023, 0, 16);

  lcd.setCursor(0, 0);
  lcd.print("Val: ");
  lcd.print(value);
  lcd.print("     ");

  lcd.setCursor(0, 1);
  for (int i = 0; i < 16; i++) {
    lcd.print(i < bar ? char(255) : ' ');
  }
  delay(300);
}

🔢 Display de 7 Segmentos

Exemplo da Internet

1 Dígito (Comum Cátodo)

  • a–g → D2..D8
  • dp → D9 (opcional)
  • COM → GND
const int segPins[8] = {2,3,4,5,6,7,8,9};
const byte digits[10][8] = {
  {1,1,1,1,1,1,0,0}, {0,1,1,0,0,0,0,0}, {1,1,0,1,1,0,1,0},
  {1,1,1,1,0,0,1,0}, {0,1,1,0,0,1,1,0}, {1,0,1,1,0,1,1,0},
  {1,0,1,1,1,1,1,0}, {1,1,1,0,0,0,0,0}, {1,1,1,1,1,1,1,0},
  {1,1,1,1,0,1,1,0}
};

void setup() {
  for (int i = 0; i < 8; i++) pinMode(segPins[i], OUTPUT);
}

void showDigit(int n) {
  for (int s = 0; s < 8; s++) digitalWrite(segPins[s], digits[n][s] ? HIGH : LOW);
}

void loop() {
  for (int n = 0; n <= 9; n++) {
    showDigit(n);
    delay(700);
  }
}

4 Dígitos (Comum Ânodo, Multiplexado)

const int segPins[8] = {2,3,4,5,6,7,8,9};
const int digitPins[4] = {10,11,12,13};
const byte numMap[10][7] = {
  {1,1,1,1,1,1,0}, {0,1,1,0,0,0,0}, {1,1,0,1,1,0,1}, {1,1,1,1,0,0,1},
  {0,1,1,0,0,1,1}, {1,0,1,1,0,1,1}, {1,0,1,1,1,1,1}, {1,1,1,0,0,0,0},
  {1,1,1,1,1,1,1}, {1,1,1,1,0,1,1}
};
unsigned int counter = 0;
unsigned long lastInc = 0;

void setup() {
  for (int i = 0; i < 8; i++) pinMode(segPins[i], OUTPUT);
  for (int i = 0; i < 4; i++) pinMode(digitPins[i], OUTPUT);
}

void showDigitValue(int digitIndex, int value) {
  digitalWrite(digitPins[digitIndex], HIGH);
  for (int s = 0; s < 7; s++) digitalWrite(segPins[s], numMap[value][s] ? LOW : HIGH);
  delayMicroseconds(2500);
  digitalWrite(digitPins[digitIndex], LOW);
}

void showNumber(int n) {
  int d4 = (n / 1000) % 10, d3 = (n / 100) % 10, d2 = (n / 10) % 10, d1 = n % 10;
  showDigitValue(0, d4);
  showDigitValue(1, d3);
  showDigitValue(2, d2);
  showDigitValue(3, d1);
}

void loop() {
  showNumber(counter);
  if (millis() - lastInc >= 250) { lastInc = millis(); counter = (counter + 1) % 10000; }
}

📡 Módulo IR (VS1838B/TSOP38238)

Exemplo da Internet

📌 Ligações

  • OUT → D2
  • VCC → 5V
  • GND → GND

📦 Biblioteca

Instalar IRremote (#include <IRremote.hpp>).

✅ Sketch 1 — Sniffer

#include <IRremote.hpp>
const int IR_RECEIVE_PIN = 2;

void setup() {
  Serial.begin(115200);
  IrReceiver.begin(IR_RECEIVE_PIN, ENABLE_LED_FEEDBACK);
  Serial.println(F("IR Sniffer pronto. Pressione botoes..."));
}

void loop() {
  if (IrReceiver.decode()) {
    IrReceiver.printIRResultShort(&Serial);
    Serial.print(F(" | RAW HEX: 0x"));
    Serial.println(IrReceiver.decodedIRData.decodedRawData, HEX);
    IrReceiver.resume();
  }
}

✅ Sketch 2 — Controle de LED

#include <IRremote.hpp>
const int IR_RECEIVE_PIN = 2;
const int LED_PIN = LED_BUILTIN;
const uint8_t CMD_POWER = 0x45; // substitua
bool ledOn = false;

void setup() {
  Serial.begin(115200);
  pinMode(LED_PIN, OUTPUT);
  IrReceiver.begin(IR_RECEIVE_PIN, ENABLE_LED_FEEDBACK);
}

void loop() {
  if (!IrReceiver.decode()) return;
  auto &data = IrReceiver.decodedIRData;

  if (data.protocol != UNKNOWN) {
    if (data.command == CMD_POWER) {
      ledOn = !ledOn;
      Serial.println(F("Toggle LED"));
    }
  }
  digitalWrite(LED_PIN, ledOn ? HIGH : LOW);
  IrReceiver.resume();
}

⚙️ Servo SG90

Exemplo da Internet

📌 Ligações

  • Marrom/Preto → GND
  • Vermelho → 5V
  • Laranja/Amarelo → D9

✅ Sketch 1 — Movimentação básica

#include <Servo.h>
Servo myServo;
const int servoPin = 9;

void setup() { myServo.attach(servoPin); }

void loop() {
  for (int angle = 0; angle <= 180; angle++) {
    myServo.write(angle); delay(15);
  }
  for (int angle = 180; angle >= 0; angle--) {
    myServo.write(angle); delay(15);
  }
}

✅ Sketch 2 — Controle por potenciômetro

#include <Servo.h>
Servo myServo;
const int servoPin = 9, potPin = A0;

void setup() { myServo.attach(servoPin); }

void loop() {
  int potValue = analogRead(potPin);
  int angle = map(potValue, 0, 1023, 0, 180);
  myServo.write(angle);
  delay(15);
}

🔌 Módulo Relé (1 canal)

Exemplo da Internet

📌 Ligações (lado lógico)

  • VCC → 5V
  • GND → GND
  • IN → D7

📌 Contatos de potência

  • COM → Fonte +
  • NO → Carga +
  • NC → normalmente fechado

✅ Sketch 1 — Liga/Desliga automático

const int RELAY_PIN = 7;
const bool RELAY_ACTIVE_LOW = true;

void relayWrite(bool on) {
  digitalWrite(RELAY_PIN, (RELAY_ACTIVE_LOW ? (on ? LOW : HIGH) : (on ? HIGH : LOW)));
}

void setup() {
  pinMode(RELAY_PIN, OUTPUT);
  relayWrite(false);
}

void loop() {
  relayWrite(true); delay(2000);
  relayWrite(false); delay(2000);
}

✅ Sketch 2 — Controle por botão

const int RELAY_PIN = 7;
const bool RELAY_ACTIVE_LOW = true;
const int BUTTON_PIN = 2;

bool relayState = false;
unsigned long lastDebounce = 0;
const unsigned long DEBOUNCE_MS = 40;
int lastReading = HIGH;

void relayWrite(bool on) {
  digitalWrite(RELAY_PIN, (RELAY_ACTIVE_LOW ? (on ? LOW : HIGH) : (on ? HIGH : LOW)));
}

void setup() {
  pinMode(RELAY_PIN, OUTPUT); relayWrite(false);
  pinMode(BUTTON_PIN, INPUT_PULLUP);
}

void loop() {
  int reading = digitalRead(BUTTON_PIN);
  if (reading != lastReading) lastDebounce = millis();

  if ((millis() - lastDebounce) > DEBOUNCE_MS) {
    if (reading == LOW && lastReading == HIGH) {
      relayState = !relayState;
      relayWrite(relayState);
    }
  }
  lastReading = reading;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment