⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 spi.c

📁 ST7032i驱动应用实例(I2C接口)
💻 C
字号:
// ------------- Functions for simulating Serial Peripheral Interface ----------
/*  FileName: spi.c
	Version : 0.2
	Last Updated: 2007-4-27
	Description:
	This library contains the necessary functions for Simulating SPI bus.
	Program Coder: Seeseawe
*/


// Initialize the SPI as a master
void spi_init(void)
{
	#ifdef HW_SPI
		//DDRB |= (1<<SPI_CLK)|(1<<SPI_MOSI)|(1<<LCD_CS)|(1<<LCD_RST);
		do
		{
			DDRB = 0xBF;
		}while(DDRB != 0xBF);
		
		PORTB = 0x00;
		
		do
		{
			SPCR = 0x5A;
		}while(SPCR != 0x5A);
		
		do
		{
			SPSR = 0x00;
		}while(SPSR != 0x00);
		// Write to SPI Control Register.
		//SPCR = ( (1<<SPE)|(1<<MSTR)|(1<<CPOL) ) + 1;
		//SPCR = 0x58;
		/*
			D7: SPIE(SPI Interupt Enable)[1: Enable; 0: Disable]
			D6: SPE (SPI Enable)[1: Enable; 0: Disable]
			D5: DORD(Data Order)[1: LSB-MSB; 0: MSB-LSB]
			D4: MSTR(Master/Slave Mode)[1: Master; 0: Slave]
			D3: CPOL(Clock Polarity)
			D2: CPHA(Clock Phase)
			D1: SPR1(Speed Rate 1)
			D0: SPR0(Speed Rate 0)
			SPI2X D[1:0]	SPEED
			0		0		Fosc/4
			0		1		Fosc/16
			0		2		Fosc/64
			0		3		Fosc/128
			1		0		Fosc/2
			1		1		Fosc/8
			1		2		Fosc/32
			1		3		Fosc/64
		*/	
		// Set SPI Status Register
		//SPSR = 0x00;
		// D7: SPIF(SPI Interrupt Flag)
		// D6: WCOL(Write collision flag)
		// D[5:1]: 0(Reserved)
		// D0: SPI2X(Double SPI speed bit)
	#else
		LCD_CtrlPort_DDR = 0xB8;
		LCD_CtrlPort = 0x00;
	#endif
}


// Send a bit to the SPI device
void spi_sendbit(uint8 bitx)
{
	cbi(LCD_DataPort, SPI_CLK);
	if (bitx == 0)
		cbi(LCD_DataPort, SPI_MOSI);
	else
		sbi(LCD_DataPort, SPI_MOSI);
	sbi(LCD_DataPort, SPI_CLK);	
}

// Send a byte to the SPI device
void spi_sendbyte(uint8 dByte)
{
	#ifdef HW_SPI
		SPDR = dByte;
		while (!(SPSR & (1<<SPIF)));
		dByte = SPDR;
	#else
		uint8 i;
		for (i = 0; i < 8; i++)
		{
			spi_sendbit((dByte<<i) & 0x80);
		}
	#endif
}

// Read a byte from the SPI device
uint8 spi_readbyte(void)
{
	#ifdef HW_SPI
		SPDR = 0x00;
		while (!(SPSR & (1<<SPIF)));
		return SPDR;
	#else
		uint8 i;
		uint8 Result = 0;
		for (i = 0; i < 8; i++)
		{
			cbi(LCD_DataPort, SPI_CLK);
			Result <<= 1;
			sbi(LCD_DataPort, SPI_CLK);
			#ifdef SPI_MOSI
				// A-TYPE SPI(SDIN and SDOUT together)
				if ((LCD_DataPins & (1<<SPI_MOSI)) != 0)
			#else
				// B-TYPE SPI
				if ((LCD_DataPins & (1<<SPI_MISO)) != 0)
			#endif
			Result |= 0x01;
		}
		return Result;
	#endif
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -