Bluetooth and Ultrasonic problem

When I add ultrasonic i cannot control my bluetooth anymore :o
Is it serial problem?
Here is my code thank you in advance :slight_smile:

//L293
const int motorA1  = 5;  // Pin  2
const int motorA2  = 6;  // Pin  7
const int motorB1  = 10; // Pin 10
const int motorB2  = 9;  // Pin 14
//Ultra garsas
const int trig = 7; //paduoda garsa
const int echo = 8; //priima garsa
int cm;
//LEDAI
const int lights  = 13;
const int lightsb  = 12;
bool ledState = false; // state variable for the LED
//Pypsas
const int buzzer = 3 ;
//Bluetooth
const int BTState = 2;
//Baterijos likutis
const float maxBattery = 9.0;// Change value to your max battery voltage level!
int perVolt;                 // Percentage variable
float voltage = 0.0;         // Read battery voltage
int level;
// Use it to make a delay... without delay() function!
long previousMillis = 0; // -1000*10=-10sec. to read the first value. If you use 0 then you will take the first value after 10sec. ///long previousMillis = -1000 * 10;
const long interval = 1000;    // interval at which to read battery voltage, change it if you want! (10*1000=10sec) ////long interval = 1000 * 10;
unsigned long currentMillis;   //unsigned long currentMillis;
//Papildomos nuorodos i koda
int i = 0;
int j = 0;
int state;
int vSpeed = 200;   // Default speed, from 0 to 255
int data;
void setup() {
  pinMode(motorA1, OUTPUT);
  pinMode(motorA2, OUTPUT);
  pinMode(motorB1, OUTPUT);
  pinMode(motorB2, OUTPUT);
  pinMode(lights, OUTPUT);
  pinMode(BTState, INPUT);
  pinMode(lightsb, OUTPUT);
  // BT serialas
  Serial.begin(9600);
}

