Reputation: 4733
Microcontroller : ATmega328P in Arduino Uno
Clock Frequency : 16MHz
void timeDelay_CTC(float sec, unsigned char times)
{
unsigned char cycles = (unsigned char)(sec / 0.000064f);
OCR1A = cycles - 1;
TCCR1A = 0b00000000;
TCCR1B = 0b00001101;
for( unsigned char i = 1; i <= times; i++ )
{
while( (TIFR1 & (1<<OCF1A)) == 0 );
TIFR1 |= (1<<OCF1A);
}
TCCR1A = 0;
TCCR1B = 0;
}
The function is used for calculating the number of time delay cycles and then implement it.
int main(void)
{
//Initialization
LED1_DDR |= (1<<LED1_BIT);
LED1_PORT |= (1<<LED1_BIT);
//Start
while(1)
{
LED1_PORT ^= (1<<LED1_BIT);
timeDelay_CTC(1, 1);
}
}
However, when running the code above, the LED light does not toggle. If I just type OCR1A = 15624;
(the number of cycles for 1s), it works well. Therefore, the problem should come from the calculation of unsigned char cycles = (unsigned char)(sec / 0.000064f);
I think that the data type conversion may be wrong. Can you teach me how to make it work? Or give me some hints.
Upvotes: 0
Views: 262
Reputation: 100
Please check the range of unsigned char, it is [0 255], it is not big enough for your application. Try to use unsigned int.
Upvotes: 3