ds3231.h

#include "main.h"                        //不同的cubemx版本生成的不一样,自己看着调用
#include "stm32l0xx_hal.h"   
#define DS3231_WriteAddress 0xD0         //器件写入地址
#define DS3231_ReadAddress  0xD1         //器件读取地址
#define DS3231_SECOND       0x00         //秒地址
#define DS3231_MINUTE       0x01         //分地址
#define DS3231_HOUR         0x02         //时地址
#define DS3231_WEEK         0x03         //周地址
#define DS3231_DAY          0x04         //天地址
#define DS3231_MONTH        0x05         //月地址
#define DS3231_YEAR         0x06         //年地址    
extern I2C_HandleTypeDef hi2c1;         //硬件IIc 1

ds3231.c

#include "ds3231.h"       
struct time
{
    char year;
    char mon;
    char day;
    char hour;
    char min;
    char sec;
}now;//保存当前时间的结构体    
//由于器件里的是8421码所以需要转换一下
//读出来的是8421需要转成16进制
//变量写进去要转成8421写进去
char BCD2HEX(char val)//8421转16进制    
{
     char temp;
     temp=val&0x0f;
     val>>=4;
     val&=0x0f;
     val*=10;
     temp+=val;    
     return temp;
}
char HEX2BCD(char val)//16进制转8421    
{
     char i,j,k;
     i=val/10;
     j=val%10;
     k=j|(i<<4);
     return k;
}    
uint8_t AD_ReadData(uint16_t Addr, uint8_t Reg)//硬件iic读取数据,器件地址,读取地址
{
    HAL_StatusTypeDef status = HAL_OK;
    uint8_t value = 0;
    status = HAL_I2C_Mem_Read(&hi2c1, Addr, Reg, I2C_MEMADD_SIZE_8BIT, &value, 1, 100);
    if(status != HAL_OK)
    {
    }
    return value;
}    
void get_time()//循环调用,读取时间到结构体
{
    now.year=BCD2HEX(AD_ReadData(DS3231_ReadAddress,DS3231_YEAR));
    now.mon=BCD2HEX(AD_ReadData(DS3231_ReadAddress,DS3231_MONTH));
    now.day=BCD2HEX(AD_ReadData(DS3231_ReadAddress,DS3231_DAY));
    now.hour=BCD2HEX(AD_ReadData(DS3231_ReadAddress,DS3231_HOUR));
    now.min=BCD2HEX(AD_ReadData(DS3231_ReadAddress,DS3231_MINUTE));
    now.sec=BCD2HEX(AD_ReadData(DS3231_ReadAddress,DS3231_SECOND));
}
void Writetime(char add,char time)//修改时间,修改地址,
{    
uint8_t *pData;    
time=HEX2BCD(time);    
pData=&time;    
HAL_I2C_Mem_Write(&hi2c1,DS3231_WriteAddress,add,I2C_MEMADD_SIZE_8BIT,pData,1,100);
}
最后修改:2020 年 06 月 28 日 03 : 49 PM
声明:无闻风博客|版权所有,违者必究|如未注明,均为原创| 转载:转载请注明原文链接