📚 NÍVEL 1 - BÁSICO (Semanas 1-4)

Progresso: [ ] Semana 1 [ ] Semana 2 [ ] Semana 3 [ ] Semana 4 [ ] Projeto Final

📑 Índice

Semana 1: GPIO Digital

Semana 2: PWM e Controle Analógico

Semana 3: ADC e Sensores Analógicos

Semana 4: Serial e Múltiplos Dispositivos

🎯 Projeto Final: Semáforo Inteligente

⚠️ Problemas Comuns e Soluções

🔗 Próximos Passos


Semana 1: GPIO Digital

📊 Metadados:

📖 Fundamentos - GPIO (General Purpose Input/Output)

O que é GPIO?

Modos de Operação:

Pull-up vs Pull-down:

Debouncing:

Funções Principais:

1
2
3
4
5
pinMode(pin, mode)        // Configura pino (OUTPUT, INPUT, INPUT_PULLUP)
digitalWrite(pin, value)  // Escreve HIGH ou LOW
digitalRead(pin)          // Lê estado do pino (HIGH ou LOW)
delay(ms)                 // Pausa por millisegundos (bloqueante)
millis()                  // Retorna tempo desde boot em ms

Objetivo: Piscar LED interno usando delay()

Componentes Necessários:

Conceitos:

1
2
3
4
5
6
7
8
9
10
11
12
// Blink básico - LED interno pino 13

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);  // LED_BUILTIN = pino 13
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);  // Liga LED
  delay(1000);                      // Aguarda 1 segundo
  digitalWrite(LED_BUILTIN, LOW);   // Desliga LED
  delay(1000);                      // Aguarda 1 segundo
}

Upload:

Desafios:

  1. 🟢 Fácil: Fazer piscar mais rápido (200ms)
  2. 🟡 Médio: Criar padrão S.O.S em morse (••• — •••)
  3. 🔴 Difícil: Usar 3 LEDs externos criando efeito “corrida” (knight rider)

Exercício 2: Botão e LED

Objetivo: Controlar LED com botão físico

Componentes Necessários:

Conceitos:

Circuito:

1
2
Botão: Pino 2 → Botão → GND (usando INPUT_PULLUP)
LED: Pino 13 → Resistor 220Ω → LED → GND
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const int LED_PIN = 13;
const int BUTTON_PIN = 2;

void setup() {
  pinMode(LED_PIN, OUTPUT);
  pinMode(BUTTON_PIN, INPUT_PULLUP);  // Pull-up interno
}

void loop() {
  int buttonState = digitalRead(BUTTON_PIN);
  
  if (buttonState == LOW) {  // LOW = pressionado (pull-up invertido)
    digitalWrite(LED_PIN, HIGH);  // Liga LED
  } else {
    digitalWrite(LED_PIN, LOW);   // Desliga LED
  }
}

Desafios:

  1. 🟢 Fácil: Inverter lógica (botão apaga LED)
  2. 🟡 Médio: Toggle LED (pressiona uma vez liga, pressiona de novo desliga)
  3. 🔴 Difícil: Contar número de pressionamentos e exibir no Serial Monitor

Exercício 3: Debounce de Botão

Objetivo: Eliminar bouncing com técnica millis()

Componentes Necessários:

Conceitos:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
const int LED_PIN = 13;
const int BUTTON_PIN = 2;
const long DEBOUNCE_DELAY = 50;  // 50ms

int ledState = LOW;
int buttonState;
int lastButtonState = HIGH;  // Pull-up: HIGH quando solto
unsigned long lastDebounceTime = 0;

void setup() {
  pinMode(LED_PIN, OUTPUT);
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  digitalWrite(LED_PIN, ledState);
}

