Try this:
Code:
unsigned int button_counter;
void main(void) {
Init();
button_counter = 0;
while (1) {
if (PORTCbits.RC0 == 0)
blink_led(++button_counter);
}
}
void blink_led(unsigned int blink_count) {
unsigned int i = 0;
while (i < blink_count) {
LATCbits.LATC1 = !LATCbits.LATC1;
Wait();
LATCbits.LATC1 = !LATCbits.LATC1;
Wait();
++i;
}
}
- - - Updated - - -
but my coach told me that we cannot use for loop, only if statement can be used. Because the program is for pic, not for PC. It's different. what do you think about it?
Your coach may be right and wrong.
Whether or not you can use a for loop is not limited by the PIC in terms of hardware, but rather the compiler. A for loop is a while loop just doing variable declaration, variable assignment, loop test condition and variable incrementation all on one line. This is high level programming language specific (such as C) and how the compiler reads it. There is no special assembly command required for a for loop.
All code is converted to assembly by the compiler. The compiler picks the best instructions available for the target processor. If your processor does not have a multiply instructions is uses a ton of additions to complete the operation. Which is why some processors are faster than others, they have a better instruction set which allows them to accomplish more in fewer cycles/time.
So your coach is wrong that you cannot run a for loop on a PIC, but may be right that the compiler does not allow it. I don't remember of the top of my head. I remember there being something funny about it when I first started using PIC18s. Then again Microchip just changed compilers so they may have fixed it. I have just always done the old while loop.
One thought is that you have to declare your variables at the top of the function because of C. So maybe it wants this:
int i;
void main (void) {
for (i= 0; i < 12; ++i) {
// code
}
}
Instead of this:
void main (void) {
for (int i= 0; i < 12; ++i) {
// code
}
}
Hope this helped.
- - - Updated - - -
Change this:
To:
That will fix your code but I would use my code from earlier or something like it. The reason for this is buttonPress*2 will get to big.