void loop() {
  //Isjungti variklius jei dingsta rysys
  if (digitalRead(BTState) == LOW) {

    state = 'S';


  }

  //BT duomenu saugojimas (siuntimas gavimas) jei daugiau nei 0 bitu
  if (Serial.available() > 0) {
    state = Serial.read();
  }

  //4 greiciu reguliatorius Values must be from 0 to 255 (PWM)
  if (state == '0') {
    vSpeed = 0;
  }
  else if (state == '1') {
    vSpeed = 100;
  }
  else if (state == '2') {
    vSpeed = 180;
  }
  else if (state == '3') {
    vSpeed = 200;
  }
  else if (state == '4') {
    vSpeed = 255;
  }

  /***********************Fowardi****************************/
  //Raide F= Foward
  if (state == 'F') {
    analogWrite(motorA1, vSpeed); analogWrite(motorA2, 0);
    analogWrite(motorB1, 0);      analogWrite(motorB2, 0);
  }
  /**********************Forward Left************************/
  //Raide G= Left Foward
  else if (state == 'G') {
    analogWrite(motorA1, vSpeed); analogWrite(motorA2, 0);
    analogWrite(motorB1, 200);    analogWrite(motorB2, 0);
  }
  /**********************Forward Right************************/
  //Raide I= Right Foward
  else if (state == 'I') {
    analogWrite(motorA1, vSpeed); analogWrite(motorA2, 0);
    analogWrite(motorB1, 0);      analogWrite(motorB2, 200);
  }
  /***********************Backward****************************/
  //Raide B= Backward
  else if (state == 'B') {
    analogWrite(motorA1, 0);   analogWrite(motorA2, vSpeed);
    analogWrite(motorB1, 0);   analogWrite(motorB2, 0);
  }
  /**********************Backward Left************************/
  //Raide H= Backward Left
  else if (state == 'H') {
    analogWrite(motorA1, 0);   analogWrite(motorA2, vSpeed);
    analogWrite(motorB1, 200); analogWrite(motorB2, 0);
  }
  /**********************Backward Right************************/
  //Raide J= Backward Right
  else if (state == 'J') {
    analogWrite(motorA1, 0);   analogWrite(motorA2, vSpeed);
    analogWrite(motorB1, 0);   analogWrite(motorB2, 200);
  }
  /***************************Left*****************************/
  //Raide L= Left
  else if (state == 'L') {
    analogWrite(motorA1, 0);   analogWrite(motorA2, 0);
    analogWrite(motorB1, 200); analogWrite(motorB2, 0);
  }
  /***************************Right*****************************/
  //Raide R= right
  else if (state == 'R') {
    analogWrite(motorA1, 0);   analogWrite(motorA2, 0);
    analogWrite(motorB1, 0);   analogWrite(motorB2, 200);
  }
  /************************Lights*****************************/
  //Raide W= Lights
  else if (state == 'W') {
    if (i == 0) {
      digitalWrite(lights, HIGH);
      i = 1;
    }
    else if (i == 1) {
      digitalWrite(lights, LOW);
      i = 0;
    }
    state = 'w';
  }
  /************************Galines????*****************************/
  //Raide X= Lights
  else if (state == 'U') {
    if (i == 0) {
      digitalWrite(lightsb, HIGH);
      i = 1;
    }
    else if (i == 1) {
      digitalWrite(lightsb, LOW);
      i = 0;
    }
    state = 'u';
  }
  /**********************Pypsikas***************************/
  //Raide V= pypsikas
  else if (state == 'V') {
    if (j == 0) {
      tone(buzzer, 1000);//Speaker on
      j = 1;
    }
    else if (j == 1) {
      noTone(buzzer);    //Speaker off
      j = 0;
    }
    state = 'v';
  }
  /************************Stop*****************************/
  //Raide S= Stop
  else if (state == 'S') {
    analogWrite(motorA1, 0);  analogWrite(motorA2, 0);
    analogWrite(motorB1, 0);  analogWrite(motorB2, 0);
  }
  /***********************Batterija???*****************************/
  /*/Baterija skaitoma kas  10sec
  currentMillis = millis();
  if (currentMillis - (previousMillis) > (interval)) {
    previousMillis = currentMillis;
    //Skaitomas A0 kistukas
    voltage = (analogRead(A0) * 5.015 / 1024.0) * 11.132;
    //Procentai 5 lygiu
    perVolt = (voltage * 100) / maxBattery;
    if      (perVolt <= 75)               {
      level = 0;
    }
    else if (perVolt > 75 && perVolt <= 80) {
      level = 1;  //        Battery level
    }
    else if (perVolt > 80 && perVolt <= 85) {
      level = 2;  //Min ------------------------   Max
    }
    else if (perVolt > 85 && perVolt <= 90) {
      level = 3;  //    | 0 | 1 | 2 | 3 | 4 | 5 | >
    }
    else if (perVolt > 90 && perVolt <= 95) {
      level = 4;  //    ------------------------
    }
    else if (perVolt > 95)                {
      level = 5;
    }
    Serial.println(level);
  }

  /***********************Ultra garsas???*****************************/
  //UltraSonic 
  
  {
  
 long duration, inches, cm; // atsakymas bus cm

    // padavimas mikrosekundem
    pinMode(trig, OUTPUT);
    digitalWrite(trig, LOW);
    delayMicroseconds(2);
    digitalWrite(trig, HIGH);
    delayMicroseconds(10);
    digitalWrite(trig, LOW);

    //priimimas echo mikrosekundem po nusiuntimo
    //auksto daznio priemimas

    pinMode(echo, INPUT);

     duration = pulseIn(echo, HIGH);

    //pakeiciam laika i atstuma!

   cm = microsecondsToCentimeters(duration);
    Serial.print(cm);
    Serial.print("cm");
    Serial.println();

    delay(100);
  }
}
  //padarom skaiciavima
  // garso greitis 340m/s arba 29 mikrosekundes/cm
  // kad suzinotumem atstuma mums reik puse atstumo iki objekto
  // paskaiciuojam biski
  
   long microsecondsToCentimeters(long microseconds)
    {
      return microseconds / 29 / 2;
    }
const int lights  = 13;
const int lightsb  = 12;

Adding a suffix to one variable makes it look like you didn't plan ahead. That is not the impression you are trying to give, is it?

When I add ultrasonic i cannot control my bluetooth anymore

Perhaps I missed where you try to "control" your bluetooth.

What is on the other end of the bluetooth connection? Why is the bluetooth device tying up the hardware serial port, preventing you from debugging your code?

Please always do a Tools > Auto Format on your code before posting it. This will make it easier for you to spot bugs and make it easier for us to read.

I'm not sure if it's the cause of your issue but you have some blocking code in the ultrasonic part which is definitely problematic for combining code:

   duration = pulseIn(echo, HIGH);

This will block up to 1000 ms if no echo is received. You should set a sane timeout value (calculate the max reasonable echo time based on effective range and the speed of sound). See:
https://www.arduino.cc/en/Reference/PulseIn

   delay(100);

Don't use long delays. Instead use millis() to determine when it's time to send the next ultrasonic ping. See File > Examples > 02.Digital > BlinkWithoutDelay and:

