so ive tried for days a few different ways and i just cant get this to work, yes its another self driving rc car type project but with a few tiny minor differences.
right now i am in the very early part of this process so my errors shouldnt be hard to spot.
now the code compiles but i'm still having issues, all you need to know is that i have a test circuit wired to leds for simplicity's sake.
the code compiles, and the serial monitor is outputting distance properly (i use a ruler just to be sure lol)
so when i go to test the leds don't light when expected or just get stuck in one form or another, Ive switched the if statements around and sometimes i can get one of the functions to execute consistently when expected but then none of the others work, almost always the accelerate function works and i do see the brightness of the led corresponding to throttle correctly.
I could speculate on and on about why it doesn't work, i'm sure i need a bool or something, which i am just grasping the concept of how a boolean works but its still a little rocky, i understand how they work but don't really understand how to implement it in my code, idk. Maybe the way i'm declaring functions is all wrong i'm not sure anyway here is my code at this point..... and im using a mega btw
#include <NewPing.h>
#define TRIGGER_PIN 12
#define ECHO_PIN 11
#define MAX_DISTANCE 200
#define FRWD 22
#define RVRS 23
#define THROTTLE 3
const int incoming_object_distance = 50;
const int slow_down_distance = 25;
const int Ebrake_distance = 10;
const int slow = 75;
int AccelValue = 5;
float distance;
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
void setup() {
pinMode(FRWD, OUTPUT);
pinMode(RVRS, OUTPUT);
pinMode(THROTTLE, OUTPUT);
Serial.begin(9600);
distance = readping();
delay(20);
digitalWrite(FRWD, LOW);
digitalWrite(RVRS, LOW);
analogWrite(THROTTLE, 0);
}
void loop() {
if (distance >= incoming_object_distance) {
Forward();
distance = readping();
}
else if (distance <= slow_down_distance) {
Slow();
distance = readping();
}
else if (distance >= Ebrake_distance) {
Stop();
delay(100);
Reverse();
distance = readping();
}
else if (distance <= Ebrake_distance) {
Stop();
distance = readping();
}
else
{
Forward();
}
delay(30);
distance = readping();
Serial.print("Ping: ");
Serial.print(distance);
Serial.println("cm");
}
int readping()
{
int cm = sonar.ping_cm();
if (cm == 0) {
cm = 250;
}
return cm;
}
void accelerate()
{
if (AccelValue < 255)
{
if (AccelValue >= 245)
{
AccelValue = 255;
}
else
{
AccelValue++;
}
analogWrite(THROTTLE, AccelValue);
delay(100);
}
}
void Slow()
{
analogWrite(THROTTLE, slow);
AccelValue = 0;
}
void Stop()
{
AccelValue = 0;
digitalWrite(FRWD, LOW);
analogWrite(THROTTLE, 0);
digitalWrite(RVRS, LOW);
}
void Forward()
{
digitalWrite(RVRS, LOW);
digitalWrite(FRWD, HIGH);
accelerate();
}
void Reverse()
{
digitalWrite (FRWD, LOW);
digitalWrite(RVRS, HIGH);
Slow();
delayMicroseconds(1000);
AccelValue = 0;
digitalWrite(RVRS, LOW);
}