Hello,
i am trying to add the third position (ultrasonic sensor ) to the two position of dc motor directions (Forward & Reverse), but it does not work .Since the position 1&2 worked together and ultrasonic code worked alone.
here is my code for (forward direction & Ultrasonic sensor) only:
// defines pins numbers
const int trigPin = 6;
const int echoPin = 5;
// defines variables
long duration ;
int distance;
int SPEED; // speed of motor
int switchPos3 = 4; // pin for position 3
int switchPos1 = 2; // pin for position 1
int ENA = 8; // enable pin for L298n H bridge motor driver
int In1 = 9; // input pin for L298n H bridge motor driver
int In2 = 7; // input pin for L298n H bridge motor driver
int potval =A0;// analog pin for potentiometer
// variable will change
int switchState1 = 0;
int switchState3=0;
void setup() {
// put your setup code here, to run once:
// put your setup code here, to run once:
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
pinMode (switchPos3, INPUT);
pinMode (switchPos1, INPUT);
pinMode(In1, OUTPUT);
pinMode (In2, OUTPUT);
pinMode(ENA, OUTPUT);
}
void posOne()
{
switchState1 = digitalRead (switchPos1); // read the switch pin
if ( switchState1 == HIGH )
{
SPEED = analogRead(A0); // Read potentiometer value
SPEED = SPEED * 0.249;
Serial.println(SPEED);
digitalWrite (In1, HIGH); // forward direction set pin states HIGH
digitalWrite (In2, LOW); // forward direction set pin states LOW
digitalWrite (ENA, HIGH); // forward direction set pin states HIGH
Serial.println("Position 1 = on "); // print to serial monitor
// Serial.print("Position1: "); // print to serial monitor
}
else {
//Serial.println(“off”);
digitalWrite (In2, LOW); // off
digitalWrite (In1, LOW); // off
digitalWrite (ENA, LOW); // off
}
}
void posThree(){
switchState3 = digitalRead (switchPos3); // read the switch pin
if ( switchState3 == HIGH )
{
// put your main code here, to run repeatedly:
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
//Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
}
if (distance >=5 && distance <=30)
{
analogWrite(ENA,SPEED); // Send PWM signal to L298N Enable pin
digitalWrite (In1,LOW ); // forward direction set pin states HIGH
digitalWrite (In2, HIGH); // forward direction set pin states LOW
digitalWrite (ENA, HIGH); // forward direction set pin states HIGH
}
else {
digitalWrite (ENA,LOW); // off
digitalWrite (In2, LOW); // off
digitalWrite (In1, LOW); // off
}
}
void loop() {
// put your main code here, to run repeatedly:
posThree();
posOne();
}