EmbeddedRelated.com
The 2024 Embedded Online Conference

Software SPI

May 6, 20131 comment Coded in ASM for the Microchip PIC16

Software SPI Read and write function for PIC

#include<p16f877a.inc>

#define	s_data_o	PORTC,5 ;serial data out
#define	s_data_i	PORTC,4	;serial data in
#define	s_clock		PORTC,3 ;clock out

	udata_shr
tx_reg	res	1
rx_reg	res	1

	code

;************************
;Configure I/O Ports
;Load data in WREG
;Call soft_spi_write
;************************
soft_spi_write
	global	soft_spi_write
	banksel	tx_reg
	movwf	tx_reg  	;store W = tx_reg
	banksel	PORTC 		;Bank 0
	bsf	STATUS,C 	;Set Carry Flag=1
send_next_bit
	rlf	tx_reg,F	;rotate left
	movf	tx_reg,F	;Check wheter 8 bit transmitted or not
	btfsc	STATUS,Z 	;If no ,send next bit
	return			;if yes,return

	bcf	s_data_o	;data line low
	btfsc	STATUS,C	;check the bit in carry,      	
	bsf	s_data_o	;if high,s_data_o =1
	fill	(nop),3
	bsf	s_clock		;s_clock=1	|		     _
	fill	(nop),5		;		|clock high to low _| |_		
	bcf	STATUS,C	;clear carry	|
	bcf	s_clock 	;S_clock=0  	|
	fill	(nop),3
	goto	send_next_bit	; looping process...........

;**************************************************
;Configure I/O Ports
;Call soft_spi_read	
;This fuction returns the received data is in WREG
;**************************************************
soft_spi_read			;subroutine for receive
	global	soft_spi_read
	movlw	0x01		;eight bit reception
	movwf	rx_reg
read_next_bit
	rlf	rx_reg,f	;rotating the rx_reg register to store the received bit
	bsf	s_clock 
	fill	(nop),5
	btfsc	s_data_i
	bsf	rx_reg,0	;receiving the data
	bcf	s_clock 
	fill	(nop),3
	btfss	STATUS,C	;testing whether the reception is compleate or not
	goto	read_next_bit	;if not compleated do the process again
	movf	rx_reg,W	;restore data in WREG
	return

	end

The 2024 Embedded Online Conference