arduino is making wrong calculations

hi, my I have developed a module for my eurorack that generates clock impulses. To see how it works, here is a video of me explaining it : Arduino clock generator
but one line of the code is making a lot of trouble. interval0 = reverseDelay * (100 - swing); - when swing is 50 than everything is ok, but when it changes to anything else the calculations go to negative.

Here is the whole code but the part that is not working is in void bpmTick

I CANT POST THE CODE so it will be as an attachment

arduino_clock_generator.ino (38.4 KB)

You're probably doing 16 bit "int" arithmetic.
A 16 bit signed int can store -32768 to 32767
Change to 32 bit "long" variables

I'm sorry, I can't see your code on my phone

Most likely, the value of reverseDelay * (100 - swing) is exceeding 32767, so the integer result overflows.

  • when swing is 50 than everything is ok, but when it changes to anything else the calculations go to negative.

Isn't that what you told it to do?

if(swing == 50) interval1 = interval0;
    else interval1 = interval0 * -1;

What specifically do you mean by "the calculations"?

line 55 in your code - int interval0;
line 217 in your code - reverseDelay = 60000 / bpm;

Calculations are fine, code is wrong.