I have a real noob question about variable overflow.
I'm writing a function to generate sinusoidal output via PWM. In my function, I have an 32-element array containing sinusoidal PWM duty cycle values, and I wish to move through the values of that array when the function is called. When I get to the 31th element of the array, I want to start over at the 0th element--the array values are 'circular'.
The way I'm doing this is that I have unsigned byte variable "index". I increment that by 1 when the function is called, and then copy the (index % N)th array element to the PWM output compare register. I believe that my index variable can overflow without any problem. The modulo will work correctly and everything, even through the overflow from 255 to 0.
I'm not sure exactly what happens going the other way, however. When I decrement my index variable, eventually I'm going to get down to 0. When I decrement it again, does it "underflow" back to 255? And in this case, is the modulo operator going to work the "expected" way?
I have a feeling it will and everything will be alright, but I don't really know. I can use a signed variable, if that is necessary.
I could write a test program on a computer, I guess. If I try to write a test program on the microcontroller, it's very hard to debug or confirm that it's working (I don't have a simulator or debugger).
I don't have serial capabilities in my application.
I wrote this on the PC though, which seems to indicate it will work
#include <stdio.h>
int main(){
unsigned char index;
for (int i =0;i<257;i++){
printf("index %d\n", index);
printf("index mod32 %d\n", index%32);
index ++;
}
for (int i =0;i<257;i++){
printf("index %d\n", index);
printf("index mod32 %d\n", index%32);
index --;
}
}
index mod32 28
index 253
index mod32 29
index 254
index mod32 30
index 255
index mod32 31
index 0
index mod32 0
index 1
index mod32 1
index 0
index mod32 0
index 255
index mod32 31
index 254
index mod32 30
index 253
index mod32 29
index 252
OK, sure you can program using the ISP header. But without making an attempt to bring out the Tx pin to a serial-to-usb converter you are working with your hands tied behind your back. Basically your debugging will be "does it work perfectly? or not?".
With serial prints you can check stuff (like your original question). You can see if code is entered and how often. You can see if it resets unexpectedly. You can see what numbers (where relevant) are coming into your analog port.
There are other debugging methods. I describe one here:
If you have the I2C pins free (or free for another device) you can send I2C debugging out to a second Arduino (or Atmega or whatever) and get your debugging via that.