Debugging C, the Mega32, and the STK500
General C "features"
- When xyzzy is a variable, the following syntax using = instead of ==:
if (xyzzy=0){stuff};
is completely legal and will never enter the if-block because the variable is first assigned the value zero, then checked to see if it is not-zero.
- The operators ! (logical not) and ~ (bitwise not) are not equivalent.
Let's say we have the char variable xyzzy=1. The syntax:
if (~xyzzy){stuff};
will always enter the if-block because ~1 for a char variable is 0xFE, which is non-zero.
- C does not protect you from yourself!
- You can overrun array boundaries at run time (no bounds checks).
- You can force C to storevariables in fixed RAM locations, then overwrite them at compile time.
- If you store an int to a char, it may overwrite the next byte in memory.
- If variables seem to be changing on their own, o rinserting debug variables seems to 'fix' the problem, you probably have a memory issue. Check the compiler-generated .map file. Look for zero-based versus one-based array errors.
- Also see Common C errors.
You load a program and nothing happens.
- Master interrupt bit set? If your code depends on a timer for scheduling tasks, it will appear dead if the I-bit is 0.
- If your task clock is timer0 and timer1 is set to interrupt on match, and timer1 is set to clear on match, and OCR1A is zero, then
timer0 will never take an interrupt. Timer 1 takes an interrupt on every cycle.
- Did your code exit main? Codevision lets you do this even though there is no code running after you leave main, unless you are running the debugger.
- Did you turn on ANY interrupt enable and not supply the ISR? Codevision simply generates a default reset if you don't write an ISR.
- Start inserting printf (or blink some LEDs) to see where the code stalls.
STK500 does not program:
- Does the board have a crystal?
- Are all the jumpers in place as shown in lab0?
- Do you have PORTB connected to anything? If so, disconnect.
- If the error message is "Failure to program flash error"
- From the main Codevision window: Choose menu Tools...Chip Programmer.
- In the resulting dialog box:
- set cpu clock to 1 MHz
- uncheck all fuse bits
- choose menu Program...Fuse Bits
- set cpu clock back to 16 MHz
- close chip programmer dialog box
- The normal make/program dialog should now work.
- In the folder C:\programFiles\atmel\AVRtools\STK500 you will find the utility "upgrade.exe". This file reflashes the PROGRAMMER on the STK500. To do this: Turn off the STK500, hold down the "program" switch and turn it on. Run the utility and follow directions.
- The last step is to swap out the cpu. Have the TA help you.