|
发表于 2013-8-8 19:03:55
|
显示全部楼层
Writing a modular code base is not just to make it more readable, but also to make it re-usable for your next job.
The following is an example:
- //#include <avr/io.h> //we use gcc-avr
- #include <regx51.h> //we use keil c51
- #include "gpio.h"
- //#include "delay.h"
- #include "tmr0.h" //we use hardware tmr
- //hardware configuration
- #define P1_PORT P2
- #define P2_DDR P2
- #define P1_OUT (1<<0) //pulse 1 output pin
- #define P1_PR (TMR_20ms + TMR_5ms) //p1's period
- #define P1_TMR TMR_5ms //tmr interrupts every 5ms
- #define P1_WIDTH() {NOP();} //p1's pulse width
- //end hardware configuration
- //reset the pins
- void p1_init(void) {
- IO_CLR(P1_PORT, P1_OUT); //idles low
- IO_OUT(P1_DDR, P1_OUT); //pin as output
- }
- //output a pulse
- void p1_out(void) {
- static unsigned char p1_count=0; //counter
- p1_count+=1;
- if (p1_count>=(P1_PR / P1_TMR)) { //50ms has been reached
- p1_count -= (P1_PR / P1_TMR); //update p1_count
- //output 12 pulses, 50% dc, with duration P1_WIDTH()
- //each pulse takes (2 + 1) * 2 us, at 12Mhz crystal, 12:1 prescaler
- IO_SET(P1_PORT, P1_OUT); P1_WIDTH(); IO_CLR(P1_PORT, P1_OUT); P1_WIDTH();
- IO_SET(P1_PORT, P1_OUT); P1_WIDTH(); IO_CLR(P1_PORT, P1_OUT); P1_WIDTH();
- IO_SET(P1_PORT, P1_OUT); P1_WIDTH(); IO_CLR(P1_PORT, P1_OUT); P1_WIDTH();
- IO_SET(P1_PORT, P1_OUT); P1_WIDTH(); IO_CLR(P1_PORT, P1_OUT); P1_WIDTH();
- IO_SET(P1_PORT, P1_OUT); P1_WIDTH(); IO_CLR(P1_PORT, P1_OUT); P1_WIDTH();
- IO_SET(P1_PORT, P1_OUT); P1_WIDTH(); IO_CLR(P1_PORT, P1_OUT); P1_WIDTH();
- IO_SET(P1_PORT, P1_OUT); P1_WIDTH(); IO_CLR(P1_PORT, P1_OUT); P1_WIDTH();
- IO_SET(P1_PORT, P1_OUT); P1_WIDTH(); IO_CLR(P1_PORT, P1_OUT); P1_WIDTH();
- IO_SET(P1_PORT, P1_OUT); P1_WIDTH(); IO_CLR(P1_PORT, P1_OUT); P1_WIDTH();
- IO_SET(P1_PORT, P1_OUT); P1_WIDTH(); IO_CLR(P1_PORT, P1_OUT); P1_WIDTH();
- IO_SET(P1_PORT, P1_OUT); P1_WIDTH(); IO_CLR(P1_PORT, P1_OUT); P1_WIDTH();
- IO_SET(P1_PORT, P1_OUT); P1_WIDTH(); IO_CLR(P1_PORT, P1_OUT); P1_WIDTH();
- }
- }
- void mcu_init(void) {
- }
- int main(void) {
- mcu_init(); //reset the mcu
- p1_init(); //reset the pins
- tmr0_init(1, TMR_5ms); //5ms per interrupt
- tmr0_act(p1_out); //install handler
- ei();
- while (1) {
- }
- }
复制代码 It is a piece of code that I wrote to generate a series of short pulses every 25ms. It was originally written for an avr, utilizing tmr0. I simply copy-and-paste the avr code, made a few minor changes, and then plug in the corresponding C51 timer modules and then code now runs on 89C51.
The way those modules are coded allows me to reuse the code base, with confidence that they would work for a new chip - because I have debug'd and tested them before and they share the same interface.
That is really the beauty of writing modular / portable code.
|
|