0

我创建了用于操作驱动 1602 LCD 端口的函数。

  #include "delay.h"
    #include <stdint.h>
    #include "stm32f0xx.h"
    
    #ifndef LCD1602A_H_
    #define LCD1602A_H_
    #define DATA_PORT GPIOA
    #define CONTROL_PORT GPIOA
    //Set pins
    #define RS  6
    #define RW  7
    #define E   9
    #define D4  10
    #define D5  0
    #define D6  1
    #define D7  2    
    void send_8_bit_command(unsigned char command){     
        
            union DATA{
                struct {
                    unsigned char Bit0:1;
                    unsigned char Bit1:1;
                    unsigned char Bit2:1;
     

            unsigned char Bit3:1;
                unsigned char Bit4:1;
                unsigned char Bit5:1;
                unsigned char Bit6:1;
                unsigned char Bit7:1;
            }Bits;
            unsigned char input;
        }data;
        data.input=command;
        GPIOA->BSRR|=1<<(16+RS);
        GPIOA->BSRR|=1<<(16+RW);
    
        GPIOA->BSRR|=1<<(16+D7);
        GPIOA->BSRR|=1<<(16+D6);
        GPIOA->BSRR|=1<<(16+D5);
        GPIOA->BSRR|=1<<(16+D4);
        GPIOA->BSRR|=1<<(E);
        Delay_us(1);
        if(data.Bits.Bit7==1){GPIOA->BSRR|=1<<(D7);}else{GPIOA->BSRR|=1<<(16+D7);}
        if(data.Bits.Bit6==1){GPIOA->BSRR|=1<<(D6);}else{GPIOA->BSRR|=1<<(16+D6);}
        if(data.Bits.Bit5==1){GPIOA->BSRR|=1<<(D5);}else{GPIOA->BSRR|=1<<(16+D5);}
        if(data.Bits.Bit4==1){GPIOA->BSRR|=1<<(D4);}else{GPIOA->BSRR|=1<<(16+D4);}
        GPIOA->BSRR|=1<<(16+E);
        Delay_us(1);
    
        GPIOA->BSRR|=1<<(16+D7);
        GPIOA->BSRR|=1<<(16+D6);
        GPIOA->BSRR|=1<<(16+D5);
        GPIOA->BSRR|=1<<(16+D4);
        GPIOA->BSRR|=1<<(E);
        Delay_us(1);
        if(data.Bits.Bit3==1){GPIOA->BSRR|=1<<(D7);}else{GPIOA->BSRR|=1<<(16+D7);}
        if(data.Bits.Bit2==1){GPIOA->BSRR|=1<<(D6);}else{GPIOA->BSRR|=1<<(16+D6);}
        if(data.Bits.Bit1==1){GPIOA->BSRR|=1<<(D5);}else{GPIOA->BSRR|=1<<(16+D5);}
        if(data.Bits.Bit0==1){GPIOA->BSRR|=1<<(D4);}else{GPIOA->BSRR|=1<<(16+D4);}
        GPIOA->BSRR|=1<<(16+E);
        Delay_us(1);
    }

但是在 main() 中,当第二次使用这个函数时,程序崩溃了,并且在调试模式下,所有的电阻都变成了“目标不可用”。我使用联合来访问输入字符值的片段。使用后是否需要清除或销毁联合,否则会在作用域结束时销毁?为什么第二次 send_8_bit_command 函数会导致程序挂起?

send_8_bit_command(0x20);
send_8_bit_command(0xE);//This line program collapsed.
4

1 回答 1

0

我通过使用两个函数之间的延迟来修复它:

send_8_bit_command(0x20);
delay_us(10);
send_8_bit_command(0xE);//Program live again!
于 2021-11-29T05:10:37.453 回答