在以上代码中,我们定义了一个mystruct结构体,其中有三个函数指针作为结构体成员,然后定义了一个结构体指针,通过指针来调用各个函数。
现在我们把这种方法应用到单片机编程中,实现对LCD1602各个功能函数的打包。- /*目的:练习使用结构体封装函数,然后使用结构体指针来控制LCD
- 1. 定义一个结构体
- 2. 定义一个结构体变量
- 3. 定义几个函数
- 4. 定义结构体指针
- 5. LCD控制引脚,初始化,在哪里显示,显示什么
- */
- #include "reg52.h"
- typedef unsigned char uchar;
- sbit RS=P2^7;
- sbit EN=P2^6;
- struct mystruct {
- void (*LCD_init)(void);
- void (*write_data)(uchar);
- void (*write_string)(uchar *);
- void (*write_com)(uchar);
- void (*delay)(uchar);
- };
- void LCD_init(void);
- void delayUs(uchar t);
- void delayMs(uchar t);
- void write_com(uchar mycmd);
- void write_data(uchar mydata);
- void write_string(uchar *p);
- struct mystruct LCD_struct;
- struct mystruct *LCD;
- void main(void)
- {
- struct mystruct LCD_struct={
- LCD_init,
- write_data,
- write_string,
- write_com,
- delayMs,
- };
- while(1)
- {
- LCD=&LCD_struct;
- LCD->LCD_init();
- LCD->write_com(0x80);
- LCD->write_string("This is struct");
- while(1);
- }
- }
- void LCD_init(void)
- {
- delayMs(15);
- write_com(0x38);
- delayMs(5);
- write_com(0x38);
- write_com(0x08);
- write_com(0x01);
- write_com(0x06);
- write_com(0x0c);
- }
- void write_data(uchar mydata)
- {
- delayMs(5);//注意这里需要延时5ms比较保险
- P0=mydata;
- RS=1;
- EN=1;
- delayUs(5);
- EN=0;
- }
- void write_string(uchar *p) //如何写一个字符串
- {
- while(*p)
- {
- write_data(*p);
- p++;
- }
- }
- void write_com(uchar mycmd)
- {
- delayMs(5);//注意这里需要延时5ms比较保险 代替判断忙信号
- P0=mycmd; //准备好指令
- RS=0; //告诉LCD1602,P0中放的是指令不是数据
- EN=1;
- delayUs(5); //根据时序图,脉冲要有一定宽度
- EN=0; //使指令有效,开始执行
- }
- void delayUs(uchar t)
- {
- while(--t);
- }
- void delayMs(uchar t)
- {
- while(--t)
- {
- delayUs(245);
- delayUs(245);
- }
- }
|