Go Down

Topic: I'd like o add the ultrasonic sensor in this code (Read 727 times) previous topic - next topic

jjboy

How should I add a condition inside of switch case to use the function ultra ().

Code: [Select]
#include <Wire.h>
#include <Servo.h>    //Biblioteca de controle servo

int lamp=12;     //lâmpada
int EN2 = 2; 
int EN3 = 3;
int EN4 = 4;
int EN5 = 5; 
int val;
int valor = 15;
int lx=90;
const int pingPin = 11;
const int start_signal = 12;
long duration, inches, cm;

//2-way servo
Servo servoX; //Servo eixo X movimento da cabeca esquerdo direito
Servo servoY; //Servo eixo Y movimento de cima para baixo
///////////////////////////////////////

void ting(void)
        {
          digitalWrite(EN2,LOW);   
          digitalWrite(EN3,LOW);
          digitalWrite(EN4,LOW);   
          digitalWrite(EN5,LOW);       
        }
       
void qian(void)
        {       
          digitalWrite(EN2,LOW);
          digitalWrite(EN3,HIGH);
          digitalWrite(EN4,LOW);
          digitalWrite(EN5,HIGH);     
        }
void hou(void)
        {       
          digitalWrite(EN2,HIGH);
          digitalWrite(EN3,LOW);
          digitalWrite(EN4,HIGH);
          digitalWrite(EN5,LOW);           
        }
void zuo(void)
        {       
          digitalWrite(EN2,LOW);
          digitalWrite(EN3,HIGH);
          digitalWrite(EN4,HIGH);
          digitalWrite(EN5,LOW);     
        }       
void you(void)
        {       
          digitalWrite(EN2,HIGH);
          digitalWrite(EN3,LOW);
          digitalWrite(EN4,LOW);
          digitalWrite(EN5,HIGH);
         
        } 


void ultra() // Ultrasonic sensor
        {
          //long duration, inches, cm;
          pinMode(pingPin, OUTPUT);
          pinMode(start_signal, OUTPUT);
          digitalWrite(start_signal, HIGH);
          delayMicroseconds(20);
          digitalWrite(start_signal, LOW);
          digitalWrite(pingPin, LOW);
          delayMicroseconds(2);
          digitalWrite(pingPin, HIGH);
          delayMicroseconds(5);
          digitalWrite(pingPin, LOW);
          pinMode(pingPin, INPUT);
          duration = pulseIn(pingPin, HIGH);
          inches = microsecondsToInches(duration);
          cm = microsecondsToCentimeters(duration); 
          Serial.print(inches);
          Serial.print("in, ");
          Serial.print(cm);
          Serial.print("cm");
          Serial.println();
          delay(80);
          }
          long microsecondsToInches(long microseconds)
          {
          return microseconds / 74 / 2;
          }
          long microsecondsToCentimeters(long microseconds)
          {
          return microseconds / 29 / 2;
          }


//Servo virar a esquerda
void servo_left()
{
  int servotemp=servoX.read();//Obter o valor atual do ângulo do servo
  servotemp-=2;//Movimento do servo de 1 grau
  if(servotemp<170&&servotemp>10) //definir o ângulo de rotação da direcção de engrenagem de 10 graus a 170 graus
  servoX.write(servotemp);
  else if (servotemp<=10)  servoX.write(10);
  else servoX.write(170);
}


//Servo virar à direita
void servo_right()
{
  int servotemp=servoX.read();//Obter o valor atual do ângulo do servo
  servotemp+=2;//Movimento do servo de 1 grau
  if(servotemp<170&&servotemp>10)//definir o ângulo de rotação da direcção de engrenagem de 10 graus a 170 graus
  servoX.write(servotemp);
  else if (servotemp<=10)  servoX.write(10);
  else servoX.write(170);
}


//servo Carregar
void servo_up()
{
  int servotemp1=servoY.read();//Obter o valor atual do ângulo do leme
  servotemp1+=2;//Obter o valor atual do ângulo do servo
  if(servotemp1<170&&servotemp1>10)//definir o ângulo de rotação da direcção de engrenagem de 10 graus a 170 graus
  servoY.write(servotemp1);
  else if (servotemp1<=10)  servoY.write(10);
  else servoY.write(170);
}


