0

我正在尝试为基本的骰子模拟器程序编写代码。当按下一个开关时,两个七段显示器将在 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[];
                  }
            }
}
4

2 回答 2

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. 这会让你开始吗?

于 2013-01-10T15:17:49.023 回答
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 段显示器,但我假设会有某种功能。

于 2013-01-10T14:56:04.827 回答