Electronic – avr microcontrollers and how to get started coding init or main loop or timers or interrupts


I have been modifying AVR and PIC microcontroller code for a few years now for work but have never written anything from scratch, I understand it pretty well.

I am starting to write my own code now and am having trouble getting started. I was wondering how other people start writing code and if there is a book or tutorial people would recommend on this.

Do you start with coding your initialization function then interrupts then timers then the main while(1) loop… I am wondering what the best way to get started is.

Thank you

Best Answer

  1. The first thing one does in any microcontroller project is blink an LED; keep it blinking and give it a name ("Blinky"), too. It's the heart beat of your widget, and will always work so long as your program doesn't get stuck.
  2. Commit to the local version control repository.
  3. Next is to fly through the entire program in pseudo/crapcode, based on your program flow diagrams or whatever planning methods you've subscribed to. If something doesn't work or you just don't like it, comment it out but keep it there so you know to fix it later. If you don't know how to do something, write down what it's supposed to do in comments.
  4. Commit to the local version control repository.
  5. Time to fill in the blanks! Implement one function at a time, for example the timer, and test it. Your program should always compile and work as expected. I like to implement any user interface connections at this point, like UART -> RS232 -> PC links or LCD displays. Don't forget about Blinky.
  6. Commit to the local version control repository.
  7. Try to break your code with rigorous test routines; debug. Have others review your code; debug. Run your widget through its design parameters regularly, like temperature variations; debug.
  8. Commit to the local version control repository.
  9. Disconnect Blinky if you're a heartless fool, and ship.

AVRFreaks has an excellent tutorial written by Dean Camera (aka. abcminuser) called Modularizing C Code: Managing large projects. You may also be interested in reading State Machines for Microprocessors by James Wagner.