Pages: [1]   Go Down
Author Topic: I'd like o add the ultrasonic sensor in this code  (Read 469 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 3
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Code:
#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;
}
}
}
Logged

UK
Offline Offline
Shannon Member
****
Karma: 184
Posts: 11196
-
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

I only provide help via the forum - please do not contact me for private consultancy.

Offline Offline
Newbie
*
Karma: 0
Posts: 3
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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; 
Logged

UK
Offline Offline
Shannon Member
****
Karma: 184
Posts: 11196
-
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

I only provide help via the forum - please do not contact me for private consultancy.

Offline Offline
Newbie
*
Karma: 0
Posts: 3
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
#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;
}
}
}
Logged

Global Moderator
UK
Offline Offline
Brattain Member
*****
Karma: 241
Posts: 24480
I don't think you connected the grounds, Dave.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

"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.

East Anglia (UK)
Offline Offline
Faraday Member
**
Karma: 90
Posts: 3527
May all of your blinks be without delay()
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Code:
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.
Logged

Please do not send me PMs asking for help.  Post in the forum then everyone will benefit from seeing the questions and answers.

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 553
Posts: 46300
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

Pages: [1]   Go Up
Jump to: