controller-pcba/User/driver/DAC8568.c

97 lines
2.2 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "DAC8568.h"
#include "stm32f4xx_hal.h" // 添加HAL库头文件
#include "main.h"
#include "user_spi.h"
#include <stdint.h> // 添加标准整型定义
#define DAC_MAX_VALUE 65535
/**
* @brief DAC8568通用写函数
* @param cmd 命令类型0-初始化内部参考电压1-写入并更新DAC值
* @param channel 通道号(0-7)仅在cmd=1时有效
* @param value DAC值(0-65535)或命令值根据cmd决定
* @return void
*/
void DAC8568_Write(uint8_t cmd, uint8_t channel, uint32_t value)
{
uint8_t tx_data[4];
uint8_t rx_data[4] = {0}; // Initialize receive buffer
uint32_t send_data;
// 根据命令类型准备发送数据
if(cmd == 0) // 初始化内部参考电压
{
send_data = DAC8568_EN_INTER_REF_STATIC;
}
else // 写入并更新DAC值
{
// 输入参数合法性检查
if(channel > 7)
{
channel = 7;
}
if(value > DAC_MAX_VALUE)
{
value = DAC_MAX_VALUE;
}
send_data = DAC8568_WRITE_UPDATE_SEL_DAC;
send_data |= (channel << 20);
send_data |= (value << 4);
}
// 准备发送数据
tx_data[0] = (uint8_t)(send_data >> 24);
tx_data[1] = (uint8_t)(send_data >> 16);
tx_data[2] = (uint8_t)(send_data >> 8);
tx_data[3] = (uint8_t)(send_data & 0xFF);
// 开始SPI传输
DAC8568_CS_L; // 拉低CS使能SPI接口
extern SPI_HandleTypeDef hspi3; // 声明外部SPI句柄
spi_transmit_receive(&hspi3, tx_data, rx_data, 4); // 使用hspi3发送4字节数据
DAC8568_CS_H; // 拉高CS禁止SPI接口
}
/**
* @brief 初始化DAC8568芯片
* @return void
*/
void DAC8568_Init(void)
{
//初始化GPIO和SPI
dac8568_spi_init();
// 将LDAC置低DAC8568处于同步模式
DAC8568_LD_L;
// 初始化内部参考电压
DAC8568_Write(0, 0, 0);
}
/**
* @brief 设置DAC8568指定通道的电压值
* @param mCh 通道号(0-7)
* @param mVol 电压值(0-2.5V)
* @return void
*/
void dac8568_set_voltage(unsigned char mCh, float mVol)
{
float mDatafloat;
uint16_t mDtashort;
// 将电压值转换为DAC值
mDatafloat = mVol * (65536/(5*1.91));
mDtashort = (uint16_t)mDatafloat;
mDtashort &= 0xffff;
// 限制DAC值范围
if(mDtashort > 65535)
mDtashort = 65535;
// 写入并更新DAC值
DAC8568_Write(1, mCh, mDtashort);
}