//Servo próximo turno
void servo_down()
{
  int servotemp1=servoY.read();//Obter o valor atual do ângulo do servo
  servotemp1-=2;//Movimento do servo de 1 grau
  if(servotemp1<170&&servotemp1>10)//definir o ângulo de rotação da direcção de engrenagem de 10 graus a 170 graus
  servoY.write(servotemp1);
  else if (servotemp1<=10)  servoY.write(10);
  else servoY.write(170);
}
void setup()
{
  delay(35000);//Um atraso de 35 segundos, para evitar a interferência emitida pela inicialização do roteador porta WF171
  Serial.begin(9600);//Definir a taxa de transmissão de 9600bps
  servoX.attach(8);//Servo horizontal por 10 metros
  servoY.attach(9);//Superior e inferior de engrenagem de direção, em seguida, 11 pés
  servoX.write(90);//A posição X de saída servos inicial de 90 graus
  servoY.write(90);//A posição Y de saída servos inicial de 90 graus
  pinMode(lamp,OUTPUT);
pinMode(EN2,OUTPUT);
pinMode(EN3,OUTPUT);
pinMode(EN4,OUTPUT);
pinMode(EN5,OUTPUT);
pinMode(11,OUTPUT);
pinMode(12,OUTPUT);

}


void loop()
{
   
  if (Serial.available())
{ val = Serial.read();
  switch(val)
{
  case 'a':
    servoX.write(lx);
     qian();
     break;
   case 'b':
     hou();
     break; 
   case 'c':
     zuo();
     break;
   case 'd':
    you();
     break;
   case 'e':
    ting();
     break; 
   case 'j':
     servo_left();
     break;
   case 'l':
     servo_right();
     break;
   case 'k':
    servo_up();
    break;
   case 'i':
     servo_down();
     break;
  case 'n':
     digitalWrite(lamp,HIGH);
     break;
  case 'm':
    digitalWrite(lamp,LOW);
    break;
}
}
}

PeterH


How should I add a condition inside of switch case to use the function ultra ().


If you mean how do you add a new case to a switch, you just type in code similar to the other cases and ensure it has a unique label. If you mean how do you add conditional code within a case statement, it's just like adding conditional code anywhere else.
I only provide help via the forum - please do not contact me for private consultancy.

jjboy

Something like this but I don't know how to do it


