; miditest.asm
; (c) 2007  Avelino Herrera Morales
; (c) 2011  Yamil Saiegh
; 4MHz PIC16F84 microcontroller
;
; based on midisend.asm source code from http://www.audiomulch.com/midipic/


processor 16f84
include	  <p16f84.inc>
__config  _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF


temp	equ	0x1F
xmit	equ	0x1D ; xmit contains the byte to send
j		equ	0x1B


org	0

	
	; port A as output
	bsf		STATUS,5
	movlw	0x00
	movwf	TRISA

	; port B as input
	movwf	TRISB
	movlw	0xFF
	bcf		STATUS,5

	; init midi out pin state
	bsf		PORTA,0x00

 
mainloop:

testbit0:
	; port B bit 0 = 0 : NOTE ON
	btfsc	PORTB,0   
	goto	testbit1
	
	movlw 0x90		; note on
	movwf xmit
	call	sendmidi
	
	movlw 0x3C		; middle C
	movwf xmit
	call	sendmidi

	movlw 0x7F		; velocity = 127
	movwf xmit
	call	sendmidi
	goto	mainloop

testbit1:
	; port B bit 1 = 0 : NOTE OFF
	btfsc	PORTB,1
	goto	mainloop

	movlw 0x80		; note off
	movwf xmit
	call	sendmidi

	movlw 0x3C		; middle C
	movwf xmit
	call	sendmidi

	movlw 0x7F		; velocity = 127
	movwf xmit
	call	sendmidi
	goto	mainloop

 
sendmidi:			

	; send start bit (0)
	bcf PORTA,0x00
	
	; 25 cycles
	movlw 8		
	movwf temp		
	loop1:
	decfsz temp,f	
	goto loop1					

	; 2 cycles
	movlw 8
	movwf j

	; 3 cycles whether "0", 4 cycles whether "1"
sendloop:
	rrf xmit,f
	btfsc STATUS,C
	goto	send1

	; 4 cycles
send0:
	nop                 
	bcf	PORTA,0x00	
	goto	endloop        

	; 3 cycles
send1:
	bsf PORTA,0x00
	nop			 
	nop

	; 22 cycles
endloop:
	movlw 7		
	movwf temp
loop2:
	decfsz temp,f
	goto	loop2 

	; 3 cycles when restart, 2 cycles when stop
	decfsz j,f
	goto	sendloop

	; 5 cycles
	nop
	nop
	nop
	nop
	nop

	; send stop bit (1)
	bsf PORTA,0x00	          

	; 32 cycles
	movlw 10
	movwf temp
loop3:
	decfsz temp,f   
	goto loop3     
	nop

	return

	
end