for an example of how to do this.

Some other minor issues, unrelated to your problem:

   pinMode(trig, OUTPUT);
    pinMode(echo, INPUT);

There's no point in doing this over and over again in loop() since you never change the pinMode. Just do it once in setup(). Maybe you copied this code that was originally written to use the same pin for trigger and echo but you're not doing that so there's no reason for this.

Is it serial problem?

 Serial.print(cm);
    Serial.print("cm");
    Serial.println();

Looks like it.

Pauls: yea it's kinda it is what it is i made fron light then wanted back lights now..... and every minute make up new stuff original plan was just to make this car running on bluetooth :smiley: now i want more

Pert i tired to change i tought something will change actualy i tried alot of stuff but when i connect ultrasound my bluetooth control dies but ultrasonic range works fine :slight_smile: I'll try use milis and thanks wor your answer

Groove any suggestions to it? :slight_smile:

You did not answer the question about what the bluetooth device is paired with.

You did not say what “control” the bluetooth means.

You did not say what the code actually does, or how that differs from what you want.

Hard to help with so little to go on.

PaulS:
You did not answer the question about what the bluetooth device is paired with.

You did not say what "control" the bluetooth means.

You did not say what the code actually does, or how that differs from what you want.

Hard to help with so little to go on.

It controls my rc car trough the android smartphone i use this app arduino rc car controler

artazzs1:
It controls my rc car trough the android smartphone i use this app arduino rc car controler

what is more im new to this arduino stuff, but i did some research on it and only thing i found that serial read interfare with each other and im not sure what to to next my plan is to put Us sensor on servo so my car could bump in objects, i found out that it is possible to connect US as analog read but it's not precice because analog read has kind of random comunication as i said im new to this stuff thats why im ask, i keep on trying to solve this and if i will, i let you guys know :slight_smile:

and only thing i found that serial read interfare with each other

Is that "interface" or "interfere" ?

my plan is to put Us sensor on servo so my car could bump in objects,

I am QUITE certain that your car is able to bump into things without a Us sensor.

i found out that it is possible to connect US as analog read but it's not precice because analog read has kind of random comunication

The only way you can use analogRead() to read a US sensor is if the manufacturer added hardware to convert the time reading to an analog output. Most sensors do not have that capability. There is NOTHING random about the output of analogRead().

as i said im new to this stuff thats why im ask

Are you new to using capital letters to start sentences? Are you new to using apostrophes in contractions? Are you new to using punctuation?

The level of effort (minimal, it appears) you put into your posts is a reflection of the level of effort you put into your code, generally.

PaulS:
I am QUITE certain that your car is able to bump into things without a Us sensor.
The only way you can use analogRead() to read a US sensor is if the manufacturer added hardware to convert the time reading to an analog output. Most sensors do not have that capability. There is NOTHING random about the output of analogRead().
Are you new to using capital letters to start sentences? Are you new to using apostrophes in contractions? Are you new to using punctuation?

The level of effort (minimal, it appears) you put into your posts is a reflection of the level of effort you put into your code, generally.

Sorry if I offend you :), these thing happen when you catch spare minute at work to look for an answer :)Thinking all day long, to find a way to a problem. As far as I learned you can do everything in a thousand ways :stuck_out_tongue: I believe I'll find the answer after work :slight_smile: And i would like to thank you for your time trying to help me. By the way, I tried millis now, didin't work :frowning:

By the way, I tried millis now, didin't work

I can assure you that millis() worked just fine. It is the (unspecified) way you are using it that did not achieve the results you expected.

Of course, we have no idea what results you expected, or what results you got, but what it wrong is your expectations.

PaulS:
I can assure you that millis() worked just fine. It is the (unspecified) way you are using it that did not achieve the results you expected.

Of course, we have no idea what results you expected, or what results you got, but what it wrong is your expectations.

I mean millis worked as it suppose to work but it didin't solve my issue :slight_smile:

I guess im one step closer to figure this thing out, i think thats because bluetooth commands and ultrasonic sensor commands by commands i mean bytes interfere with each other, so is there a way for example let's say to make bluetooth count from 100 to 255 and US from 0 to 100 i believe i know how to make second part work but how can i manage bluetooth bytes to work from 100? any ideas it would be appreciated :slight_smile:

any ideas it would be appreciated

if I had any idea what you were talking about, I'd try to help.

i think thats because bluetooth commands and ultrasonic sensor commands by commands i mean bytes interfere with each other

That is just impossible.

