stm32f103zet6 写ad9959的代码
时间: 2023-07-10 19:37:00 浏览: 214
AD9959的stm32驱动
为了驱动AD9959芯片,我们需要使用STM32的SPI接口。
以下是一个简单的示例代码,用于将频率设置为10MHz:
```c
#include "stm32f10x.h"
#define AD9959_CS_PIN GPIO_Pin_4
#define AD9959_CS_PORT GPIOA
void AD9959_Init(void);
void AD9959_SetFreq(uint32_t freq);
int main(void)
{
AD9959_Init();
AD9959_SetFreq(10000000); // 10MHz
while (1);
}
void AD9959_Init(void)
{
// 初始化SPI接口
RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
SPI_InitTypeDef SPI_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_7; // SCK, MOSI
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = AD9959_CS_PIN; // CS
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(AD9959_CS_PORT, &GPIO_InitStructure);
SPI_InitStructure.SPI_Direction = SPI_Direction_1Line_Tx;
SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
SPI_InitStructure.SPI_DataSize = SPI_DataSize_16b;
SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;
SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;
SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_2;
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
SPI_InitStructure.SPI_CRCPolynomial = 7;
SPI_Init(SPI1, &SPI_InitStructure);
SPI_Cmd(SPI1, ENABLE);
GPIO_SetBits(AD9959_CS_PORT, AD9959_CS_PIN);
}
void AD9959_SetFreq(uint32_t freq)
{
uint32_t fsys = 50000000; // STM32时钟频率为50MHz
uint32_t delta = (uint32_t)(((double)freq / (double)fsys) * 4294967296.0);
uint16_t data0 = (delta & 0xFFFF);
uint16_t data1 = ((delta >> 16) & 0xFFFF);
GPIO_ResetBits(AD9959_CS_PORT, AD9959_CS_PIN);
SPI_I2S_SendData(SPI1, 0x2100); // 写频率控制寄存器
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_BSY) != RESET);
SPI_I2S_SendData(SPI1, data0);
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_BSY) != RESET);
SPI_I2S_SendData(SPI1, data1);
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_BSY) != RESET);
GPIO_SetBits(AD9959_CS_PORT, AD9959_CS_PIN);
}
```
需要注意的是,这只是一个简单的示例代码,仅演示了如何设置频率。如果需要驱动AD9959芯片的其他功能(如幅度控制、相位控制等),还需要编写相应的代码。
阅读全文