volatile uint16_t sample;
...
if (sample >= sinewave_length) { sample = -1;
How does an unsigned number become -1?