我正在尝试为基本骰子模拟器程序编写代码。当按下开关时,两个七段显示将在1-6之间快速变化。释放按钮后,随机数将显示在两个七段显示屏上。
此代码将连接到ISIS中的pic16F877,我正在使用MPLAB进行C编程。
我对这些编程工作真的很陌生,所以我很难理解它。
#include <pic.h>
const char patterns[]={0X3F, 0X06, 0X5B, 0x4F, 0X66, 0X6D, 0X7D}
char rand_num1=0;
char rand_num2=0;
void main(void)
{
TRISB=0x00;
TRISC=0x01;
TRISD=0x00;
for(;;)
{
if(RCO==0)
{
rand_num1=rand()%6+1;
rand_num2=rand()%6+1;
}
if (RC0==1)
{
const char patterns[];
}
}
}
答案 0 :(得分:0)
让我稍微澄清一下我的评论:
首先,您无需致电rand()
。用户将按下按钮一段时间(精度为10或20纳秒,这是微控制器的合理时钟)。这个间隔,并且给定精度可能比调用rand()
更随机。因此,您可以拥有一个计数器(即最多256个)并从此计数器中获取两个随机数。在代码中,这将是:
int counter = 0;
int lo_chunk, hi_chunk;
if(RCO == 0) { // assuming that RCO == 0 means the button is pressed
counter = (counter + 1) % 256; // keep one byte out of the int
// we'll use that byte two get 2 4-bit
// chunks that we'll use as our randoms
lo_chunk = (counter & 0xF) % 6; // keep 4 LSBits and mod them by 6
hi_chunk = ((counter >> 4) & 0xF) % 6; // shift to get next 4 bits and mod them by 6
// Now this part is tricky.
// since you want to display the numbers in the 7seg display, I am assuming
// that you will need to write the respective patterns "somewhere"
// (either a memory address or output pins). You'll need to check the
// documentation of your board on this. I'll just outline them as
// "existing functions"
write_first_7segment(patterns[lo_chunk]);
write_second_7segment(patterns[hi_chunk]);
} else if(RCO == 1) { // assuming that this means "key released"
rand_num1 = lo_chunk;
rand_num2 = hi_chunk;
// probably you'll also need to display the numbers.
}
我希望我在上面的评论中所写的内容现在更有意义。
请记住,由于不知道您的电路板的确切细节,我不能 告诉你如何将模式实际写入7段显示,但我 假设会有某种功能。
答案 1 :(得分:0)
让我们先把它分解成碎片,然后逐个解决。无论如何,这是一种很好的做法,你最终会遇到许多容易解决的小问题。
我们可以从主循环的伪代码开始:
for ever {
while button is pushed {
roll the dice
update the displays
}
/* this ^ loop ends when the button is released
and is never entered until the button is pushed
*/
}
转换为:
int main(void)
{
/* somewhere to keep the current value of each die,
initialized to zero */
char dice[2] = {0,0};
for (;;) {
while (button_pushed()) {
roll(dice);
display(dice);
}
}
}
现在我们需要写button_pushed
:
/* return true (non-zero) if RC0 is zero/one (delete as appropriate) */
int button_pushed(void)
{
return RC0 == 0;
}
...和roll
以及display
。这会让你开始吗?