void loop() {
  int reading = digitalRead(BUTTON_PIN);
  
  // Se o estado mudou (ruído ou pressionamento real)
  if (reading != lastButtonState) {
    lastDebounceTime = millis();  // Reseta timer
  }
  
  // Se passou tempo suficiente desde última mudança
  if ((millis() - lastDebounceTime) > DEBOUNCE_DELAY) {
    // Se o estado mudou de fato
    if (reading != buttonState) {
      buttonState = reading;
      
      // Toggle LED apenas quando botão é pressionado (LOW)
      if (buttonState == LOW) {
        ledState = !ledState;
        digitalWrite(LED_PIN, ledState);
      }
    }
  }
  
  lastButtonState = reading;
}

Desafios:

  1. 🟢 Fácil: Ajustar tempo de debounce para 100ms
  2. 🟡 Médio: Detectar pressionamento longo (> 2 segundos) vs curto
  3. 🔴 Difícil: Implementar double-click (dois cliques rápidos)

Semana 2: PWM e Controle Analógico

📊 Metadados:

📖 Fundamentos - PWM (Pulse Width Modulation)

O que é PWM?

Pinos PWM no Arduino UNO:

Aplicações:

Função Principal:

1
analogWrite(pin, value)  // value: 0-255 (0% a 100% duty cycle)

Relação Valor → Duty Cycle:


Exercício 4: Fade LED com PWM

Objetivo: Criar efeito de fade (respiração) em LED

Componentes Necessários:

Conceitos:

Circuito:

1
Pino 9 → Resistor 220Ω → LED → GND
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const int LED_PIN = 9;  // Deve ser pino PWM (~)
int brightness = 0;
int fadeAmount = 5;

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

void loop() {
  analogWrite(LED_PIN, brightness);  // 0-255
  
  brightness += fadeAmount;
  
  // Inverte direção nos extremos
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount;
  }
  
  delay(30);  // Velocidade da animação
}

Desafios:

  1. 🟢 Fácil: Fazer fade mais lento (delay maior)
  2. 🟡 Médio: Controlar 3 LEDs RGB criando efeito arco-íris
  3. 🔴 Difícil: Usar potenciômetro para controlar velocidade do fade

Exercício 5: Controle de Servo Motor

Objetivo: Controlar posição de servo com biblioteca Servo

Componentes Necessários:

Conceitos:

Circuito:

1
2
3
4
Servo:
  Fio Marrom/Preto: GND
  Fio Vermelho: 5V (usar fonte externa se possível)
  Fio Laranja/Amarelo: Pino 9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <Servo.h>

Servo myServo;
const int SERVO_PIN = 9;

void setup() {
  myServo.attach(SERVO_PIN);  // Conecta servo ao pino
  myServo.write(90);           // Posição inicial (centro)
}

void loop() {
  // Varre de 0° a 180°
  for (int pos = 0; pos <= 180; pos++) {
    myServo.write(pos);
    delay(15);
  }
  
  // Varre de volta (180° a 0°)
  for (int pos = 180; pos >= 0; pos--) {
    myServo.write(pos);
    delay(15);
  }
}

Desafios:

  1. 🟢 Fácil: Fazer servo ir para posições fixas (0°, 90°, 180°) com pausas
  2. 🟡 Médio: Controlar posição do servo com potenciômetro (0-1023 → 0-180)
  3. 🔴 Difícil: Criar “braço robótico” com 2 servos controlados por Serial

Semana 3: ADC e Sensores Analógicos

📊 Metadados:

📖 Fundamentos - ADC (Analog to Digital Converter)

O que é ADC?

Pinos Analógicos:

Resolução:

Conversão Valor → Voltagem:

1
2
int rawValue = analogRead(A0);
float voltage = (rawValue / 1023.0) * 5.0;

Função Principal:

1
analogRead(pin)  // Retorna valor 0-1023

Sensores Analógicos Comuns:


Exercício 6: Ler Potenciômetro

Objetivo: Ler potenciômetro e exibir valor no Serial Monitor

Componentes Necessários:

Conceitos:

Circuito:

