STM32 产生随机数方式
C语言的stdlib.h库里的srand(unsigned seed)和rand(void)函数,可以配合产生伪随机数。其中srand(seed)产生算法种子,再由rand()通过算法产生随机数,产生的随机数在宏定义RAND_MAX范围内。如果seed不变,则产生的随机数不变。
这里介绍STM32 HAL库环境的随机数产生代码,采用STM32CUBEIDE开发环境,以STM32F103C6T6为例,通过USB虚拟串口将归一化随机数打印出,归一化随机数为0~1之间的浮点值。顺便这里将STM32指令微秒延时函数PY_Delay_us_t(us);的基本参数usDelayBase的测定值打印出。STM32微秒延时函数参考: STM32 HAL us delay(微秒延时)的指令延时实现方式及优化 。
这里介绍的方法,不依赖于硬件产生随机数的方式,因此也可以用于STM8和其它厂家的各种MCU产生随机数。
STM32工程配置
首先建立基本工程并设置时钟,这里只用到USB接口用于打印输出:
设置USB虚拟串口:
保存并生成初始工程文件:
STM32随机数生成代码
随机数种子seed的选择,在计算机应用领域,可以采用系统时间作为种子,而在嵌入式方面,因为STM32 HAL有不断运行的毫秒计数值uwTick,因此可选作随机数种子。uwTick是递增形态,为了加强随机性,还可以将uwTick进行一次CRC32计算得到32位验证码,然后用此验证码作为随机数种子。STM32的硬件和软件CRC32计算,参考 C语言CRC-32 STM32格式校验函数,硬件CRC32可以加快随机数产生速度,而软件CRC32则具有通用型,一些型号MCU并不具有硬件CRC32计算组件。
采用空间节约的编译方式,参考 STM32 region `FLASH‘ overflowed by xxx bytes 问题解决
USB虚拟串口的使用,参考 STM32 USB VCOM和HID的区别,配置及Echo功能实现(HAL)
采用的浮点转字符函数py_f2s4printf(),参考 STM32 UART串口printf函数应用及浮点打印代码空间节省 (HAL)
主要功能代码实现部分如下:
if(USB_CONN_STATUS())
{
py_f2s4printf(fchar, usDelayBase, 8);
sprintf(console, "usDelayBase for STM32F103 in 72MHz is %s\r\n", fchar);
CDC_Transmit_FS((uint8_t*)console, strlen(console)) ;
seed = uwTick;
srand((unsigned)PY_CRC_32_T32_STM32(&seed, 1));
rn = ((float)rand())/RAND_MAX;
py_f2s4printf(fchar, rn, 8);
sprintf(console, "Random number is %s\r\n\r\n", fchar);
CDC_Transmit_FS((uint8_t*)console, strlen(console)) ;
}
包含主要功能代码的完整的main.c文件:
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* Copyright (c) 2023 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 "usb_device.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "string.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
__IO float usDelayBase;
void PY_usDelayTest(void)
{
__IO uint32_t firstms, secondms;
__IO uint32_t counter = 0;
firstms = HAL_GetTick()+1;
secondms = firstms+1;
while(uwTick!=firstms) ;
while(uwTick!=secondms) counter++;
usDelayBase = ((float)counter)/1000;
}
void PY_Delay_us_t(uint32_t Delay)
{
__IO uint32_t delayReg;
__IO uint32_t usNum = (uint32_t)(Delay*usDelayBase);
delayReg = 0;
while(delayReg!=usNum) delayReg++;
}
void PY_usDelayOptimize(void)
{
__IO uint32_t firstms, secondms;
__IO float coe = 1.0;
firstms = HAL_GetTick();
PY_Delay_us_t(1000000) ;
secondms = HAL_GetTick();
coe = ((float)1000)/(secondms-firstms);
usDelayBase = coe*usDelayBase;
}
void PY_Delay_us(uint32_t Delay)
{
__IO uint32_t delayReg;
__IO uint32_t msNum = Delay/1000;
__IO uint32_t usNum = (uint32_t)((Delay%1000)*usDelayBase);
if(msNum>0) HAL_Delay(msNum);
delayReg = 0;
while(delayReg!=usNum) delayReg++;
}
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
uint32_t PY_CRC_32_T32_STM32(uint32_t *di, uint32_t len)
{
uint32_t crc_poly = 0x04C11DB7; //X^32+X^26+X^23+X^22+X^16+X^12+X^11+X^10+X^8+X^7+X^5+X^4+X^2+X^1+1 total 32 effective bits without X^32.
//uint32_t data_t = 0; //CRC register
uint32_t data_t = 0xffffffff; //CRC register
for(uint32_t i = 0; i < len; i++)
{
data_t ^= di[i]; //32-bit data
for (uint8_t j = 0; j < 32; j++)
{
if (data_t & 0x80000000)
data_t = (data_t << 1) ^ crc_poly;
else
data_t <<= 1;
}
}
return (data_t);
}
uint32_t seed;
/* 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);
static void MX_GPIO_Init(void);
/* USER CODE BEGIN PFP */
/*
*Convert float to string type
*Written by Pegasus Yu in 2022
*stra: string address as mychar from char mychar[];
*float: float input like 12.345
*flen: fraction length as 3 for 12.345
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
void py_f2s4printf(char * stra, float x, uint8_t flen)
{
uint32_t base;
int64_t dn;
char mc[32];
base = pow(10,flen);
dn = x*base;
sprintf(stra, "%d.", (int)(dn/base));
dn = abs(dn);
if(dn%base==0)
{
for(uint8_t j=1;j<=flen;j++)
{
stra = strcat(stra, "0");
}
return;
}
else
{
if(flen==1){
sprintf(mc, "%d", (int)(dn%base));
stra = strcat(stra, mc);
return;
}
for(uint8_t j=1;j<flen;j++)
{
if((dn%base)<pow(10,j))
{
for(uint8_t k=1;k<=(flen-j);k++)
{
stra = strcat(stra, "0");
}
sprintf(mc, "%d", (int)(dn%base));
stra = strcat(stra, mc);
return;
}
}
sprintf(mc, "%d", (int)(dn%base));
stra = strcat(stra, mc);
return;
}
}
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
char fchar[16];
char console[256];
float rn;
/* 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_USB_DEVICE_Init();
/* USER CODE BEGIN 2 */
PY_usDelayTest();
PY_usDelayOptimize();
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
if(USB_CONN_STATUS())
{
py_f2s4printf(fchar, usDelayBase, 8);
sprintf(console, "usDelayBase for STM32F103 in 72MHz is %s\r\n", fchar);
CDC_Transmit_FS((uint8_t*)console, strlen(console)) ;
seed = uwTick;
srand((unsigned)PY_CRC_32_T32_STM32(&seed, 1));
rn = ((float)rand())/RAND_MAX;
py_f2s4printf(fchar, rn, 8);
sprintf(console, "Random number is %s\r\n\r\n", fchar);
CDC_Transmit_FS((uint8_t*)console, strlen(console)) ;
}
PY_Delay_us_t(500000);
/* 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_USB;
PeriphClkInit.UsbClockSelection = RCC_USBCLKSOURCE_PLL_DIV1_5;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOD_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
}
/* 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 */
代码测试效果
版本下载后,通过USB连接虚拟串口,测试效果如下:
例程下载
–End–