【问题标题】:Blinking 3 LEDs using PIC 18F4550使用 PIC 18F4550 闪烁 3 个 LED
【发布时间】:2016-09-17 15:38:23
【问题描述】:

我正在尝试使用 C、MPLAB X(IDE 和 IPE)和 PICKit 3 开始使用 PIC 18F4550。 我已经设法让一个 LED 闪烁而没有任何问题,但是当我尝试同时闪烁多个 LED 时,它不起作用。

请注意,我将在问题末尾发布我的完整代码。在那之前,我将编写伪代码,希望能让我的问题更清楚一点。

假设我要闪烁 4 个 LED,每个 LED 都连接到芯片的一个输出引脚,你显然会输入类似

loop{
     output1 = 1;
     output2 = 1;
     output3 = 1;
     output4 = 1;
     delay();
     output1 = 0;
     output2 = 0;
     output3 = 0;
     output4 = 0;
     delay();
}

您会期望所有 LED 会同时打开和关闭。但是,我注意到只有连接到 output4 的 LED 会闪烁,其余的将保持关闭状态。 所以我尝试翻转输出引脚的顺序

 loop{
         output1 = 1;
         output2 = 1;
         output4 = 1;
         output3 = 1;
         delay();
         output1 = 0;
         output2 = 0;
         output4 = 0;
         output3 = 0;
         delay();
    }

因此,只有连接到输出 3 的 LED 会闪烁,其余的将保持关闭状态。

所以我想,不知何故,代码并没有像我预期的那样按顺序执行。 谁能给我一个解释和可能的解决方案?

非常感谢!

这是完整的代码

#include <xc.h>
#include <p18f4450.h>
#pragma config FOSC = HS

#define outRed  PORTBbits.RB0
#define outBlue PORTBbits.RB1
#define outYellow PORTBbits.RB2
#define outGreen PORTBbits.RB3
#define _XTAL_FREQ 10000000

void delay(unsigned int);



void main(void) {
    TRISBbits.TRISB0 = 0;
    TRISBbits.TRISB1 = 0;
    TRISBbits.TRISB2 = 0;
    TRISBbits.TRISB3 = 0;

    while(1) {
        outRed = 1;
        outGreen = 1;
        outBlue = 1;
        outYellow = 1;
        delay(1000);   
        outRed = 0;
        outGreen = 0;
        outBlue = 0;
        outYellow = 0;
        delay(1000);
    }        

}

void delay(unsigned int delayInput) {
    unsigned int mul = delayInput/50;
    unsigned int count = 0;
    for (count = 0; count <= mul; count ++)
        __delay_ms(50);
}

【问题讨论】:

    标签: c embedded pic microchip mplab


    【解决方案1】:

    这可能是 LATCH 问题。我启动时遇到过几次这个问题。尝试写入 LATB(输出锁存器)寄存器而不是 PORTB 寄存器。我总是使用 LATx 作为输出,使用 PORTx 作为输入。

    【讨论】:

    • 这对我来说效果很好!非常感谢!但是,这个问题有原因吗?在 PIC 的架构中?我的意思是为什么会发生这种情况?
    • PORTx 从数字输入缓冲器读取,而 LATx 写入输出锁存器。在某些情况下,数字输入缓冲器不会看到您尝试使用 LATx 寄存器输出的电压(例如,如果任何引脚设置为模拟输入,它们将读取为 0)。再加上位操作是通过 8 位读取=>修改=>写入来实现的,您的 PORTx 结果可能会令人惊讶。附: PIC18F4550 的一些引脚可以使用 ADCON1 寄存器配置为模拟或数字输入。
    【解决方案2】:

    始终写入输出锁存器(在您的情况下为 LATB)并从 PORTx 读取输入。写入 PORTx 具有不可预测的行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多