mardi 28 mai 2019

Trying to toggle random LEDs with a XOR and bit shift operator

For a model railroad project, I am trying to toggle LEDs by using a random number generator (rand()) which produces x and then shifting 1 to the left by x on the LATC register on a PIC16F15325. (I am an enthusiastic hobbyist, but still with so much to learn, completely self-taught.) I am using XC8 and PICkit 3.

I am using the 16F15325 pic, and, in my mind, the following code should (A) generate a random number (pseudo is ok) between 0 and 5 (this is x) and (B) toggle bits C0 through C5 (each connected to an LED in the LATC register) by shifting 1 by x bits (i.e., 0 to 5) and by applying an XOR to that pin. Given that this is in an infinite loop, then each time the code loops, it should toggle at least one LED. This works about 90% of the time, but sometimes it doesn't result in a toggle, and it's driving me nuts.

#include <xc.h>
#include <stdint.h>         /* For uint8_t definition */
#include <stdbool.h>        /* For true/false definition */
#include "configs.c"

void main(void) {

InitProgram();   // THIS SETS UP THE TRIS AND SETS THE C PORT TO OUTPUT

//  DECLARE AND SET VARIABLES

int x;             //  GENERAL PURPOSE VARIABLE TO USE ON THE FLY

LATC = 0b00111111;

while(1)
{
    x = rand() % 6;   //  SHOULD GENERATE 0 THROUGH 5 B/C NO "+ 1"

    LATC = LATC ^ 1 << x;

    //  I HAVE ALSO TRIED LATC = LATC ^ 1 << (char) x;

    //  THERE IS A ONE SECOND DELAY HERE

 }
}

As noted, this very often works on each run through the loop, but about 10% of the time, no LED will toggle. 90% of the time, one of the LEDs toggles.




Aucun commentaire:

Enregistrer un commentaire