xingcontrol/safety.c
2019-10-18 22:08:59 +02:00

100 lines
2.4 KiB
C
Executable File

#define F_CPU 16000000UL
#include <avr/io.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>
#include <stdfix.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include "mytimer.h"
#include "usart.h"
///////////////////////////////////////////////////////////
//MACROS
#define GATE_DISTcm 20 //distance between gates in cm
#define setb(port,pin) port |= 1<<pin //set bit
#define clrb(port,pin) port &= ~(1<<pin) //clear bit
#define negb(port,pin) port ^= 1<<pin //negate bit
///////////////////////////////////////////////////////////
//global vars
char tmp[100];
unsigned long t;
unsigned long t2;
int trains = 0;
int carriages = 0; //storing stats
int trg0;
int trg1;
unsigned long trgt;
void idle(void){
setb(PORTB, 5);
_delay_ms(100);
clrb(PORTB, 5);
_delay_ms(100);
setb(PORTB, 5);
_delay_ms(100);
clrb(PORTB, 5);
_delay_ms(1000);
};
void light_clear(void){
if(bit_is_set(PORTC,0) || bit_is_set(PORTC,2)){
clrb(PORTC,0);
clrb(PORTC,2);
};
negb(PORTC,1);
_delay_ms(700);
};
void light_blocked(char sound){
if(bit_is_set(PORTC,1)) clrb(PORTC,1);
//mute sound signalling
if(sound == 0){
setb(PORTC,0);
_delay_ms(500);
clrb(PORTC,0);
setb(PORTC,2);
_delay_ms(500);
clrb(PORTC,2);
}
else { //enable sound signalling
setb(PORTC,0);
for(int i = 0;i < 110;i++){ //sound generation
setb(PORTC,3);
_delay_us(900);
clrb(PORTC,3);
_delay_us(900);
};
_delay_ms(75);
for(int i = 0;i < 116;i++){ //sound generation again
setb(PORTC,3);
_delay_us(870);
clrb(PORTC,3);
_delay_us(870);
};
clrb(PORTC,0);
setb(PORTC,2);
/*alternate warning sound
for(int i = 0;i < 160;i++){
setb(PORTC,3);
_delay_us(600);
clrb(PORTC,3);
_delay_us(600);
};
*/
_delay_ms(500); //if using alternate sound adjust delay accordingly
clrb(PORTC,2);
};
};
void eval(void){
accum trvt = 0;
accum spd = 0; //fixed point decimal vars
trvt = (t2 - trgt) * 1e-6; //calculate time spent crossing in s
spd = GATE_DISTcm / ((t - trgt) * 1e-6); //calculate speed in cm/s (gate distance can be adjusted by editing macro at the top)
sprintf(tmp,"Train passed: %d carriage(s), time %.2fs, speed %.2fcm/s\r\n",trg0/2,(double)trvt,(double)spd); //convert stats to format readable by USART_putstring i.e. a string
USART_putstring(tmp); //send info
trains++; //increment amount of trains passed
carriages = carriages + trg0/2; //increment amount of carriages
};