/*
8位数码管模块，MAX7219驱动
Flash moving ...
A website may be useful as https://xantorohara.github.io/led-matrix-editor/
Board: STC32G12K128
Author: Jin-Lei Li
Email: lijinlei0907@163.com
Date: Jan. 24, 2024
*/

#include <STC32G.h>
#include <intrins.h>

#define MAIN_Fosc 35000000UL		//定义主频35MHz

typedef unsigned char u8;
typedef unsigned int u16;
typedef unsigned long int u32;

/*-------------- Define MAX7219 IO ----------------*/
sbit Max7219_pinCLK = P2^2;
sbit Max7219_pinCS  = P2^1;
sbit Max7219_pinDIN = P2^0;

void Delay_xms(u16 ms);
void Init_MAX7219(void);
void Write_Max7219(u8 address,u8 dat);
void Write_Max7219_byte(u8 DATA);

/*-------------- Main Program ----------------------*/
void main(void)
{
	EAXFR = 1;				//使能XFR访问
	CKCON = 0x00;			//设置外部数据总线速度最快
	WTST = 0x00;			//设置程序读取等待时间为0个时钟，CPU执行程序速度最快
	
	P0M1 = 0x00;P0M0 = 0x00;		//设置P0口为准双向口模式 00：准双向口 01：推挽输出 10：高阻输入 11：开漏输出
	P1M1 = 0x00;P1M0 = 0x00;		//设置P1口为准双向口模式 00：准双向口 01：推挽输出 10：高阻输入 11：开漏输出
	P2M1 = 0x00;P2M0 = 0x00;		//设置P2口为准双向口模式 00：准双向口 01：推挽输出 10：高阻输入 11：开漏输出
	
	Delay_xms(50);
	Init_MAX7219();
	Delay_xms(2000);
	Write_Max7219(0x0f, 0x00);  //显示测试：1；测试结束，正常显示：0
	Write_Max7219(1,8); // the first Bit segment -> the corresponding Number
	Write_Max7219(2,7);
	Write_Max7219(3,6);
	Write_Max7219(4,5); 
	Write_Max7219(5,4);
	Write_Max7219(6,3);
	Write_Max7219(7,2);
	Write_Max7219(8,1);
	while(1);
}
/*-------------------------------------------
功能：向MAX7219写入数据
入口参数：address、dat
出口参数：无
---------------------------------------------*/
void Write_Max7219(u8 address,u8 dat)
{
	Max7219_pinCS = 0;
	Write_Max7219_byte(address);           //写入地址，即数码管编号
	Write_Max7219_byte(dat);               //写入数据，即数码管显示数字 
	Max7219_pinCS = 1;                        
}

void Init_MAX7219(void)
{
	Write_Max7219(0x09, 0xff);       //译码方式：BCD码
	Write_Max7219(0x0a, 0x02);       //亮度 0x01~0x07
	Write_Max7219(0x0b, 0x07);       //扫描界限；8个数码管显示
	Write_Max7219(0x0c, 0x01);       //掉电模式：0，普通模式：1
	Write_Max7219(0x0f, 0x00);       //显示测试：1；测试结束，正常显示：0
}
/*--------------------------------------------
功能：向MAX7219(U3)写入字节
入口参数：DATA 
出口参数：无
---------------------------------------------*/
void Write_Max7219_byte(u8 DATA)
{
	u8 i;    
	Max7219_pinCS=0;		
	for(i=8;i>=1;i--)
  {
		Max7219_pinCLK = 0;
    Max7219_pinDIN = DATA&0x80;
    DATA = DATA << 1;
    Max7219_pinCLK = 1;
  }                                 
}
/*-------------- Time Delay -----------------*/
void Delay_xms(u16 ms)
{
	u16 i;
	do
	{
		i = MAIN_Fosc / 6000;
		while(--i);
	}
	while(--ms);
}