.include "tn45def.inc" .def bit_count = R16 .def temp = R17 .def temp1 = R18 .def txbyte = R19 .def lowbyte = R20 .def highbyte = R21 .def count = R22 .cseg .org 0 rjmp reset .org 6 rjmp t0overflow ; ; bit delay ; serial bit delay ; .equ b = 13 ; 9600 baud (clock /8) ;.equ b = 8 ; 115200 baud (clock /1) bit_delay: ldi temp, b bitloop: dec temp brne bitloop ret ; ; putchar ; .equ sb = 1; number of stop bits putchar: ldi bit_count, 9+sb; 1+8+sb com txbyte; invert everything sec; set start bit putchar0: brcc putchar1; if carry set cbi PORTB, PB1; send a '0' rjmp putchar2; else putchar1: sbi PORTB, PB1 ; send a '1' nop ; even out timing putchar2: rcall bit_delay; one bit delay rcall bit_delay lsr txbyte; get next bit dec bit_count; if not all bits sent brne putchar0; send next bit ret; ; ; puthex ; print a byte in hex ; clobbers txbyte ; puthex: push txbyte swap txbyte andi txbyte, 15 ldi temp, '0' cpi txbyte, 10 brcs lessthantenh ldi temp, 'A'-10 lessthantenh: add txbyte, temp rcall putchar pop txbyte andi txbyte, 15 ldi temp, '0' cpi txbyte, 10 brcs lessthantenl ldi temp, 'A'-10 lessthantenl: add txbyte, temp rcall putchar ret reset: sbi DDRB, PB1 ; select analog input 1 (PB2) sbi ADMUX, MUX0 ; enable ADC sbi ADCSRA, ADEN ; configure timer 0 for pre-scale factor of 8, fast-PWM mode ldi temp, 3 out TCCR0A, temp ldi temp, 10 out TCCR0B, temp ; trigger timer 0 overflow interrupt at TCNT0 = 91 ldi temp, 92 out OCR0A, temp ; enable timer 0 overflow interrupt ldi temp, 2 out TIMSK, temp sei loop: rjmp loop t0overflow: sbi ADCSRA, ADSC ; start conversion AD_loop: sbic ADCSRA, ADSC ; loop until complete rjmp AD_loop in temp, ADCL sbrs count, 0 add lowbyte, temp sbrc count, 0 sub lowbyte, temp in temp, ADCH sbrs count, 0 adc highbyte, temp sbrc count, 0 sbc highbyte, temp inc count cpi count, 20 brne done mov txbyte, highbyte rcall puthex mov txbyte, lowbyte rcall puthex ldi txbyte, 10 rcall putchar ldi txbyte, 13 rcall putchar tst highbyte brpl positive neg lowbyte inc highbyte neg highbyte positive: cpi lowbyte, 8 brpl detected tst highbyte brne detected cbi PORTB, PB0 rjmp notdetected detected: sbi PORTB, PB0 notdetected: mov txbyte, highbyte rcall puthex mov txbyte, lowbyte rcall puthex ldi txbyte, 10 rcall putchar ldi txbyte, 13 rcall putchar ldi lowbyte, 0 ldi highbyte, 0 ldi count, 0 done: reti