Created
December 25, 2009 07:19
-
-
Save PhirePhly/263546 to your computer and use it in GitHub Desktop.
Twinkling LED algorithm for http://kennethfinnegan.blogspot.com/2009/12/twinkling-led-snowflakes.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <avr/io.h> // this contains all the IO port definitions | |
#include <util/delay.h> | |
// Global used to store the generated randomness | |
unsigned int reg=1; | |
// This function basically wastes time | |
void delay_ms(long int ms) { | |
for( ; ms > 0; ms--) { | |
_delay_ms( 1); | |
} | |
} | |
// Generate one random bit using a feedback shift register | |
// pseudorandom number generator algorithm | |
// The coefficients for this came from the TTL Cookbook, Lancaster | |
void gentick(void) { | |
int newbit = (((reg>>3)^(reg>>12))^((reg>>14)^(reg>>15)))&1; | |
reg = (reg<<1) + newbit; | |
} | |
int main(void) { | |
int i; | |
DDRB = 0xFF; // set port B to output only | |
PORTB = 0; // turn off all LEDs | |
while (1) { | |
// Generate this cycles randomness | |
for (i=3+8; i; i--) { | |
gentick(); | |
} | |
// Flip a random LED | |
PORTB = PORTB ^ (1<<(reg&7)); | |
// wait a random 0-0.5 seconds | |
delay_ms(((reg>>3)&0xFF) * 2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment