#include "main.h"
#include"MAX6675.h"
extern SPI_HandleTypeDef hspi2;
// ------------------- Functions ----------------
uint8_t MAX6675_ReadWriteByte(uint8_t txData)
{
unsigned char txdata,rxdata;
txdata = txData;
HAL_SPI_TransmitReceive(&hspi2,&txdata,&rxdata,1,1000);
return rxdata;
}
/**
* @brief max6675模块读取测得的原始数据
* @param None
* @retval 温度的原始数据
*/
uint16_t MAX6675_ReadRawValue(void)
{
uint16_t tmp=0;
HAL_GPIO_WritePin(GPIOB, GPIO_PIN_12, GPIO_PIN_RESET);;
tmp = MAX6675_ReadWriteByte(0XFF); //read MSB
tmp <<= 8;
tmp |= MAX6675_ReadWriteByte(0XFF); //read LSB
HAL_GPIO_WritePin(GPIOB, GPIO_PIN_12, GPIO_PIN_SET);
if (tmp & 0x04)
{
// thermocouple open
tmp = 4095; //未检测到热电偶
}
else
{
tmp<<=1;//去掉D15位
tmp>>=4;//去掉D0、1、2位
}
return tmp;
}
/**
* @brief max6675模块读取温度
* @param None
* @retval 温度值(单位:℃)
*/
float MAX6675_ReadTemperature(void)
{
return (MAX6675_ReadRawValue() *0.25);
}
// 初始化USART2,波特率为115200bps
void USART2_Init(void)
{
RCC->APB1ENR1 |= RCC_APB1ENR1_USART2EN; // 使能USART2时钟
// 配置GPIOA的PA2、PA3管脚为USART2的TX、RX功能
GPIOA->MODER &= ~(GPIO_MODER_MODE2 | GPIO_MODER_MODE3);
GPIOA->MODER |= (GPIO_MODER_MODE2_1 | GPIO_MODER_MODE3_1);
GPIOA->AFR[0] |= (7U << GPIO_AFRL_AFSEL2_Pos) | (7U << GPIO_AFRL_AFSEL3_Pos);
// 配置USART2,波特率为115200bps
USART2->BRR = SystemCoreClock / 115200;
USART2->CR1 |= USART_CR1_TE_Msk | USART_CR1_RE_Msk |
USART_CR1_RXNEIE_Msk | USART_CR1_UE_Msk;
}
// 发送字符串到USART2
void USART2_SendString(char *str)
{
while (*str)
{
while (!(USART2->ISR & USART_ISR_TXE_Msk));
USART2->TDR = *str++;
}
}
void HAL_SPI_MspInit(SPI_HandleTypeDef* hspi)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
if(hspi->Instance==SPI2)
{
/* USER CODE BEGIN SPI2_MspInit 0 */
/* USER CODE END SPI2_MspInit 0 */
/* Peripheral clock enable */
__HAL_RCC_SPI2_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
/**SPI2 GPIO Configuration
PB13 ------> SPI2_SCK
PB14 ------> SPI2_MISO
*/
GPIO_InitStruct.Pin = GPIO_PIN_13|GPIO_PIN_14;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF5_SPI2;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
}
}
while (1){
/* Write NDEF to EEPROM */
K_Temperature=MAX6675_ReadTemperature(); //读取热电偶温度值
sprintf(str, "Temperature: %.2f\r\n", K_Temperature);
USART2_SendString(str);
// 延时一段时间
HAL_Delay(1000);
}
|