gpt4 book ai didi

c - ATMega 随机数生成

转载 作者:行者123 更新时间:2023-11-30 17:03:20 24 4
gpt4 key购买 nike

在某些情况下,我正在为 Arduino 项目开发基本上是“Simon”的东西。我正在使用 ATMEGA2560 并使用 Atmel Studio 6.1 编辑代码。该项目使用随机数生成器来创建按钮输入的序列,这就是我遇到麻烦的地方。

我当前添加一些方差的方法是使用计时器中断来播种随机数,方法是增加要通过方程处理的数字。然而,计时器根本不起作用——而且数字也不会增加。我在初始化时做错了什么,还是有其他问题?

代码:

#define F_CPU 1000000UL  // 1 MHz, for timer

#include <avr/io.h> // normal stuff
#include <avr/interrupt.h> // timer interrupt
#include <util/delay.h> // easy delay functions
#include <stdlib.h> // random function

// global var that timer uses
volatile uint8_t count;

// function prototypes
int generateSeq(); // generates random number
int getRandomNumber(); // also generates random number (?)



int main(void)
{

// variables
int sequence[8] = {0, 0, 0, 0, 0, 0, 0, 0}; // actual sequence
int terms = 0; // terms in sequence
int gameState = 0;
int ifWrong = 0; // if sequence is wrong


// timer interrupt (WHAT AM I DOING WRONG)
TCCR0A |= (1<<CS02)|(1<<CS00);
TIMSK0 |= (1<<TOIE0);
TCNT0 = 0;
count = 1;
sei();

while(1)
{
// actual "game" part
while(gameState == 1)
{

// generate term in sequence
// 1 = up, 2 = right, 3 = down, 4 = left

if(ifWrong == 0)
{
sequence[terms] = generateSeq(); // call sequence function
terms++;
}
}
}
}

// random seed for sequence generator (something wrong here?)
ISR(TIMER0_OVF_vect)
{
count++;

if(count >= 255)
{
count = 1;
}
}

int generateSeq() // function to generate sequence
{
// equation is currently a placeholder
int r2 = (int)rand() * (int)count;
int num = r2 * count;
return (num % 4) + 1;
}

最佳答案

gameState 为 0,并且从未改变,因此不会调用任何 generateSeq() 代码。

您还遇到了 sequence[terms] 的严重问题,因为您没有检查 terms 是否在 0 到 7 之间。您将超出数组。

关于c - ATMega 随机数生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36230918/

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