I am writing a delay function for Arduino to be used in a project. The reason is that TIMER0 (the default timer used for Arduino delay) is occupied with PWM control. The test code for the delay function is as follows:
int count;
unsigned long int sec;
void delay_ms (uint16_t millisecond) {
sec = ((16000000/12)/1000)*millisecond;
for (count = 0; count < sec; count ++);
}
void setup (){
Serial.begin(9600);
}
void loop (){
Serial.println('a');
delay_ms(1000);
Serial.println('b');
delay_ms(1000);
}
This setup simply prints a and b with a 1-second delay between each. It's working properly but before that there were other setups I used that did not work. The changes are:
- Declaring count as an unsigned long => This led to the delay function working properly but only for the first time.
- Declaring and intializing count as an int in the initialization step of the for loop => The delay function does not work as intended, at all.
Based on the knowledge provided by Arduino Reference on Unsigned Long and Int, I'd thought that they are essentially the same in this case. Therefore, I'd like to get some clarification in terms of how the data is processed by the loop as well as the delay function.