Show Posts
Pages: 1 2 3 [4] 5 6 ... 31
46  Using Arduino / Programming Questions / Re: Libraries incompatible: IRemote.cpp vs. NewPing.cpp on: July 11, 2013, 12:05:29 pm
Did anyone ever resolve this?  I ran into the same issue last night, thought I'd ask if anyone worked it out before I started digging into the libraries.

The timer 2 stuff is only in NewPing for the timer interrupt method ping_timer().  If you're just using the standard ping(), ping_in(), ping_cm(), or ping_median() methods, NewPing is not using timer 2.  However, the compiler is not smart enough to know that you're not using those interrupts. So you'll get this error if any other library is also using timer 2.

There's an easy solution as long as you're not using ping_timer().  Change the NewPing.cpp program and comment out the section that calls timer 2.  Find this section at around lines 210 - 216 in version 1.5:

#if defined (__AVR_ATmega32U4__) // Use Timer4 for ATmega32U4 (Teensy/Leonardo).
ISR(TIMER4_OVF_vect) {
if(intFunc) intFunc(); // If wrapped function is set, call it.

Comment it all out like this:

#if defined (__AVR_ATmega32U4__) // Use Timer4 for ATmega32U4 (Teensy/Leonardo).
ISR(TIMER4_OVF_vect) {
if(intFunc) intFunc(); // If wrapped function is set, call it.

That's it!  Also, if the conflict is with the tone library, you can use a different tone library that doesn't use timer 2.  I've created a couple tone replacement libraries that not only use timer 1 instead of timer 2 to avoid a conflict, they also have many other advantages:

NewTone - About 1,200 bytes smaller code size than the standard tone library. Faster execution time. Exclusive use of port registers for fastest and smallest code. Higher quality sound output than tone library. Plug-in replacement for Tone. Uses timer 1 which may free up conflicts with the tone library.

toneAC - Nearly twice the volume (because it uses two out of phase pins in push/pull fashion). Higher quality (less clicking). Capability of producing higher frequencies (even if running at a lower clock speed). Nearly 1.5k smaller compiled code. Bug fixes (standard tone library can generate some odd and unpredictable results). Can set not only the frequency but also the sound volume. Less stress on the speaker so it will last longer and sound better.

In addition, version 1.6 of the NewPing library (currently under development) will include a setting that allows you to easily turn off the timer 2 stuff if you're not using the ping_timer() method.

47  Using Arduino / Sensors / Re: NewPing Library: HC-SR04, SRF05, SRF06, DYP-ME007, Parallax PING))) - v1.5 on: July 01, 2013, 09:56:18 am
really new to arduino and coding, so I am trying to figure out this library.  I have been searching and trying things out on my own, but haven't see any examples of using the 2 commands the way I am attempting.  I think I have figured it out... at least it appears this snippet of my code is working.
 What I am trying to do with this is return the center reading (median) out of 15. using convert_in to convert it to inches. I figure returning 15 readings, choosing the median one is the middle between the high and low readings.
Is this correct?

centerDist = (sonar.convert_in(sonar.ping_median(15)));
 //median ping (out of 15), distance in inches and assign to centerDist on sensor named "sonar"

I run it and it seems to give me a very accurate reading, in inches.  Is there anything wrong with this format?

That's correct.  That command will return the median distance measurement in inches out of 15 pings.  With that many iterations, it should give very stable results.

If you find that the distance is slightly off, it's because of the convert_in() math, which by default simply divides the ping microseconds by 146.  For example, the following code will give the same result:

centerDist = sonar.ping_median(15) / 146;

If you find that you need more accurate conversion from ping time to distance and wish to create a calculation based on temperature readings, you can replace the division by 146 (or the convert_in()) to whatever calculation you wish based on temperature, altitude, humidity, or whatever level of accuracy you wish.  The convert_in() is designed to be fast, create small code, not require additional sensors, and be fairly accurate for almost all users.  If you need higher accuracy, you can use whatever calculations you wish with NewPing.

48  Using Arduino / Sensors / Re: NewPing Library: HC-SR04, SRF05, SRF06, DYP-ME007, Parallax PING))) - v1.5 on: June 18, 2013, 11:48:42 am
I'm trying to use an SR04 with the single-pin method, but I can't get it to work.  I've tried it with two different identical looking sensors purchased from Amazon and eBay.  This is on an Arduino Uno (might be a SainSmart recreation but it looks like an authentic one, not sure.

What troubleshooting steps can I try?

Start with supplying your sketch, schematic, and exactly what your results are. "can't get it to work" is too vague to diagnose over the internet with no other information.

49  Using Arduino / Sensors / Re: Problem with Ping))) sensor and Arduino accuracy. on: May 24, 2013, 01:40:24 pm

Im new here at the forum so I hope i'm posting this at the right Place.

I bought myself an Arduino Mega 2560 and some Ping))) sensors and after some testing with the NewPing librarie which I found here I had them up and running sending me measurments in centimeters (I also wrote my own code which gives me the same result).

Then i Went ahead testing the accuracy and here is were the problem starts (You might find this a small problem but for my Project this is a big problem).

If the actual measurment is 20 cm arduino shows me 21, 30 shows 31, 40 shows 41.
50 shows 50, 60 shows 60 and so on up to 120 where sensor shows 121 again...

so between 50 and 110 cm all works great but below 50 and above 120 it ads a centimeter... has anyone else  run into this problem or has any idea how i could solve this (I know I can do a if ping < 50 ping = ping - 1 but that's plan B).

My guess is that you don't have ROUNDING_ENABLED set to true in the NewPing header file.  Try that and see if your accuracy is better.  It's disabled by default because the level of accuracy you describe is PLENTY good for 99.9% of people.  If not, try turning on the rounding and it should give better results.

But, if you have any issues with the distance calculation, simply use the ping() method instead of ping_cm() and apply your own conversion to distance.  If the numbers are still not right, the fault is with the accuracy of the sensor, which is typically only good to about +/- 0.33 cm.

50  Using Arduino / Sensors / Re: NewPing Library: HC-SR04, SRF05, SRF06, DYP-ME007, Parallax PING))) - v1.5 on: May 24, 2013, 01:36:15 pm
yes. i do think you missed something.

if i run the new ping sampe code i get a minimum error of 1cm or 2cm even in an absolutely stable setup, if i change the calculation to float the error is a little bit smaller but still in the range of 1cm. and both will give no stable values. the results fluctuate with ever line on the console.

if i use my 'slow' method to measure i get an error that is in the range of 1mm and absolutely stable values. no fluctuation. repeated measurements give the same distance again and again.

this is a huge difference for my application. and now it makes sense to appy the temperature correction.

if you say that this is not your intendet usage scenario that is fine with me. but to say the sensors are inherently so bad that nothing can be done ist just plain wrong.

Maybe you need to turn on rounding in the header file?  #define ROUNDING_ENABLED true

I get stable values with no fluctuations with my library without any modifications with all the sensors I have.

The math doesn't change from sensor reading to sensor reading.  So, if the sensor is outputting the exact same ping time, the exact same distance calculation will occur.  With this said, it does depend on how it's rounded.  By default, NewPing truncates the distance calculation.  So if the distance is say 50.95cm it could flip between 50 and 51cm.  This has to do with the margin of error of the sensor, which is around 0.33cm.  With the rounding enabled, the same situation as shown above would yield a stable 51cm.

I think you've confused the accuracy of the sensors and the method of time to distance calculation.  But, in all cases, you can simply just use the ping() method which just gives you the ping time.  Then, you can do whatever logic you wish to convert this to a distance.  The ping_cm() and ping_in() methods are meant to be a down and dirty, fast, and tight way of getting accurate results.  This works for 99.9% of people best.  But, if you're in the 0.01% that must use a different formula and use a thermometer to get more accurate results, NewPing is already set to work for you, just use the ping() method.