1
2
3
4
Potenciômetro:
  Pino 1: 5V
  Pino 2 (central): A0
  Pino 3: GND
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const int POT_PIN = A0;

void setup() {
  Serial.begin(9600);  // Inicia comunicação serial
}

void loop() {
  int rawValue = analogRead(POT_PIN);  // 0-1023
  float voltage = (rawValue / 1023.0) * 5.0;
  
  Serial.print("Raw: ");
  Serial.print(rawValue);
  Serial.print(" | Voltage: ");
  Serial.print(voltage);
  Serial.println("V");
  
  delay(200);  // Atualiza 5x por segundo
}

Usar Serial Monitor:

Desafios:

  1. 🟢 Fácil: Mapear valor 0-1023 para 0-100 (percentual)
  2. 🟡 Médio: Controlar brilho de LED com potenciômetro (usar map)
  3. 🔴 Difícil: Criar bargraph com 5 LEDs mostrando nível do potenciômetro

Exercício 7: Sensor de Temperatura LM35

Objetivo: Ler temperatura com sensor LM35

Componentes Necessários:

Conceitos:

Circuito:

1
2
3
4
LM35:
  Pino 1 (esquerda): 5V
  Pino 2 (centro): A0
  Pino 3 (direita): GND

Especificação LM35:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const int LM35_PIN = A0;

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

void loop() {
  int rawValue = analogRead(LM35_PIN);
  float voltage = (rawValue / 1023.0) * 5.0;
  float tempC = voltage * 100.0;  // LM35: 10mV/°C
  float tempF = (tempC * 9.0 / 5.0) + 32.0;
  
  Serial.print("Temperatura: ");
  Serial.print(tempC);
  Serial.print("°C (");
  Serial.print(tempF);
  Serial.println("°F)");
  
  delay(1000);
}

Desafios:

  1. 🟢 Fácil: Adicionar alerta se temperatura > 30°C (LED vermelho)
  2. 🟡 Médio: Implementar média móvel de 10 leituras para suavizar ruído
  3. 🔴 Difícil: Criar datalogger que grava temperatura a cada minuto no EEPROM

Semana 4: Serial e Múltiplos Dispositivos

📊 Metadados:

📖 Fundamentos - Display 7 Segmentos

O que é Display 7 Segmentos?

Segmentos:

1
2
3
4
5
   A
 F   B
   G
 E   C
   D   (DP)

Cátodo Comum vs Ânodo Comum:

Controle:


Exercício 8: Display 7 Segmentos

Objetivo: Exibir números 0-9 em display 7 segmentos

Componentes Necessários:

Conceitos:

Circuito:

1
2
3
Display cátodo comum:
  COM → GND
  Segmentos A-G → Pinos 2-8 (cada um com resistor 220Ω)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Pinos dos segmentos (A-G)
const int segmentPins[] = {2, 3, 4, 5, 6, 7, 8};  // A, B, C, D, E, F, G

// Padrões para dígitos 0-9 (cátodo comum: HIGH acende)
const byte digitPatterns[10][7] = {
  {1,1,1,1,1,1,0},  // 0
  {0,1,1,0,0,0,0},  // 1
  {1,1,0,1,1,0,1},  // 2
  {1,1,1,1,0,0,1},  // 3
  {0,1,1,0,0,1,1},  // 4
  {1,0,1,1,0,1,1},  // 5
  {1,0,1,1,1,1,1},  // 6
  {1,1,1,0,0,0,0},  // 7
  {1,1,1,1,1,1,1},  // 8
  {1,1,1,1,0,1,1}   // 9
};

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

void displayDigit(int digit) {
  if (digit < 0 || digit > 9) return;
  
  for (int i = 0; i < 7; i++) {
    digitalWrite(segmentPins[i], digitPatterns[digit][i]);
  }
}

void loop() {
  for (int i = 0; i <= 9; i++) {
    displayDigit(i);
    delay(1000);
  }
}

