gpt4 book ai didi

c - 我如何在 C 中创建一个真正的随机数 (IDE : MPLAB)

转载 作者:太空宇宙 更新时间:2023-11-03 23:39:08 25 4
gpt4 key购买 nike

我正在 PIC18F2550 上制作游戏,我需要创建一个介于 1 和 4 之间的随机数。我已经发现 rand() 函数对于真正的随机数很糟糕。我试过 srand(time(NULL)),这是主文件

#include <time.h>
#include <stdlib.h>
#include <stdio.h>
void main(void) {
srand(time(NULL));
init();
while(timed_to_1ms()) {
fsm_game();
}
}

这是fsm_game.c文件

void randomSpawn(int time2) {
if(counter%time2==0) {
int x = rand()%4 +1; // Makes number between 1 and 4
}
}

当我尝试构建它时,我收到一条错误消息:

“:0:错误:(499) undefined symbol : _time(dist/default/production\Dontcrash.production.obj) "

我认为问题可能在于微处理器不“知道时间”,所以如果是这样的话,我能做些什么来解决这个问题?

最佳答案

要初始化随机数生成器,您可以使用 PIC 的 ADC 读取 float 引脚上的电压,并使用 srand() 设置种子。 .

此外,您可以在每次程序启动时将种子保存到 EEPROM,并从 EEPROM 中读取之前的种子值,将其与 ADC 值结合起来,以减少事情的可预测性。 - 我认为这对于游戏来说已经足够好了,否则我想那太粗糙了。

unsigned int seed = read_seed_from_adc();
seed ^= read_seed_from_eeprom(); /* use something else than XOR here */
srand(seed);
write_seed_to_eeprom(seed);

I think the problem may be in the fact that a microProcessor doesn't 'know the time', so if that's the case, what can I do to solve this problem?

时间通常是用微 Controller 上的RTC来测量的,所以RTC是否可以使用取决于你的硬件(RTC通常需要一个 quartz 谐振器和一个备用电池来保持它一直运行,一些微 Controller 使用外部实时时钟)。由于微 Controller 上通常只使用一个小型 C 库,time()通常不可用,您需要自己读取 RTC 寄存器。 - 它也可以用于初始化 PRNG。

关于c - 我如何在 C 中创建一个真正的随机数 (IDE : MPLAB),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50298845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com