if (Serial.available())
{ val = Serial.read();
  switch(val)
if (ultra() <= 15)
hou();
delay (80);

else gian ();

{
  case 'a':
    servoX.write(lx);
     qian(); // forward
     break;
   case 'b':
     hou(); // stop
     break; 

PeterH


Something like this but I don't know how to do it


Can you explain in words what you want the code to do?

The code snippet you posted doesn't make enough sense for me to figure out what you're trying to achieve.
I only provide help via the forum - please do not contact me for private consultancy.

jjboy

http://imageshack.us/a/img9/3812/truck012.jpg

This is the original code for the Rover car. I just want to add the ultrasonic sensor so when the car get close to object ( 15cm ) the car stop, back and turn left or right. Thanks for you help PeterH. I'm newbie.

Code: [Select]
#include <Servo.h>    //?????
int lamp=12;     //?
int EN2 = 2; 
int EN3 = 3;
int EN4 = 4;
int EN5 = 5; 
int val;
int lx=90;
//2???
Servo servoX; //??X??? ??
Servo servoY; //??Y??? ??
///////////////////////////////////////
void ting(void)
        {
          digitalWrite(EN2,LOW);   
          digitalWrite(EN3,LOW);
          digitalWrite(EN4,LOW);   
          digitalWrite(EN5,LOW);       
        }
       
void qian(void)
        {       
          digitalWrite(EN2,LOW);
          digitalWrite(EN3,HIGH);
          digitalWrite(EN4,LOW);
          digitalWrite(EN5,HIGH);     
        }
void hou(void)
        {       
          digitalWrite(EN2,HIGH);
          digitalWrite(EN3,LOW);
          digitalWrite(EN4,HIGH);
          digitalWrite(EN5,LOW);           
        }
void zuo(void)
        {       
          digitalWrite(EN2,LOW);
          digitalWrite(EN3,HIGH);
          digitalWrite(EN4,HIGH);
          digitalWrite(EN5,LOW);     
        }       
void you(void)
        {       
          digitalWrite(EN2,HIGH);
          digitalWrite(EN3,LOW);
          digitalWrite(EN4,LOW);
          digitalWrite(EN5,HIGH);
         
        } 
//????
void servo_left()
{
  int servotemp=servoX.read();//??????????
  servotemp-=2;//????1?
  if(servotemp<170&&servotemp>10) //???????????10??170?
  servoX.write(servotemp);
  else if (servotemp<=10)  servoX.write(10);
  else servoX.write(170);
}


//????
void servo_right()
{
  int servotemp=servoX.read();//??????????
  servotemp+=2;//????1?
  if(servotemp<170&&servotemp>10)//???????????10??170?
  servoX.write(servotemp);
  else if (servotemp<=10)  servoX.write(10);
  else servoX.write(170);
}


//????
void servo_up()
{
  int servotemp1=servoY.read();//??????????
  servotemp1+=2;//????1?
  if(servotemp1<170&&servotemp1>10)//???????????10??170?
  servoY.write(servotemp1);
  else if (servotemp1<=10)  servoY.write(10);
  else servoY.write(170);
}


//????
void servo_down()
{
  int servotemp1=servoY.read();//??????????
  servotemp1-=2;//????1?
  if(servotemp1<170&&servotemp1>10)//???????????10??170?
  servoY.write(servotemp1);
  else if (servotemp1<=10)  servoY.write(10);
  else servoY.write(170);
}
void setup()
{
  delay(35000);//??35????WF171?????????????????
  Serial.begin(9600);//??????9600bps
  servoX.attach(8);//?????10?
  servoY.attach(9);//?????11?
  servoX.write(90);//?????????90?
  servoY.write(90);//?????????90?
  pinMode(lamp,OUTPUT);
pinMode(EN2,OUTPUT);
pinMode(EN3,OUTPUT);
pinMode(EN4,OUTPUT);
pinMode(EN5,OUTPUT);
}


void loop()
{

  if (Serial.available())
{ val = Serial.read();
  switch(val)
{
  case 'a':
    servoX.write(lx);
     qian();
     break;     
   case 'b':
     hou();
     break;     
   case 'c':
     zuo();
     break;
   case 'd':
    you();
     break;
   case 'e':
    ting();
     break; 
   case 'j':
     servo_left();
     break;
   case 'l':
     servo_right();
     break;
   case 'k':
    servo_up();
    break;
   case 'i':
     servo_down();
     break;
  case 'n':
     digitalWrite(lamp,HIGH);
     break;
  case 'm':
    digitalWrite(lamp,LOW);
    break;
}
}
}

AWOL

Quote
if (Serial.available())
{ val = Serial.read();
  switch(val)
if (ultra() <= 15)
hou();
delay (80);

else gian ();

Your switch/case is there to process serial commands, but the sensor code should be running all the time, and so should be completely outside of the serial command processing. Maybe the first thing in "loop" should be your sensor read, before you even check the serial port to see if anything is there.
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

UKHeliBob

Here is how I have done it with a 2 wheeled buggy

Code: [Select]
void loop()
{
  int cm = lookForward();
  while (cm > 20)
  {
    random(0,1);              //help randomise turns
    forwardBoth(HIGH_SPEED);
    cm = lookForward();
    Serial.println(cm);
  }
  hardStopBoth();
  delay(1000);
  backUp(SLOW_SPEED);
  randomSpin(SLOW_SPEED);
}


The lookFoward() function returns a value indicating how far ahead any obstruction is
If it is less than 20 cm both motors are stopped, the buggy backs up then spins either way for a random time.

In your case you need to insert such code in loop() before reading the serial input as it has priority over other actions.
Please do not send me PMs asking for help.  Post in the forum then everyone will benefit from seeing the questions and answers.

PaulS

The ultra() function is declared not to return a value. Yet, it has return statements that try to return values. They will generate warnings, but they are suppressed. The values will simply be discarded.

So, calling the ultra() function will be a waste of time.

Go Up