is there a way for example let's say to make bluetooth count from 100 to 255

No, you can not make the hardware do something impossible. That would be like trying to make a horse bowl a 300 point game.

You send data to, or read data from, a bluetooth radio. That is ALL. Your code tries to read one byte from the bluetooth device, and tries to write to the bluetooth device.

For all we know, the bluetooth device is paired to a roll of duct tape. Why won't you tell us what the hell it is paired with?

Why don't you get the stupid device off the hardware serial pins, so you can debug your code?

I forgot to tell my issue is solved topic can be closed, it was PulseIn and Delay issue, so i changed it to Millis and Ping.
I leave my code, so if anybody else has a problem, your welcome to use it :slight_smile:

(Next time, please use code tags when posting big messages like this. Thanks - Moderator)

#include <NewPing.h>

//L293
const int motorA1  = 5;  // Pin  2
const int motorA2  = 6;  // Pin  7
const int motorB1  = 10; // Pin 10
const int motorB2  = 9;  // Pin 14
//Ultra garsas
const int trig = A1; //paduoda garsa
const int echo = A2; //priima garsa
const int maxDistance = 50; //cm
unsigned int pingSpeed = 50; // frequency of ping
unsigned long pingTimer;
unsigned int Distance;

NewPing sonar(trig, echo, maxDistance); // NewPing setup of pins and maximum distance.
//LEDAI
const int lights  = 13;
const int lightsb  = 12;

//Pypsas
const int buzzer = 3 ;
//Bluetooth
const int BTState = 2;
//Baterijos likutis
//const float maxBattery = 9.0;// Change value to your max battery voltage level!
//int perVolt;                 // Percentage variable
//float voltage = 0.0;         // Read battery voltage
//int level;
// Use it to make a delay... without delay() function!
//unsigned long previousMillis = 0; // -1000*10=-10sec. to read the first value. If you use 0 then you will take the first value after 10sec. ///long previousMillis = -1000 * 10;
//const long interval = 10;    // interval at which to read battery voltage, change it if you want! (10*1000=10sec) ////long interval = 1000 * 10;
//unsigned long currentMillis = 0;   //unsigned long currentMillis;unsigned int pingSpeed = 50; // frequency of ping


//Papildomos nuorodos i koda
int i = 0;
int j = 0;
int state;
int vSpeed = 255;   // Default speed, from 0 to 255
int data;
void setup() {
 pinMode(motorA1, OUTPUT);
 pinMode(motorA2, OUTPUT);
 pinMode(motorB1, OUTPUT);
 pinMode(motorB2, OUTPUT);
 pinMode(lights, OUTPUT);
 pinMode(BTState, INPUT);
 pinMode(lightsb, OUTPUT);
 // Serial for US and BT
 Serial.begin(9600);
 pingTimer = millis(); // Start now.
}

void loop() {
 //Isjungti variklius jei dingsta rysys
 if (digitalRead(BTState) == LOW) {

   state = 'S';


 }

 //BT duomenu saugojimas (siuntimas gavimas) jei daugiau nei 0 bitu
 if (Serial.available() > 0) {
   state = Serial.read();
   delay(20);
 }

 //4 greiciu reguliatorius Values must be from 0 to 255 (PWM)
 if (state == '0') {
   vSpeed = 0;
 }
 else if (state == '1') {
   vSpeed = 100;

 }
 else if (state == '2') {
   vSpeed = 180;

 }
 else if (state == '3') {
   vSpeed = 200;

 }
 else if (state == '4') {
   vSpeed = 255;

 }

 /***********************Fowardi****************************/
 //Raide F= Foward
 if (state == 'F') {
   analogWrite(motorA1, vSpeed); analogWrite(motorA2, 0);
   analogWrite(motorB1, 0);      analogWrite(motorB2, 0);

 }
 /**********************Forward Left************************/
 //Raide G= Left Foward
 else if (state == 'G') {
   analogWrite(motorA1, vSpeed); analogWrite(motorA2, 0);
   analogWrite(motorB1, 255);    analogWrite(motorB2, 0);

 }
 /**********************Forward Right************************/
 //Raide I= Right Foward
 else if (state == 'I') {
   analogWrite(motorA1, vSpeed); analogWrite(motorA2, 0);
   analogWrite(motorB1, 0);      analogWrite(motorB2, 255);

 }
 /***********************Backward****************************/
 //Raide B= Backward
 else if (state == 'B') {
   analogWrite(motorA1, 0);   analogWrite(motorA2, vSpeed);
   analogWrite(motorB1, 0);   analogWrite(motorB2, 0);

 }
 /**********************Backward Left************************/
 //Raide H= Backward Left
 else if (state == 'H') {
   analogWrite(motorA1, 0);   analogWrite(motorA2, vSpeed);
   analogWrite(motorB1, 255); analogWrite(motorB2, 0);

 }
 /**********************Backward Right************************/
 //Raide J= Backward Right
 else if (state == 'J') {
   analogWrite(motorA1, 0);   analogWrite(motorA2, vSpeed);
   analogWrite(motorB1, 0);   analogWrite(motorB2, 255);

 }
 /***************************Left*****************************/
 //Raide L= Left
 else if (state == 'L') {
   analogWrite(motorA1, 0);   analogWrite(motorA2, 0);
   analogWrite(motorB1, 255); analogWrite(motorB2, 0);

 }
 /***************************Right*****************************/
 //Raide R= right
 else if (state == 'R') {
   analogWrite(motorA1, 0);   analogWrite(motorA2, 0);
   analogWrite(motorB1, 0);   analogWrite(motorB2, 255);

 }
 /************************Lights*****************************/
 //Raide W= Lights
 else if (state == 'W') {
   if (i == 0) {
     digitalWrite(lights, HIGH);

     i = 1;
   }
   else if (i == 1) {
     digitalWrite(lights, LOW);

     i = 0;
   }
   state = 'w';
 }
 /************************Galines????*****************************/
 //Raide X= Lights
 else if (state == 'U') {
   if (i == 0) {
     digitalWrite(lightsb, HIGH);

     i = 1;
   }
   else if (i == 1) {
     digitalWrite(lightsb, LOW);

     i = 0;
   }
   state = 'u';
 }
 /**********************Pypsikas***************************/
 /*Raide V= pypsikas
   else if (state == 'V') {
   if (j == 0) {
     tone(buzzer, 1000);//Speaker on

     j = 1;

   }
   else if (j == 1) {
     noTone(buzzer);    //Speaker off

     j = 0;
   }
   state = 'v';
   }*/
 /************************Stop*****************************/
 //Raide S= Stop
 else if (state == 'S') {
   analogWrite(motorA1, 0);  analogWrite(motorA2, 0);
   analogWrite(motorB1, 0);  analogWrite(motorB2, 0);
 }


 /***********************Batterija???*****************************/
 /*Baterija skaitoma kas  10sec
   currentMillis = millis();
   if (currentMillis - (previousMillis) > (interval)) {
   previousMillis = currentMillis;
   //Skaitomas A0 kistukas
   voltage = (analogRead(A0) * 5.015 / 1024.0) * 11.132;
   //Procentai 5 lygiu
   perVolt = (voltage * 100) / maxBattery;
   if      (perVolt <= 75)               {
     level = 0;
   }
   else if (perVolt > 75 && perVolt <= 80) {
     level = 1;  //        Battery level
   }
   else if (perVolt > 80 && perVolt <= 85) {
     level = 2;  //Min ------------------------   Max
   }
   else if (perVolt > 85 && perVolt <= 90) {
     level = 3;  //    | 0 | 1 | 2 | 3 | 4 | 5 | >
   }
   else if (perVolt > 90 && perVolt <= 95) {
     level = 4;  //    ------------------------
   }
   else if (perVolt > 95)                {
     level = 5;
   }
   Serial.println(level);
   }
 */
 /***********************Ultra garsas???*****************************/
 //UltraSonic

 if (millis() >= pingTimer) {   // pingSpeed milliseconds since last ping, do another ping.
   pingTimer += pingSpeed;      // Set the next ping time.
   sonar.ping_timer(echoCheck); // Send out the ping, calls "echoCheck" function every 24uS where you can check the ping status.
   Serial.print("Ping: ");
   Serial.print(Distance); // Ping returned, uS result in ping_result, convert to cm with US_ROUNDTRIP_CM.
   Serial.println("cm");
 }
 // Loop tesinys
}

void echoCheck() { // Timer2 interrupt calls this function every 24uS where you can check the ping status.
 // Don't do anything here!
 if (sonar.check_timer()) { // This is how you check to see if the ping was received.
   // Here's where you can add code.
   Serial.print("Ping: ");
   Serial.print(sonar.ping_result / US_ROUNDTRIP_CM); // Ping returned, uS result in ping_result, convert to cm with US_ROUNDTRIP_CM.
   Serial.println("cm");
   Distance = sonar.ping_result / US_ROUNDTRIP_CM;
 }
 // Uzdrausta zona!
}