Skip to content

Instantly share code, notes, and snippets.

@mendax1234
Created November 30, 2024 08:52
Show Gist options
  • Save mendax1234/49efa9daa3693b5ed746ae405ccc6d1a to your computer and use it in GitHub Desktop.
Save mendax1234/49efa9daa3693b5ed746ae405ccc6d1a to your computer and use it in GitHub Desktop.
EG1311 B13 T06 (AY24/25 Sem1) Code
#include <Servo.h>
int TRIG_PIN = 13;
int ECHO_PIN = 12;
int MOTOR_PIN1 = 5;
int MOTOR_PIN2 = 6;
int SERVO_PIN = 3;
float SPEED_OF_SOUND = 0.0345;
bool is_backward = false;
unsigned long forward_time;
Servo servo;
void setup() {
// Set all the motor pins to be out
pinMode(MOTOR_PIN1, OUTPUT);
pinMode(MOTOR_PIN2, OUTPUT);
digitalWrite(MOTOR_PIN1, LOW);
digitalWrite(MOTOR_PIN2, LOW);
// Initialize forward time
forward_time = 0;
// Set servo
// setup the servo at 0 degrees because otherwise by default, it will be set to 90 degrees.
// use servo.attach(SERVO_PIN, num1, num2) to set the pulse width for 0 degree and 180 degree seperately
servo.write(0);
servo.attach(SERVO_PIN);
// Set ultrasonic sensor
pinMode(TRIG_PIN, OUTPUT);
digitalWrite(TRIG_PIN, LOW);
pinMode(ECHO_PIN, INPUT);
Serial.begin(9600);
Serial.println(is_backward);
}
void loop() {
// Ultrasonic Sensor
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
int microsecs = pulseIn(ECHO_PIN, HIGH);
float cms = microsecs * SPEED_OF_SOUND / 2;
Serial.print("CMS:");
Serial.println(cms);
Serial.println(forward_time);
Serial.println(is_backward);
// Control Logic
if (cms < 15 && !is_backward && forward_time >= 200)
{
digitalWrite(MOTOR_PIN1, LOW);
digitalWrite(MOTOR_PIN2, LOW);
// Wait for 2 seconds
delay(2000);
// Shoot the ball
servo.write(90);
delay(1000);
// Move the catapult
servo.write(0);
delay(2000);
is_backward = true;
}
else
{
// Move Forward
digitalWrite(MOTOR_PIN1, HIGH);
digitalWrite(MOTOR_PIN2, LOW);
forward_time++;
}
if (is_backward)
{
// Move Backward
digitalWrite(MOTOR_PIN1, LOW);
digitalWrite(MOTOR_PIN2, HIGH);
}
delay(10);
}
@mendax1234
Copy link
Author

The CAD files and Circuit can be found here

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