找回密碼
 立即注冊(cè)

QQ登錄

只需一步,快速開(kāi)始

搜索
查看: 3111|回復(fù): 2
打印 上一主題 下一主題
收起左側(cè)

STM32利用ADC噪聲產(chǎn)生隨機(jī)數(shù)源程序

[復(fù)制鏈接]
跳轉(zhuǎn)到指定樓層
樓主
rand_number.c

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

/***************/
//使用ADC噪聲產(chǎn)生隨機(jī)數(shù)種子
//min,max------------>隨機(jī)數(shù)范圍
//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  
     





分享到:  QQ好友和群QQ好友和群 QQ空間QQ空間 騰訊微博騰訊微博 騰訊朋友騰訊朋友
收藏收藏1 分享淘帖 頂 踩
回復(fù)

使用道具 舉報(bào)

沙發(fā)
ID:721019 發(fā)表于 2020-4-2 15:35 | 只看該作者
樓主,返回值應(yīng)該寫(xiě)成 return ((rand() % (max - min))+min),你那樣還是會(huì)有超范圍的可能。
回復(fù)

使用道具 舉報(bào)

板凳
ID:721019 發(fā)表于 2020-4-2 15:37 | 只看該作者
樓主,返回值應(yīng)該是 return ((rand() % (max - min)) + min);
回復(fù)

使用道具 舉報(bào)

本版積分規(guī)則

小黑屋|51黑電子論壇 |51黑電子論壇6群 QQ 管理員QQ:125739409;技術(shù)交流QQ群281945664

Powered by 單片機(jī)教程網(wǎng)

快速回復(fù) 返回頂部 返回列表