0

I used a PIC simulator IDE with PIC16F886 and random is always equal to 0 every time I run the code. It look like the rand() is not working. I can't understand what happened.

Here is the code:

#include <16F886.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>

#FUSES NOWDT
#FUSES PUT
#FUSES NOMCLR
#FUSES NOPROTECT
#FUSES NOCPD
#FUSES BROWNOUT
#FUSES IESO
#FUSES FCMEN
#FUSES NOLVP
#FUSES NODEBUG
#FUSES NOWRT
#FUSES BORV40
#FUSES RESERVED
#FUSES INTRC_IO

#use delay(clock=8M)

#use rs232(baud=9600,parity=N,xmit=PIN_C6,rcv=PIN_C7,bits=8)

void main()
{
    int myInput;
    int random;
    random = rand() % 5;
    printf("type a character\r\n");
    printf(" %d ", random);
    while(1) {
        myInput = getc();
        printf("You typed - %d\r\n", myInput);
        if(myInput>random){
            printf("too high\n");
        }
        else if(myInput<random) {
            printf("too low");
        }
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tenshiro
  • 11
  • 1
  • 4
    Does this answer your question? [Generating random numbers in C](https://stackoverflow.com/questions/3067364/generating-random-numbers-in-c) – alx - recommends codidact Mar 31 '20 at 16:52
  • Also you are using a (simulated) pic. So `stdlib.h` `time.h` and `stdio.h` are weird libraries to use. If you need random numbers than use the hardware. – Tarick Welling Mar 31 '20 at 21:34
  • Does this answer your question? [Why does rand() yield the same sequence of numbers on every run?](https://stackoverflow.com/questions/9459035/why-does-rand-yield-the-same-sequence-of-numbers-on-every-run) – Peter Mortensen May 13 '20 at 16:48
  • There doesn't seem to be anything PIC-specific about this as it is the standard libraries that are in use (though there could be some 16 bit vs. 32 bit vs. 64 bit differences). – Peter Mortensen May 13 '20 at 16:49
  • If you want more insight, remove the modulus (`% 5`) to see the actual values from rand(). The first value probably just happens to be divisible by 5. – Peter Mortensen May 13 '20 at 16:51
  • @Tarick Welling: What hardware? Can you elaborate? *[How to Use Than and Then](http://www.wikihow.com/Use-Than-and-Then)* – Peter Mortensen May 13 '20 at 16:54
  • @PeterMortensen great I'm getting spellchecked on the internet. Also what hardware? `PIC16F886` *that* hardware. Like peripherals hardware. It's an embedded device, use it. – Tarick Welling May 13 '20 at 17:29

1 Answers1

2

You had to initialize the starting point for rand() with a call of the srand() function.
There is a really good example in xc8 user guide on page 399.

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
void main (void){
    time_t toc; 
    int i;   
    time(&toc);
    srand((int)toc);
    for(i = 0 ; i != 10 ; i++)
        printf("%d\t", rand()); 
    putchar(’\n’);
}
Mike
  • 4,041
  • 6
  • 20
  • 37