/*
 *      launch_codes.c
 *      
 *      Copyright 2011 Brian Starkey <stark3y[AT]gmail[DOT]com>
 *      
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *      
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *      
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 *
 *
 *      Displays random 5-digit numbers on a bank of 7-segment displays
 *      using 4518 BCD counters on PORTD.
 *      Effect is reminiscent of code displays in Hollywood movies.
 *
 * 
 */

#define F_CPU 1000000

#include <avr/io.h>
#include <util/delay.h>
#include <avr/pgmspace.h>
#include <avr/interrupt.h>
#include <stdlib.h>

#define NORMAL 0
#define DONE 1
#define NONE 2

void bleep(unsigned char type) ;

int main(void) {
		DDRB = 0xFF;
		DDRD = 0x50;
		PORTD = ~0x40;
		for (;;) {
			unsigned int code_numbers[5], i, j;
			for (i = 0; i < 5; i++) {
				code_numbers[i] = (int)(rand()%500)+100;
				//display_numbers[i] = (char)(rand()%10);
			}
			for (i = 0; i < 600; i++) {
				unsigned char k;
				for (k = 0; k < 5; k++) {
					if (i < code_numbers[k]) {
						PORTB |= (1 << k);
						_delay_ms(3);
						//bleep(NORMAL);
						PORTB &= ~(1 << k);
					}
					else if (i == code_numbers[k]) {
						PORTB |= (1 << k);
						for (j = 0; j < 20; j++) {//16ms
							PORTD |= 0x10;
							_delay_us(568);
							PORTD &= ~0x10;
							_delay_us(568);
						}
						PORTB &= ~(1 << k);
					}
				}
				_delay_ms(50);
			}
			_delay_ms(3000);
		}
				
	return 0;
}

void bleep(unsigned char type) {
	unsigned char i;
	switch (type) {
		case NORMAL :
			for (i = 0; i < 15; i++) { //10ms
				PORTD |= 0x10;
				_delay_us(568);
				PORTD &= ~0x10;
				_delay_us(568);
			}
			_delay_ms(3);
			break;
		case DONE :
			for (i = 0; i < 28; i++) {//16ms
				PORTD |= 0x10;
				_delay_us(300);
				PORTD &= ~0x10;
				_delay_us(300);
			}
			break;
		case NONE :
			_delay_ms(17);
			break;
	}
}
