找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 2996|回复: 2
收起左侧

STM32利用ADC噪声产生随机数源程序

[复制链接]
ID:582899 发表于 2019-8-26 18:49 | 显示全部楼层 |阅读模式
rand_number.c

#include "rand_number.h"
#include "adc.h"
#include "stdlib.h"

/***************/
//使用ADC噪声产生随机数种子
//min,max------------>随机数范围
//Rand_Value    ADC的电压值
int32_t get_rand(int16_t min ,int16_t max)
{
    uint16_t Rand_Value[4];
    int16_t rand_temp;
    uint8_t i=0;
    HAL_ADC_Start_DMA(&hadc1, (uint32_t*)&Rand_Value, 4);
    while(1)if(i++>20)break;
    rand_temp = (Rand_Value[0] & 0xf)<<12 | (Rand_Value[1] & 0xf)<<8 | (Rand_Value[2] & 0xf)<<4 | (Rand_Value[3] & 0xf);
    srand(rand_temp);
    rand_temp = rand()% max + min;
    HAL_ADC_Stop_DMA(&hadc1);
    return rand_temp;
}


rand_number.h

#ifndef __RAND_NUMBER_H
#define __RAND_NUMBER_H
#define USED_103 1

#if USED_103
  #include "stm32f1xx_hal.h"
#else
  #include "stm32f4xx_hal.h"
#endif

int32_t get_rand(int16_t min ,int16_t max);

#endif  
     
ADC噪声随机数.PNG




回复

使用道具 举报

ID:721019 发表于 2020-4-2 15:35 | 显示全部楼层
楼主,返回值应该写成 return ((rand() % (max - min))+min),你那样还是会有超范围的可能。
回复

使用道具 举报

ID:721019 发表于 2020-4-2 15:37 | 显示全部楼层
楼主,返回值应该是 return ((rand() % (max - min)) + min);
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|小黑屋|51黑电子论坛 |51黑电子论坛6群 QQ 管理员QQ:125739409;技术交流QQ群281945664

Powered by 单片机教程网

快速回复 返回顶部 返回列表