把uint16_t 十六位类型数据转化成uint8_t 八位数据类型数据的两种方法

本文介绍在STM32单片机操作中,如何将16位或32位传感器数据转换为8位数据,以便通过UART、I2C、USB等端口发送。提供了两种方法:使用指针和数组进行数据转换,便于初学者理解和应用。

        最近在STM32单片机操作中,常常需要通过UART,I2C,USB等端口发送各种传感器的数据,这些传感器寄存器大多是32位或者16位的。HAL库中发送函数都是8位指针结构,不能直接发送不同类型的数据,这就需要把不同长度及类型的数据转换成uint8_t 无符号8位整型。现总结两种方法,如下:

/********************************************************************
 * 测试程序 
 *
 * 数据存取实验--8位类型存取16位类型数据
 *
 * 输入16位,输出8位指针或数组。
 ********************************************************************/

static uint16_t Ui16ToUin8_P(uint16_t adata,uint8_t *bdata)
{
    //方法一:指针法
    //把一个16位数复制给一个8位的指针变量,这个8位指针变量的两个连续地址用
    //于存放16位数的高低位,输入16位,输出8位指针。
   

    *bdata = (uint8_t)(adata >>8 &0x0F); //前面(uint8_t)为强制类型转换
    *(bdata+1) = (uint8_t)(adata & 0x0F);

    return *bdata;
}

//---------------------------------------

static uint16_t Ui16ToUin8_R(uint16_t adata,uint8_t bdata[])
{
    //方法二:数组法
    //把一个16位数复制给一个8位的指针变量,这个8位指针变量的两个连续地址
    //用于存放16位数的高低位,输入16位,输出8位指针。
   

    bdata[0] = (uint8_t)(adata >>8 &0x0F); //前面(uint8_t)为强制类型转换
    bdata[1] = (uint8_t)(adata & 0x0F);

    return bdata[0];
}

 (本文的目的是方便初学者,欢迎探讨。)

 

/* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : main.c * @brief : Main program body ****************************************************************************** * @attention * * Copyright (c) 2025 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file * in the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "adc.h" #include "dma.h" #include "tim.h" #include "usart.h" #include "gpio.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "math.h" #include "string.h" #include "stdio.h" /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN PTD */ typedef enum{ key_zero=0,//按键没有按下时 key_press,//按键按下时 KEY_long,//长按 KEY_short//短按 }keystate; /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ float duty_IC=0.0f;//捕获占空比 float period_pwm=0.0f;//补货周期 uint8_t efficience=0;//有效序列号数量 uint8_t idx=0;//接收索引 uint8_t eff_num[128];//存储有效序列号 #define M_PI 3.14159265358979323846f // π #define M_PI_2 1.57079632679489661923f // π/2 /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); /* USER CODE BEGIN PFP */ float get_breath_period(void); void update_led_pwm(float period); uint8_t isreally(uint8_t num); void send_results(); /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ uint8_t x=0;//存储溢出的次数 uint8_t message[50]; #define Tolong 50//长按阙值 #define xiaodou 2//消抖阙值 uint32_t presstime=0; //uint16_t key_state=0; uint8_t clear_shake=0;//消抖 //AI进行添加 #define BRIGHTNESS_LEVELS 3 // 3级亮度 uint8_t brightness_level = 1; // 初始亮度等级 float phase_offsets[4] = {0, M_PI_2, M_PI, 3*M_PI_2}; // 四个LED的相差(90°) //AI进行添加 keystate key_state=key_zero; void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim){ if(htim==&htim2){ uint8_t key_current=HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_11); switch(key_state){ case key_zero: if(key_current==GPIO_PIN_SET){ clear_shake++; if(clear_shake>=xiaodou){ key_state=key_press; presstime=0; } } break; case key_press: if(key_current==GPIO_PIN_SET){ presstime++; if(presstime>Tolong){ key_state=KEY_long; } }else{ if(presstime<Tolong){ key_state=KEY_short; }else{ key_state=key_zero; } clear_shake=0; } break; case KEY_long: case KEY_short: break; } } if(htim==&htim3){ if(x!=0){ x++; } } } float get_breath_period(void){ uint32_t adc_value=0; static uint8_t adc_init=0; if(adc_init==0){ HAL_ADCEx_Calibration_Start(&hadc1); adc_init=1; } HAL_ADC_Start(&hadc1); if(HAL_ADC_PollForConversion(&hadc1,100)==HAL_OK){ adc_value=HAL_ADC_GetValue(&hadc1); } HAL_ADC_Stop(&hadc1); return 0.5f+(adc_value/4095.0f)*4.5f; } void update_led_pwm(float period){ static float t=0.0f; const float dt=0.01f; const float max_duty=0.9f; float bright_everytime=brightness_level/(float)BRIGHTNESS_LEVELS; for(int i=0;i<4;i++){ float sin_val=sinf(2.0f*M_PI*t/period+phase_offsets[i]); float duty=(sin_val+1.0f)/2.0f*max_duty*bright_everytime; if(duty<0.0f)duty=0.0f; if(duty>max_duty)duty=max_duty; switch(i){ case 0: __HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_1,(uint16_t)(duty*100)); break; case 1: __HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_2,(uint16_t)(duty*100)); break; case 2: __HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_3,(uint16_t)(duty*100)); break; case 3: __HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_4,(uint16_t)(duty*100)); break; } } t+=dt; if(t>period){ t-=period; } } char pwm_st[50];//存储PWM数值 void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size){ if(huart==&huart1){ uint16_t sum=0; if(message[0]==0xA5){ if(Size==5){ for(int i=0;i<Size-1;i++){ sum+=message[i]; } if(sum==message[4]){ uint8_t max_val = message[3]; // 目标值(如0x10) efficience=0; for(int i=0;i<max_val;i++){ if(isreally(i)){ eff_num[efficience++]=i; } } if(message[1]==0x20&&message[2]==0x25){//升序 for(uint8_t i=0;i<efficience;i++){ for(uint8_t j=i+1;j<efficience;j++){ if(eff_num[i]>eff_num[j]){ uint8_t every_st=eff_num[i]; eff_num[i]=eff_num[j]; eff_num[j]=every_st; } } } }else if(message[1]==0x20&&message[2]==0x26){//降序 for(uint8_t i=0;i<efficience;i++){ for(uint8_t j=i+1;j<efficience;j++){ if(eff_num[i]<eff_num[j]){ uint8_t every_st=eff_num[i]; eff_num[i]=eff_num[j]; eff_num[j]=every_st; } } } } send_results(); } } } if(message[0]==0x20&&message[1]==0x23&&message[2]==0x00&&Size==3){ sprintf(pwm_st,"PWM={%fms,%.2f}",period_pwm,duty_IC); HAL_UART_Transmit_DMA(&huart1,(uint8_t*)pwm_st,strlen(pwm_st)); } HAL_UARTEx_ReceiveToIdle_DMA(&huart1,message,sizeof(message)); __HAL_DMA_DISABLE_IT(&hdma_usart1_rx,DMA_IT_HT); } } //计算占空比 uint32_t rise1=0; uint32_t rise2=0; uint32_t low=0; //计算占空比 volatile uint32_t diff_high=0;//存放高差值 volatile uint32_t diff_two=0;//存放高低差值 volatile uint8_t power=0;//捕获指示,0表示没有捕获,1表示捕获已完成一次 volatile uint8_t finsh=0;//捕获标志0未1完 void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim){ if(htim->Instance==TIM3&&htim->Channel==HAL_TIM_ACTIVE_CHANNEL_1){ uint32_t current=HAL_TIM_ReadCapturedValue(&htim3,TIM_CHANNEL_1); switch(power){ case 0: rise1=current; x=0; __HAL_TIM_SET_CAPTUREPOLARITY(htim, TIM_CHANNEL_1, TIM_INPUTCHANNELPOLARITY_FALLING); power=1; break; case 1: low=current; if(low>rise1){ diff_two=low-rise1; }else{ diff_two=65536*x+low-rise1; } __HAL_TIM_SET_CAPTUREPOLARITY(htim,TIM_CHANNEL_1,TIM_INPUTCHANNELPOLARITY_RISING); power=2; break; case 2: rise2=current; if(rise2>rise1){ diff_high=rise2-rise1; }else{ diff_high=x*65536+rise2-rise1; } if(diff_high!=0){ duty_IC=(float)diff_two/diff_high*100;//占空比 } power=0; finsh=1; break; } } } //检验序列是否有效 uint8_t isreally(uint8_t num){ uint8_t cnt=0; for(int i=0;i<8;i++){ if(num&(1<<i)){ cnt++; } } return (cnt%2==0)&&(cnt>0); } //发送数据 void send_results(){ char tx_wait[50]; char tx_total[50]; for(int x=0;x<efficience;x++){ for(int a=0;a<8;a++){ tx_wait[a]=eff_num[x]& (1 << (7 - a)) ? '1' : '0'; } tx_wait[8]='\0'; //tx_wait[9]='\n'; HAL_UART_Transmit_DMA(&huart1,(uint8_t*)tx_wait,8); } sprintf(tx_total,"total:%d",efficience); HAL_UART_Transmit_DMA(&huart1,(uint8_t*)tx_total,strlen(tx_total)); } /* USER CODE END 0 */ /** * @brief The application entry point. * @retval int */ int main(void) { /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* MCU Configuration--------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals */ MX_GPIO_Init(); MX_DMA_Init(); MX_TIM2_Init(); MX_USART1_UART_Init(); MX_TIM3_Init(); MX_ADC1_Init(); /* USER CODE BEGIN 2 */ HAL_TIM_Base_Start_IT(&htim2); HAL_TIM_PWM_Start(&htim2,TIM_CHANNEL_1); HAL_TIM_PWM_Start(&htim2,TIM_CHANNEL_2); HAL_TIM_PWM_Start(&htim2,TIM_CHANNEL_3); HAL_TIM_PWM_Start(&htim2,TIM_CHANNEL_4); HAL_TIM_IC_Start_IT(&htim3,TIM_CHANNEL_1); HAL_UARTEx_ReceiveToIdle_DMA(&huart1,message,sizeof(message)); __HAL_DMA_DISABLE_IT(&hdma_usart1_rx,DMA_IT_HT); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { switch (key_state) { case KEY_short: // 短按→亮度等级循环递增(1→2→3→1) brightness_level = (brightness_level % BRIGHTNESS_LEVELS) + 1; key_state = key_zero; // 处理完成后重置状态 break; case KEY_long: // 长按→亮度等级循环递减(3→2→1→3) brightness_level = (brightness_level == 1) ? BRIGHTNESS_LEVELS : brightness_level - 1; key_state = key_zero; // 处理完成后重置状态 break; default: // 空闲/其他状态→不处理 break; } if(finsh==1){ period_pwm=diff_high*0.1f;//周期,单:ms } float period = get_breath_period(); // 读取电器,调整周期 update_led_pwm(period); // 更新LED的PWM占空比 HAL_Delay(10); // 控制循环频率 /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; RCC_PeriphCLKInitTypeDef PeriphClkInit = {0}; /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9; 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_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { Error_Handler(); } PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC; PeriphClkInit.AdcClockSelection = RCC_ADCPCLK2_DIV6; if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK) { Error_Handler(); } } /* USER CODE BEGIN 4 */ /* USER CODE END 4 */ /** * @brief This function is executed in case of error occurrence. * @retval None */ void Error_Handler(void) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ __disable_irq(); while (1) { } /* USER CODE END Error_Handler_Debug */ } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t *file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /* USE_FULL_ASSERT */ 当我发送A5 20 25 10 FA时只能收到一个八位二进制数据0000 0011,正确应该收到7个有效数据,并带上总数7,问题出在哪
最新发布
11-09
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值