|
发表于 2008-4-18 02:12:21
|
显示全部楼层
关于SPI从机的讨论非常好。在我的书中,由于篇幅的限制,无法对SPI的更深入的东西,包括从机方式做仔细的介绍。
在3楼,我只是简单提提,原不想做更多的说明,主要针对从机中断的问题解答一下。既然楼上的有许多的认为(或许经过实践的),那就讨论一下吧。
先贴上几段原文手册中的相关说明,不晓得楼上是否全面的看过,我在这个基础上再做些解释.
When configured as a Slave, the SPI interface will remain sleeping with MISO tri-stated as long as the SS pin is driven high. In this state, software may update the contents of the SPI Data Register, SPDR, but the data will not be shifted out by incoming clock pulses on the SCK pin until the SS pin is driven low. As one byte has been completely shifted, the end of transmission flag, SPIF is set. If the SPI interrupt enable bit, SPIE, in the SPCR Register is set, an interrupt is requested. The Slave may continue to place new data to be sent into SPDR before reading the incoming data. The last incoming byte will be kept in the buffer register for later use.
MISO – Port B, Bit 6
MISO: Master Data input, Slave Data output pin for SPI channel. When the SPI is enabled as a Master, this pin is configured as an input regardless of the setting of DDB6. When the SPI is enabled as a Slave, the data direction of this pin is controlled by DDB6. When the pin is forced by the SPI to be an input, the pull-up can still be controlled
by the PORTB6 bit.
Table 65. SPI Pin Overrides(1)
Pin Direction, Master SPI Direction, Slave SPI
MOSI User Defined Input
MISO Input User Defined
SCK User Defined Input
SS User Defined Input
C Code Example(1)
void SPI_SlaveInit(void)
{
/* Set MISO output, all others input */
DDR_SPI = (1<<DD_MISO);
/* Enable SPI */
SPCR = (1<<SPE);
}
char SPI_SlaveReceive(void)
{
/* Wait for reception complete */
while(!(SPSR & (1<<SPIF)))
;
/* Return data register */
return SPDR;
}
===========================================================================
因此,首先肯定,当设置SPI为从机时,MOSI,SS,SCK 为输入,而MISO由用户配置。
因此如果从机SPI要输出数据的话,当然应该将MISO配置成输出方式了。注意的是,如果SS为高的话,SPI将强制将MISO设置成输入高阻(用户配置不起作用),但当SS为低时,MISO的特性为用户的配置。
如果能明白上面的过程的话,我们才能灵活的使用SPI的从机功能。
如果AVR的SPI设置为从机,且SPI总线上挂有多个从机时,那么SS就必须要使用了。当SS为高时,说明本SPI没有被选中,此时MISO被强制为输入高阻(此时用户设置实际无效),不会影响SPI总线上其它器件的工作。当SS拉低(不会产生中断的),MISO恢复用户设置的输出方式,在SCK的作用下将数据寄存器中数据串出。
如果AVR的SPI设置为从机,且SPI总线上只有这一个从机时,而这个从机是用户自己定义的话。那么只要选择模式1、3,SS就可以不考虑了。此处的“不考虑或不要”是指将SS永久接地(在上面没讲清楚),那么SPI永远准备工作,MISO就是用户的配置,只要有SCK输入,就将数据串出,串出8位后产生中断(仅限模式1、3)。这样主机的SS可以作为它用,节省资源。
AVR中很多的东西非常灵活,因此可以在多种情况下使用(如实现SPI多主总线系统等)。但也正式由于太灵活了,当你对协议没有真正彻底的理解透时,反而不会使用了,也用不好,当然也不会理解AVR为何这样设计。 |
|