yl2006443 发表于 2012-3-4 10:58:18

关于代码中两个TMOD的问题

我写了一个程序,用51单片机,用定时器方式产生PWM波形,同时用串口方式改变占空比,问题来了,在初始化中,都有对TMOD赋予初始值,可是我即使让TMOD成为同一个数,最后的程序, 还是不对,串口发送数据接收不到,请大家指教该如何处理呢?

beck_ck 发表于 2012-3-4 13:02:22

贴出程序看一下

millwood0 发表于 2012-3-5 04:16:46

first of all, you should learn to ask good questions.

2ndly, it will depend on how your code.

3rd, generally, you should try to preseve the portion of TMOD that your code doesn't touch. For example, if your pwm uses just TMR0, you should set up TMOD this way:

#define TMR_MODE00x00//tmr mode0
#define TMR_MODE10x01//tmr mode1
#define TMR_MODE20x02//tmr mode2
#define TMR_MODE30x03//tmr mode3
#define TMR_GATED0x08//tmr dated
#define TMR_COUNTER 0x04 //tmr as counter
#define TMR_TIMER0x00//tmr as timer

void tmr0_init(unsigned char mode) {
TR0 = 0;//stop the timer
TMOD = (TMOD & 0xf0) | (mode & ~0xf0);
//you may wish to initialize the tmr/counters now
TR0 = 1;//start the timer
}

so in your code, you set tmr0 accordingly:

tmr0_init(TMR_TIMER | TMR_MODE1); //set tmr0 as timer, not gated and in mode1

millwood0 发表于 2012-3-5 08:16:11

to continue:

the code to reset tmr1 would be something like this:


void tmr1_init(unsigned char mode) {
TR1 = 0;//stop the timer
TMOD = (TMOD & 0x0f) | ((mode & 0x0f) << 4);
//you may wish to initialize the tmr/counters now
TR1 = 1;//start the timer
}

so in your code, you set tmr1 similarly:

tmr1_init(TMR_COUNTER | TMR_MODE1); //set tmr1 as a counter, not gated and in mode 1

the beauty of this is that if you ever need to swap the assignment of tmr0/tmr1 (tmr0 for counter and tmr1 for timer),

all you need to do is to call different routines

//tmr0 as counter, not gated, mode 1
tmr0_init(TMR_COUNTER | TMR_MODE1);

//tmr1 as timer, gated, mode 1
tmr1_init(TMR_TIMER | TMR_GATED | TMR_MODE1);

the key to embedded programming is to minimize your touch points with the actual hardware. a very counter-intuitive point for many embedded programmers.
页: [1]
查看完整版本: 关于代码中两个TMOD的问题