#include "main.h" #include "gw_grayscale_sensor.h" #define GW_GRAY_ADDR GW_GRAY_ADDR_DEF I2C_HandleTypeDef hi2c1; void SystemClock_Config(void); static void MX_I2C1_Init(void); int main(void) { int ret_transmit, ret_receive; uint8_t recv_value = 0; uint8_t i2c_cmd; uint8_t send_buff[2]; uint8_t sensor_arr[8]; uint8_t channel_en_flag; HAL_Init(); SystemClock_Config(); MX_I2C1_Init(); /* 只要中间2个探头数据(4,5号) */ channel_en_flag = GW_GRAY_ANALOG_CH_EN_4 | GW_GRAY_ANALOG_CH_EN_5; // = 0b00011000 ret_transmit = HAL_I2C_Mem_Write(&hi2c1, GW_GRAY_ADDR << 1, GW_GRAY_ANALOG_CHANNEL_ENABLE, 1, &channel_en_flag, 1, 100); if (ret_transmit != HAL_OK) Error_Handler(); // i2c 错误 /* 打开模拟数据模式 */ i2c_cmd = GW_GRAY_ANALOG_MODE; ret_transmit = HAL_I2C_Master_Transmit(&hi2c1, GW_GRAY_ADDR << 1, &i2c_cmd, 1, 100); if (ret_transmit != HAL_OK) Error_Handler(); // i2c 错误 while (1) { ret_receive = HAL_I2C_Master_Receive(&hi2c1, GW_GRAY_ADDR << 1, sensor_arr, 2, 100); if (ret_receive) { Error_Handler(); //i2c 错误 } // sensor_arr[0] 为 探头4数据 // sensor_arr[1] 为 探头5数据 } } /** * @brief 时钟配置 */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /** Initializes the CPU, AHB and APB buses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK) { Error_Handler(); } } /** * @brief I2C初始化 */ static void MX_I2C1_Init(void) { /* 主设备设置 */ hi2c1.Instance = I2C1; /* i2c通道 */ hi2c1.Init.ClockSpeed = 100000; hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2; /* i2c 占空比=50% 1:1, I2C_DUTYCYCLE_16_9 用于快速i2c模式 */ /* 从设备设置(不用管) */ hi2c1.Init.OwnAddress1 = 0; hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT; hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE; hi2c1.Init.OwnAddress2 = 0; hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE; hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE; /* 是否初始化成功 */ if (HAL_I2C_Init(&hi2c1) != HAL_OK) { Error_Handler(); } } /* 出错啦 */ void Error_Handler(void) { __disable_irq(); while (1) { } }