RYMCU

分享一个可以手写的随机函数

ronger 3 月前
# 随机函数

所属作品集

rand.c

/*-------------------------------------------------------------------------
   rand.c - random number generator

   Copyright (C) 2017, Philipp Klaus Krause, pkk@spth.de

   This library is free software; you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published by the
   Free Software Foundation; either version 2, or (at your option) any
   later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this library; see the file COPYING. If not, write to the
   Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston,
   MA 02110-1301, USA.

   As a special exception, if you link this library with other files,
   some of which are compiled with SDCC, to produce an executable,
   this library does not by itself cause the resulting executable to
   be covered by the GNU General Public License. This exception does
   not however invalidate any other reasons why the executable file
   might be covered by the GNU General Public License.

   This is an xorshift PRNG. See George Marsaglia, "Xorshift RNGs" for details.
   The width of 32 bits was chosen to not regress in period length vs. the
   PRNG from the C standard, while at the same time minimizing RAM usage.
   The parameters a, b, c were chosen to allow the generation of efficient code.
-------------------------------------------------------------------------*/
#define RAND_MAX    0x7FFF

static unsigned s = 0x80000001;

int rand(void) {
    register unsigned long t = s;

    t ^= t >> 10;
    t ^= t << 9;
    t ^= t >> 25;

    s = t;

    return (t & RAND_MAX);
}

void srand(unsigned int seed) {
    s = seed | 0x80000000; /* s shall not become 0 */
}

在单片机中使用,可以通过定时器来获取一个随机的 seed

#include "stdbool.h"
#include "STC89xx.h"
#include "compiler.h"
#include "lint.h"

// 单片机晶振频率
#define FOSC 11059200
// 定时器初始值计算
#define T_1ms (65536 - FOSC/12/1000)
#define _KEY 0x90

SBIT(KEY0, _KEY, 0);
unsigned int count = 0;
int number = 0;

int main() {
    // 设置定时模式为模式1
    TMOD = 0x01;
    // 设置初始值
    TL0 = T_1ms;
    TH0 = T_1ms >> 8;
    // 启动定时器
    TR0 = 1;
    // 中断相关
    ET0 = 1;
    EA = 1;
    while (1) {}
}

void timer0() __interrupt(1) {
    TL0 = T_1ms;
    TH0 = T_1ms >> 8;
    count++;
    // 按下按键时,生成随机数,保证获取到的 count 是变化的
    if (KEY0 == 0) {
        srand(count);
	// 获取 1 - 100 的随机数
        number = rand() % 100 + 1;
    }
    // 这里的数字 1000 无特殊含义,可自行修改
    if (count >= 1000) {
        count = 0;
    }
}

所属作品集

后发布评论