Basically, what I'm saying is that you should use the ping() method and use your own math.  NewPing is not the place to debate the speed of sound (which is yet another debate that 0.01% of people want to get into).  I'm not getting into this and won't be changing NewPing making it bigger and more complex for 0.01% of people.  One of the primary goals of NewPing is to be smaller and faster than other ping libraries.  While adding rounding and temperature calculations could make it ever so slightly more accurate, it's simply not within the scope of the project, and what the ping() method is exactly designed for.  So please, use ping() and this can be the last I hear of time to distance calculations, it's an old, dead, and boring topic that I don't wish to debate further.

51  Using Arduino / Sensors / Re: NewPing Library: HC-SR04, SRF05, SRF06, DYP-ME007, Parallax PING))) - v1.5 on: May 20, 2013, 02:55:19 pm
The fact that the sensors are not accurate is imho no argument to use math that adds additional errors. The relative errors add up.
That said, I agree with you that most applications do not need this level of accuracy.


If you want to use floating point values, more power to you, go for it!  NewPing FULLY supports doing this.  *YOU* have the ability to change the US_ROUNDTRIP_CM and US_ROUNDTRIP_IN values to whatever you want, or use ping() and do any other calculations you wish factoring in temperature, altitude, humidity, etc.

The fact is, my integer values are typically more accurate than when people try to over complicate things by using floating point values in attempts to get more accurate values.  But, if you're in search for the holy grail of ultrasonic measurement, use ping() and apply your magic formula.

This is *NOT* something that will be added to NewPing as it's outside the scope of the library to be any more accurate than it is now.  Because, to be more accurate you'd need a thermometer, and apply your own formula.  So, while this is a fine topic, it shouldn't be here as it will never be added to NewPing.  Heck, there's debate on the speed of sound, I'm just staying out of the fight.

Topic closed.
52  Using Arduino / Sensors / Re: NewPing Library: HC-SR04, SRF05, SRF06, DYP-ME007, Parallax PING))) - v1.5 on: May 20, 2013, 10:05:18 am

Hi Teckel,

did investigate the duration2cm() function here -,165860.0.html -
might be useful in your library.

I tried something similar in the past, but honestly it's not worth the extra cycles adding this type of code adds.  Basically, it's pointless to try to make the math more accurate than the sensor is.  Ultrasonic sensors are not very accurate anyway.  Also, there's actually an argument as to the speed of sound (everyone likes to use a different number).  This is why I settled on an integer and the value that I default to.  It provides very accurate distance results in typical indoor temperatures and does so very fast using very little program space.

Instead of getting into this battle, I avoid it.  Just use the ping() method which returns a ping time.  Then, use whatever math you want (based on temperature or whatever).  If you want to use a fraction and want to use a different method to calculate this (like the above linked example) that's fine also.

Keep in mind that NewPing is an ultrasonic ping library, not a floating point, math, or temperature library.  I'm sure you can find or develop a library that allows you to divide a floating point number without using floating point math.  This would be then just included in your sketch along with NewPing to calculate a distance at whatever accuracy level you desired.  But keep in mind that the sensor isn't that accurate anyway (only  about 1cm).  So all this effort may be wasted anyway.

53  Using Arduino / Sensors / Re: NewPing Library: HC-SR04, SRF05, SRF06, DYP-ME007, Parallax PING))) - v1.5 on: May 05, 2013, 09:32:11 pm
some ideas about accuracy...

i have just gotten my sr04 and played a lithe with it. i intend to use it to measure oil level in a tank. so accuracy is quite important.
after reading on the web there are two main points that seem to influence the accuracy of the sensor and both are not accounted for in the newping library:

- one is temperature. it would be nice to be able to set the temperature that newping uses for the conversion to cm/inces. depending on the temperaure the error can easily be in the range of 10% if temperature is not accounted for.

- the other one is the which echo is received and evaluated. if i do repeated measurements i notice that the results will be relatively near around two or tree that are themselves further apart. this looks like it is consistent with some articles that say this error comes from reading the second or third echo and not the first and should be especialy noticeable in the short range.

so to be able to make more accurate measurements i started reading 10 or 50 pings, iterating over all of them and throwing away all that are equal to the largest and all that are equal to the smallest and then averaging the rest. if there are non available after throwing the smallest and largest away i take the smallest. the conversion to cm is then done in float.

this seems to give very accurate and reproduceable results. doing this repeatedly in a range of 1cm to 1m gives identical results up to at least 1mm.

maybe a 'slow scan' option could add this to the newping library for applications where fast response times are not needed.

1) Because you need an outside thermometer to measure temperature, it was decided not to overly complicate the NewPing library.  However, NewPing *IS* designed to adjust with temperature.  Simply use the ping() method which gives you a time.  Then, do your own calculation of distance based on your thermometer attached to the Arduino.  In almost all situations, the default distance works well for average indoor temperatures.  But, if you need accuracy, you're going to need additional hardware and then (of course) you're going to need to do your own calculation.  But, NewPing will work with this situation just fine.

2) This isn't a problem with the library, nor can it be fixed in a library.  This is fixed by following the instructions in my sample sketches.  Basically, if you ping a second time too quickly after a previous ping, you can get an echo.  This can't be fixed by the library as it's only reading what the sensor outputs, which is a digital signal (the library has no amplitude information).  The solution is to simply heed my warnings in my sketches.  Which is to not ping too quickly.  Your pings shouldn't be more frequently than around once every 29ms.  If you're in a highly sonicly reflective environment, or your sensor is overly sensitive, you may need to increase this amount.  If it's not something fast moving (probably like in your case) ping once every second or two even.  That way, you can be assured that you're not reading an echo.  NewPing doesn't control the speed of the pings *YOU* do.  If you want to make it slow, just make it slow.  Maybe I'm missing something?

54  Development / Other Software Development / Re: PWM frequency library on: April 29, 2013, 12:21:12 pm
There are technically libraries out there that allow you to set the PWM frequency.  They are, however, typically labeled as audio "tone" libraries.  It doesn't matter if the library is designed for audio, it's still just a PWM library.  I've written some of these libraries, some of which will output PWM signals at up to the gigahertz range.

This interests me.  Particularly the part about the gigahertz range.  I haven't heard of this before.  Could you point me to somewhere that explains how this is done?

Sorry, must have been drunk, I meant MEGAhertz, not gigahertz.

One of my tone libraries (toneAC) does PWM control of two pins alternating at up to 2.66 MHz with an ATmega running at 16MHz.

Official site
Arduino Playground
Support forum

Sorry about the confusion.

55  Using Arduino / Sensors / Re: NewPing Library: HC-SR04, SRF05, SRF06, DYP-ME007, Parallax PING))) - v1.5 on: April 16, 2013, 03:04:46 pm
Hi! Fantastic library.

I simply want to use 2 HC-SR04 sensors and use the result to turn on their appropriate LED when MAX_DISTANCE is less than 30.

SR04 #1 - turns on LED1 when MAX_DISTANCE is less than 30
            - turns off LED1 when MAX_DISTANCE is greater than 30

SR04 #2 - turns on LED2 when MAX_DISTANCE is less than 30
            - turns off LED2 when MAX_DISTANCE is greater than 30

I added an if/else statement in the pingResults() function, LED 1 turns ON and remains on when
either sensor is triggered.
What do I have to do to declare both sensor 1 and sensor 2 in the function?  

Sounds pretty simple but I'm kinda new at this so be gentle!  smiley


Here's the sketch:

#include <NewPing.h>

#define SONAR_NUM      2
#define MAX_DISTANCE 30
#define PING_INTERVAL 33
//LED setup
#define LED_1   12
#define LED_2   13

unsigned long pingTimer[SONAR_NUM];
uint8_t currentSensor = 0;

NewPing sonar[SONAR_NUM] = {  
  NewPing(4, 5, MAX_DISTANCE),
  NewPing(6, 7, MAX_DISTANCE)  

void setup() {
  pinMode(LED_1, OUTPUT);
  pinMode(LED_2, OUTPUT);
  pingTimer[0] = millis() + 75;
  for (uint8_t i = 1; i < SONAR_NUM; i++)
    pingTimer = pingTimer[i - 1] + PING_INTERVAL;

void loop() {
  for (uint8_t i = 0; i < SONAR_NUM; i++) {
    if (millis() >= pingTimer) {    
      pingTimer += PING_INTERVAL * SONAR_NUM;  
      currentSensor = i;                  


void echoCheck() {  
  if (sonar[currentSensor].check_timer())
    pingResult(currentSensor, sonar[currentSensor].ping_result / US_ROUNDTRIP_CM);

void pingResult(uint8_t sensor, int cm) {  // Sensor got a ping, do something with the result.
  // The following code would be replaced with your code that does something with the ping result.
    if (cm < MAX_DISTANCE) {  
      digitalWrite(LED_1, HIGH);
     else {
        digitalWrite(LED_1, LOW);
  for (uint8_t i = 0; i < SONAR_NUM; i++) {
  Serial.print(" ");

The 15 sensor example sketch is more for advanced users that require a multi-tasking type script where multiple things will be happening at basically the same time.  Therefore, your use is well outside these parameters.

Instead, simply use the basic one sensor example sketch and add a second sensor.

Basically, you're trying to make it much more complicated than it needs to be, which is why you're having problems.

Now, if you had an already event driven sketch and you wanted to add two sensors while still keeping your sketch event-driven, then using the 15 sensor sketch would be appropriate.

56  Development / Other Software Development / Re: PWM frequency library on: April 15, 2013, 09:58:54 am
I discovered in a recent project involving an Arduino microcontroller that there was no method to change PWM frequency without directly manipulating low-level memory. As far as I can Google, there is no general purpose library that can change PWM frequencies on Arduino Microcontrollers. The internet is full of partial examples and code snippets for changing PWM frequency, but in the end I still had to consult the 400+ page sec sheet ( to get the code for my Mega functional.
It is my speculation that the programmers at Arduino have not released any methods for changing PWM frequency because it is difficult to write a simple and intuitive wrapper for hardware timers that wont run the risk of confusing a beginner (the whole draw to Arduino in the first place). The hardware is has very specific limitations that present themselves in odd ways. Allow me to share a few:

  • PWM behavior is determined by integrated components called timers. Every timer has two to four channels. Each channel is connected to a pin. Changing one pin's frequency requires changes to the timer it connects to. Which in turn changes the frequency of other pins connected to that same timer.
  • Timer 0 is usually used for Arduino's time keeping functions, (i.e. the millis() function). Changing the frequency on timer 0 will break the time keeping functions you may or may not be using in other parts of your project
  • There are two types of timer, 8bit and 16bit. Long story short, they have nuances that make common code difficult to implement without limiting one or the other.
  • Creating custom frequencies (beyond messing with the prescaler) with an 8bit timer requires the sacrifice of one channel. In other words, each 8bit timer that creates a custom frequency loses the ability to perform PWM on one pin (the one connected to the A channel to be more precise). All Arduinos except the Leonardo have two 8bit timers, meaning that setting all timers to a particular frequency will sacrifice a total of two pins on said Ardiuno.

Regardless of this, I still felt it would still be worth while to make a library/wrapper for hardware timers so that I, and anyone else who chooses to use this, will not have to spend quite as many hours needlessly digging through blocks of bug prone bit wise and preprocessor slurry.

The library has five global functions:
InitTimers()Initializes all timers. Needs to be called before changing the timers frequency or setting the duty on a pin
InitTimersSafe()Same as InitTimers() except timer 0 is not initialized in order to preserve time keeping functions
pwmWrite(uint8_t pin, uint8_t val)Same as 'analogWrite()', but it only works with initialized timers. Continue to use analogWrite() on uninitialized timers
SetPinFrequency(int8_t pin, int32_t frequency)Sets the pin's frequency (in Hz) and returns a bool for success
SetPinFrequencySafe(int8_t pin, int32_t frequency) Same as SetPinFrequency except it does not affect timer 0

The library also has five functions for each Timer 'object'. I could not get the code size down to what I felt was reasonable so I ditched C++ classes and did some fancy macro work instead. Each of these functions are technically preprocessor macros with nice self explanatory names that swap out for more cryptic functions inside the library header just before compile time. For timer 1 the functions are:

Timer1_GetFrequency()Gets the timer's frequency in Hz
Timer1_SetFrequency(int frequency)Sets the timer's frequency in Hz
Timer1_GetPrescaler()Gets the value (not bits) of the prescaler. Don't know what this means? Don't worry about it, just use SetFrequency(int frequency)
Timer1_SetPrescaler(enum value)Sets the prescaler*
Timer1_GetTop()Gets the timer register's maximum value
Timer1_SetTop(int top)Sets the timer register's maximum value
Timer1_Initialize()Initializes the timer
*The prescaler is inconsistent among different timers. I figured using enumerators was the best solution because most types of invalid input will be caught at compile time. For a normal timer, use one of these as a parameter: ps_1, ps_8, ps_64, ps_256, ps_1024. If those give a type error, then the timer you are using is one of the inconsistent ones, and you should use psalt_1, psalt_8, psalt_32, psalt_64, psalt_128, psalt_256, or psalt_1024 instead.

If you want to mess with a different timer, just change the number (i.e Timer2_GetFrequency() to get timer 2's frequency). It is up to your discretion whether or not you want to use the timer specific functions. The global ones should be good enough for most situations.

With this Library, 16bit timers have a frequency range from 1Hz to 2MHz. 8bit timers have a range from 31Hz to 2MHz. As the frequency becomes larger, the smaller the range power duties for a pin becomes. It is technically possible to push the frequency to 8MHz, but the range of possible power duties get stupidly small by that point. To be sure the frequency was correctly set, be sure to check the return value. If you don't want to sacrifice any 8bit PWM pins, don't call the initialize function for that timer, try changing the prescaler to manipulate frequency instead. There are many tutorials on how the prescaler affects timers and this library contains methods that make easier and less bug prone to manipulate. So far, I have tested this library on an Uno and a Mega. This library should be compatible with all Arduinos except the Leonardo and Due. If you have an Arduino that is not a Mega or Uno, please test it and tell me how it went. If somebody has an oscilloscope on hand to verify the frequencies being generated are correct, that would also be helpful.

For now, consider this library to be in beta. Developments on this library are described in later posts.
Here are some of the current features of this library:
  • Wraps timer specific properties (such as timer top and prescaler) with functions
  • Has pin based (timer agnostic) functions
  • Has functions for getting and setting frequency at the timer level and pin level
  • Has tools for measuring timer resolution at the timer level and pin level

The latest is version .05

There are technically libraries out there that allow you to set the PWM frequency.  They are, however, typically labeled as audio "tone" libraries.  It doesn't matter if the library is designed for audio, it's still just a PWM library.  I've written some of these libraries, some of which will output PWM signals at up to the megahertz range.

57  Development / Other Software Development / Re: NewTone Library - Plug-in replacement for Tone library - Better, smaller, faster on: April 15, 2013, 09:53:35 am
this could be awesome if the library was also Due compatible

I don't find the Due relevant, so I don't consider support for it.  Also, as NewTone uses port registers and direct timer calls, it doesn't really work well for the Due which is totally different than the ATmega.

58  Using Arduino / Sensors / Re: NewPing Library: HC-SR04, SRF05, SRF06, DYP-ME007, Parallax PING))) - v1.5 on: April 15, 2013, 09:17:12 am
Yes, I set the maximum distance at 300 but then the sensors return 0's. All the sensors are pointing at a solid wall 250cm away, but the sensors are returning 0's rather than seeing the wall, thus I'm assuming out of their range. I thought it strange as the Hr04's measured/worked fine over this distance. I've tried different delay times to see if there is any interference, up to 100ms but it makes no difference to the readings

Are you sending the sensor 5v?  Other than that, must just be your sensors.

59  Using Arduino / Sensors / Re: NewPing Library: HC-SR04, SRF05, SRF06, DYP-ME007, Parallax PING))) - v1.5 on: April 14, 2013, 11:16:07 pm
Hi Tim,

In the end I brought some Yourdunino SRF06's. They are accurate at their distance measurements but unfortunately their distance max's out at about 200cm, beyond that they return 0's. I was looking for something which would hopefully be accurate to about 350cm.... I have gone ahead and bought a few of Maxbotix XL EZ0 sensors. Do you think that I could modify your New Ping code to work with these sensors or would I need to start from scratch?

Did you set the maximum distance to higher than 200cm?  Mine work well to easily over 400cm.  Maybe it's the size of the object or how sonically reflective it is?  Try using a wall as your maximum distance measurements, that's what the distance specs use.

60  Development / Other Software Development / Re: NewTone Library - Plug-in replacement for Tone library - Better, smaller, faster on: April 11, 2013, 04:58:59 pm
Hi have been trying to adapt to use it on Timer "4" on the mega
As i can not use it on Timer 1 as it then conflicts width my PWM signals on the MEGA 2560  ;-(
I am trying to drive a speedometer
as you see i have just tryed to change the 1 to 4 not sure i know what i am doing
Any reply greatly appriciatet ;-)

I have changed here


#define TIMSK4 TIMSK //#define TIMSK1 TIMSK


ICR4    = top;                     // Set the top.
  if (TCNT4 > top) TCNT4 = top;      // Counter over the top, put within range.
  TCCR4B  = _BV(WGM40)  | prescaler; // Set PWM, phase and frequency corrected (ICR1) and prescaler.
  TCCR4A  = _BV(COM4B0);
  TIMSK4 |= _BV(OCIE4A);             // Activate the timer interrupt.

TIMSK4 &= ~_BV(OCIE4A);   // Remove the timer interrupt.
  TCCR4B  = _BV(CS40);      // Default clock prescaler of 8.
  TCCR4A  = _BV(WGM40);     // Set to defaults so PWM can work like normal (PWM, phase corrected, 8bit).

ISR(TIMER4_COMPA_vect) { // Timer interrupt vector.

It doesn't just conflict with the PWM signals, it replaces them.  It's by design.  Instead, why not just use PWM for timer 4 for whatever else you're doing?

One of the main purposes of NewTone is to use a different timer than the standard tone library.

In any case, I don't really know the ATmega2560 to know off the top of my head if there's any differences between timer 1 and timer 4.  Are they identical?  For example, if timer 4 doesn't have all the features of timer 1, it won't work.  It doesn't appear it's identical as it has 3 pins tied to timer 4 while timer 1 only has 2.

Without diving into the ATmega2560 technical documentation, I'll be hard-pressed to help.

Instead, I would suggest using my ToneAC library (there's an alternate version which uses timer 2).  It's superior to NewTone anyway and is already written to use timer 2 and can be assigned to any pins.

Pages: 1 2 3 [4] 5 6 ... 31