Created
December 5, 2025 14:25
-
-
Save terremoth/67d1f08603d498388197561046dd8e75 to your computer and use it in GitHub Desktop.
Comportamento do urso - roboi de mamão
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <Servo.h> // Include the Servo library | |
| Servo myServo; // Create a Servo object | |
| const int SonarTrigger = 7; // define o pino 7 como Trigger | |
| const int SonarEcho = 8; // define o pino 6 como Echo | |
| const int led_olhos = 9; | |
| const int buzzer = 10; | |
| const int servo = 11; // Pino do servo | |
| float distancia = 0; // Use float para a distância (em cm) | |
| unsigned long tempo = 0; // Use unsigned long para o tempo (microssegundos) | |
| void setup() { | |
| pinMode(buzzer, OUTPUT); | |
| pinMode(led_olhos, OUTPUT); | |
| pinMode(SonarTrigger, OUTPUT); // Função de emitir o som (altofalante - Saída) | |
| pinMode(SonarEcho, INPUT); //Função de receber um som (microfone - Entrada) | |
| myServo.attach(servo); | |
| Serial.begin(9600); // Para escrever no monitor serial | |
| } | |
| void loop() { | |
| digitalWrite(SonarTrigger, LOW); // Estabiliza sensor | |
| delay(2); | |
| digitalWrite(SonarTrigger, HIGH); // Envia um pulso para ativar | |
| delay(10); | |
| digitalWrite(SonarTrigger, LOW); | |
| tempo = pulseIn(SonarEcho, HIGH); // Função que recebe um pulso e retorna o valor em tempo da duração deste pulso, em microsegundos | |
| distancia = tempo / 58.2; // Distancia = tempo * velocidade do som / 2 (Velocidade do som é 340 m/s) | |
| digitalWrite(led_olhos, LOW); | |
| myServo.write(0); | |
| Serial.print("Medir: "); | |
| Serial.println(distancia); | |
| if (distancia < 20 && distancia > 3) { | |
| digitalWrite(led_olhos, HIGH); | |
| Serial.println("mexe servo"); | |
| myServo.write(100); | |
| distancia = 0; // resolve bugs que até budha duvidaria em sua mais alta consciência | |
| for (int i = 75; i > 30; i--) { | |
| tone(buzzer, i); | |
| delay(25); | |
| } | |
| noTone(buzzer); | |
| distancia = 0; // resolve bugs que até budha duvidaria em sua mais alta consciência | |
| } | |
| distancia = 0; // resolve bugs que até budha duvidaria em sua mais alta consciência | |
| delay(100); // Mede a cada 1 segundo | |
| distancia = 0; // resolve bugs que até budha duvidaria em sua mais alta consciência | |
| } |
Author
Author
FINAL
#include <Servo.h>
Servo myServo;
// ---------- PINOS ----------
const int SonarTrigger = 7;
const int SonarEcho = 8;
const int led_olhos = 9;
const int buzzer = 10;
const int servoPin = 11;
// Ajuste os pinos conforme sua montagem
const int motorA_dir = 4;
const int motorA_pwm = 5;
const int motorB_pwm = 3;
const int motorB_dir = 2;
// ---------- CONFIGURAÇÕES ----------
// Velocidade de cruzeiro (andar reto)
int speedAndar = 100;
// Velocidade de GIRO (Geralmente precisa ser maior para vencer o atrito do chão)
int speedGiro = 180;
const int DIST_STOP = 45; // Distância segura para parar (45cm)
// Temporizadores
const int TEMPO_GIRO_MIN = 400; // Mínimo tempo girando (ms)
const int TEMPO_GIRO_MAX = 800; // Máximo tempo girando (ms)
// ---------- FUNÇÕES DE MOVIMENTO ----------
void pararMotores() {
// Trava imediata: coloca tudo em LOW e PWM 0
digitalWrite(motorA_dir, LOW);
digitalWrite(motorB_dir, LOW);
analogWrite(motorA_pwm, 0);
analogWrite(motorB_pwm, 0);
}
void andarFrente() {
digitalWrite(motorA_dir, HIGH);
digitalWrite(motorB_dir, LOW);
analogWrite(motorA_pwm, speedAndar);
analogWrite(motorB_pwm, speedAndar);
}
// Gira no próprio eixo (rodas opostas)
void girarDireita(int tempo) {
digitalWrite(motorA_dir, LOW); // Trás
digitalWrite(motorB_dir, HIGH); // Frente (ou vice-versa dependendo da fiação)
analogWrite(motorA_pwm, speedGiro); // Usa força extra para girar
analogWrite(motorB_pwm, speedGiro);
delay(tempo);
pararMotores();
}
void girarEsquerda(int tempo) {
digitalWrite(motorA_dir, HIGH); // Frente
digitalWrite(motorB_dir, LOW); // Trás
analogWrite(motorA_pwm, speedGiro);
analogWrite(motorB_pwm, speedGiro);
delay(tempo);
pararMotores();
}
// ---------- SENSOR ----------
float lerDistancia() {
digitalWrite(SonarTrigger, LOW);
delayMicroseconds(2);
digitalWrite(SonarTrigger, HIGH);
delayMicroseconds(10);
digitalWrite(SonarTrigger, LOW);
// Timeout reduzido para o robô não ficar "cego" esperando resposta
unsigned long duration = pulseIn(SonarEcho, HIGH, 25000);
if (duration == 0) return 999; // Se falhar, assume que está longe
return (duration / 2.0) / 29.1;
}
// ---------- SEQUÊNCIA DE AÇÃO (Susto + Giro) ----------
void executarSequenciaObstaculo() {
// 1. PARADA ABSOLUTA (Segurança)
pararMotores();
delay(200); // Pequena pausa para estabilizar a inércia do robô
// 2. O SUSTO (Servo + Led + Buzzer)
digitalWrite(led_olhos, HIGH);
myServo.write(85); // Levanta braços
// Buzzer (Loop intocável)
for (int i = 75; i > 30; i--) {
tone(buzzer, i);
delay(25);
}
noTone(buzzer);
// Desfaz susto
myServo.write(0); // Abaixa braços
digitalWrite(led_olhos, LOW);
delay(500); // Espera meio segundo parado antes de tentar girar
// 3. O GIRO OBRIGATÓRIO (Para sair da parede)
// Define tempo aleatório para não ficar previsível
int tempoGiro = random(TEMPO_GIRO_MIN, TEMPO_GIRO_MAX);
int lado = random(0, 2);
if (lado == 0) {
girarDireita(tempoGiro);
} else {
girarEsquerda(tempoGiro);
}
// Depois que girar, ele sai da função e o loop() volta a fazê-lo andar
}
// ---------- SETUP ----------
void setup() {
Serial.begin(9600);
pinMode(buzzer, OUTPUT);
pinMode(led_olhos, OUTPUT);
pinMode(SonarTrigger, OUTPUT);
pinMode(SonarEcho, INPUT);
pinMode(motorA_dir, OUTPUT);
pinMode(motorA_pwm, OUTPUT);
pinMode(motorB_dir, OUTPUT);
pinMode(motorB_pwm, OUTPUT);
myServo.attach(servoPin);
myServo.write(0); // Garante posição inicial
randomSeed(analogRead(A0));
// Delay inicial para você soltar o robô
delay(1000);
}
// ---------- LOOP ----------
void loop() {
// 1. LEITURA RÁPIDA
float distancia = lerDistancia();
// 2. CHECAGEM DE SEGURANÇA (O mais importante)
// Se a distancia for válida (>2) e perigosa (<=45)
if (distancia >= 2 && distancia <= DIST_STOP) {
distancia = 0;
executarSequenciaObstaculo();
distancia = 0;
// Assim que essa função termina, o robô já girou e está parado.
// Na próxima passada do loop, ele vai cair no "else" e voltar a andar.
} else {
// 3. CAMINHO LIVRE
// Implementação simples de andar aleatório
// Pequena chance aleatória de girar mesmo sem obstáculo (Wander)
// 1 em 100 chances a cada ciclo
if (random(0, 100) == 0) {
pararMotores();
int t = random(300, 600);
if (random(0,2) == 0) girarDireita(t);
else girarEsquerda(t);
}
else {
andarFrente();
}
}
// Delay curto para o loop rodar rápido e detectar obstáculos a tempo
delay(30);
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
novo: