Errors while trying to ping HC-SR04 sensor and sound a tone at once

Hello guys I got my Arduino 2 days ago and I’m fairly new to programming as well (I just know very basic stuff). I’m yet trying to get distance from my HC-SR04 Ultrasonic Distance Sensor and play a C4 (Do) note from a piezo at the same time. I tried to combine from 2 working codes, which then I want to turn into a musical instrument kinda thing, but I haven’t been able to compile it successfully.

Source code:

#include <NewPing.h>
#include "pitches.h"

int ses = 8;
int sensorValue = 0;

#define TRIGGER_PIN  12
#define ECHO_PIN     11
#define MAX_DISTANCE 400

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {
  pinMode(ses, OUTPUT);
  Serial.begin(115200);
}

void loop() {
  tone(ses, NOTE_C4, 20);
  delay(50);
  Serial.print(sonar.ping_cm());
}

I have both included .h files in my library and they work fine with other codes.

This is the error:

Arduino: 1.8.2 (Windows 10), Board: "Arduino/Genuino Uno"

Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':

(.text+0x0): multiple definition of `__vector_7'

libraries\NewPing\NewPing.cpp.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Arduino/Genuino Uno.

Both NewPing and tone() use the same timer. You can't use them in the same sketch.

Any way to fix it then? Can't I change the timer or something?

Can’t I change the timer or something?

Feel free to look at both libraries, and try to change the timer that one of them uses.

I looked inside the libraries and I have no idea how to change or even find a timer

PaulS: Both NewPing and tone() use the same timer. You can't use them in the same sketch.

By the way sorry if I sounded rude. Thank you. I appreciate your clarification. Now I can try to find a workaround

I would try to find another library to use instead of NewPing - timer conflicts are common enough that you can usually find versions of the library with different timers. Sometimes the library itself has #defines in it that you can change to make it use different timers.

DrAzzy: I would try to find another library to use instead of NewPing - timer conflicts are common enough that you can usually find versions of the library with different timers. Sometimes the library itself has #defines in it that you can change to make it use different timers.

Thank you so much. I used NewTone instead of tone and it works fine now. +1