Links

Template Code for techCar.ino

For reference...
If you need to restart your custom code file, you can copy and paste this.
#include "ElegooCar4.h"
ElegooCar4 car;
int followLine();
void usePhoneInput();
void driveUpToWall();
void drivePattern();
// SETUP RUNS ONCE AT STARTUP
void setup()
{
Serial.begin(9600);
car.setLED(100, 100, 100);
}
// LOOP RUNS CONTINUOUSLY AFTER SETUP
void loop()
{
if (car.checkToggle())
{
car.setLED(0, 100, 0);
drivePattern();
// driveUpToWall();
// followLine();
// usePhoneInput();
}
else
{
if (car.batteryCheck())
{
car.setLED(0, 0, 100);
}
else
{
car.setLED(100, 0, 0);
}
car.drive(0, 0);
}
}
// CUSTOM FUNCTIONS BELOW
void drivePattern()
{
int speed = 75;
car.drive(speed, speed);
delay(2000);
car.drive(0, 0);
delay(1000);
car.drive(-speed, -speed);
delay(2000);
car.drive(0, 0);
delay(1000);
car.drive(speed, -speed);
delay(2000);
car.drive(0, 0);
delay(1000);
car.drive(-speed, speed);
delay(2000);
car.drive(0, 0);
delay(1000);
}
void driveUpToWall()
{
int distance = car.getUltrasonicDistance();
while (distance > 10)
{
car.drive(50, 50);
distance = car.getUltrasonicDistance();
if (!car.checkToggle())
{
break;
}
}
car.drive(0, 0);
}
void usePhoneInput()
{
String input = car.getPhoneInput();
if (input != "null")
{
Serial.println(input);
}
if (input == "up")
{
car.drive(50, 50);
delay(2000);
car.drive(0, 0);
}
else if (input == "down")
{
car.drive(-50, -50);
delay(2000);
car.drive(0, 0);
}
else if (input == "left")
{
car.drive(-50, 50);
delay(2000);
car.drive(0, 0);
}
else if (input == "right")
{
car.drive(50, -50);
delay(2000);
car.drive(0, 0);
}
else if (input == "standby")
{
car.drive(0, 0);
car.setServo(90);
}
else if (input == "line")
{
}
else if (input == "avoid")
{
}
else if (input == "follow")
{
}
else if (input == "servo-left")
{
car.setServo(0);
}
else if (input == "servo-right")
{
car.setServo(180);
}
}
int followLine()
{
// speed settings
int low = 10;
int medium = 40;
int high = 80;
int line = car.getLineTracking(400); // adjust the threshold for black/white as needed
switch (line)
{
case 0:
car.drive(low, low); // very slow, all bright
break;
case 1:
car.drive(high, 0); // hard right, right sensor on dark
break;
case 2:
car.drive(0, high); // hard left, left sensor on dark
break;
case 3:
car.drive(high, high); // straight, center sensor on dark
break;
case 4:
car.drive(medium, high); // subtle left, left and center sensors on dark
break;
case 5:
car.drive(0, 0); // stop, left and right sensors on dark
break;
case 6:
car.drive(high, medium); // subtle right, right and center sensors on dark
break;
case 7:
car.drive(0, 0); // stop, all dark
break;
}
return line;
}