Reputation: 11
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");
}
}
}
Upvotes: 0
Views: 651
Reputation: 4288
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’);
}
Upvotes: 2