Desafios:

  1. 🟢 Fácil: Adicionar padrões para letras A, b, C, d, E, F
  2. 🟡 Médio: Usar 4 displays multiplexados para mostrar relógio (minutos:segundos)
  3. 🔴 Difícil: Criar contador regressivo com botão de start/pause

🎯 Projeto Final: Semáforo Inteligente

Objetivo: Criar semáforo com botão de pedestre e sensor de luminosidade

Tempo estimado: 6-8 horas

Componentes Necessários:

Funcionalidades:

  1. Ciclo automático: Verde (5s) → Amarelo (2s) → Vermelho (5s)
  2. Botão pedestre: Ao pressionar, após ciclo atual vai para vermelho
  3. Modo noturno: Se escuro (LDR), pisca amarelo
  4. Serial Monitor: Mostra estado atual

Conceitos Aplicados:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
const int RED_PIN = 8;
const int YELLOW_PIN = 9;
const int GREEN_PIN = 10;
const int PEDESTRIAN_LED = 11;
const int BUTTON_PIN = 2;
const int LDR_PIN = A0;

enum State { GREEN, YELLOW, RED, NIGHT_MODE };
State currentState = GREEN;

unsigned long lastStateChange = 0;
bool pedestrianRequest = false;
int lightThreshold = 300;  // Ajustar conforme LDR

void setup() {
  pinMode(RED_PIN, OUTPUT);
  pinMode(YELLOW_PIN, OUTPUT);
  pinMode(GREEN_PIN, OUTPUT);
  pinMode(PEDESTRIAN_LED, OUTPUT);
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  Serial.begin(9600);
}

void setTrafficLight(bool red, bool yellow, bool green) {
  digitalWrite(RED_PIN, red);
  digitalWrite(YELLOW_PIN, yellow);
  digitalWrite(GREEN_PIN, green);
}

void loop() {
  int lightLevel = analogRead(LDR_PIN);
  
  // Verificar botão pedestre (com debounce simples)
  if (digitalRead(BUTTON_PIN) == LOW) {
    pedestrianRequest = true;
    delay(200);  // Debounce simples
  }
  
  // Modo noturno se escuro
  if (lightLevel < lightThreshold) {
    currentState = NIGHT_MODE;
    setTrafficLight(false, false, false);
    digitalWrite(YELLOW_PIN, millis() % 1000 < 500);  // Pisca amarelo
    Serial.println("MODO NOTURNO");
    return;
  }
  
  unsigned long now = millis();
  
  switch (currentState) {
    case GREEN:
      setTrafficLight(false, false, true);
      digitalWrite(PEDESTRIAN_LED, LOW);
      Serial.println("VERDE - Veículos podem passar");
      
      if (now - lastStateChange > 5000) {  // 5 segundos
        currentState = YELLOW;
        lastStateChange = now;
      }
      break;
      
    case YELLOW:
      setTrafficLight(false, true, false);
      Serial.println("AMARELO - Atenção");
      
      if (now - lastStateChange > 2000) {  // 2 segundos
        currentState = RED;
        lastStateChange = now;
      }
      break;
      
    case RED:
      setTrafficLight(true, false, false);
      digitalWrite(PEDESTRIAN_LED, HIGH);
      Serial.println("VERMELHO - Pedestres podem atravessar");
      
      if (now - lastStateChange > 5000) {  // 5 segundos
        currentState = GREEN;
        lastStateChange = now;
        pedestrianRequest = false;
      }
      break;
  }
  
  delay(100);
}

Melhorias Opcionais:


⚠️ Problemas Comuns e Soluções

1. LED não acende

2. Botão não funciona

3. Leituras ADC instáveis

4. Serial Monitor não mostra nada

5. Código não compila

6. Upload falha

7. PWM não funciona


🔗 Próximos Passos

Parabéns! Você completou o Nível 1 - Básico do Arduino! 🎉

O que você aprendeu:

Próximo nível: 📘 Nível 2 - Intermediário

Outros recursos:

Voltar: ../README.md