最近,我让I2C使用一些MCC生成的函数工作,这些函数在.h文件中有很好的文档,但是SPI没有给我任何东西,并且给我带来了麻烦,这并不是因为我对这些串行协议很陌生。
我只是尝试在MCP23S17上读取一个寄存器,然后写入它,然后再读取它以验证它是否改变了。
我甚至不确定我是否会这样做,但我已经将我的代码包含在下面的注释中。出于某些原因,我似乎需要添加一些虚拟写来使第一个读工作,但只发生在第二个循环。
#include "mcc_generated_files/mcc.h"
uint8_t receiveData; /* Data that will be received */
uint8_t OpCodeW = 0x40;
uint8_t OpCodeR = 0x41;
void main(void)
{
SYSTEM_Initialize();
INTERRUPT_GlobalInterruptEnable();
INTERRUPT_PeripheralInterruptEnable();
Reset1_GPIO_SetLow();
__delay_ms(200);
Reset1_GPIO_SetHigh();
__delay_ms(200);
printf("Initalised \r\n");
while (1)
{
SPI1_Open(SPI1_DEFAULT);
CS1_GPIO_SetLow();
// Read IODIRA Register 0x00
SPI1_ExchangeByte(OpCodeR); // Address + Read
SPI1_ExchangeByte(0x00); // ??? -- When I add this in it works 2nd loop -- ???
receiveData = SPI1_ExchangeByte(0x00); // Returns 0x00 1st loop, then 0xFF after ...
// ... but only when duplicate sending of byte above ???
printf("Read IODIRA: 0x%02x \r\n", receiveData);
// Try writing to IODIRA Register
// Not sure what SPI1_WriteByte actually does!
// I thought it might be the same as ExchangeByte but without anything returned
// No idea!
SPI1_WriteByte(OpCodeW); // Address + Write
SPI1_WriteByte(0x00); // Register Addres IODIRA (Port A)
SPI1_WriteByte(0xF0); // Data to be written
// Read back changed IODIRA Register again - Same routine as above
SPI1_ExchangeByte(OpCodeR); // Address + Read
SPI1_ExchangeByte(0x00); // Same routine as above ...
// ... but always prints 0x00
receiveData = SPI1_ExchangeByte(0x00); // Register Address, IODIRA (Port A)
printf("Wrote to IODIRA and read back: 0x%02x \r\n", receiveData);
printf(" ----- \r\n\n");
CS1_GPIO_SetHigh();
SPI1_Close();
__delay_ms(5000);
}
}实际的打印输出如下:
Initalised
Read IODIRA: 0x00 // Should be 0xFF
Wrote to IODIRA and read back: 0x00 // Should be 0xF0
-----
Read IODIRA: 0xff // This is right now!
Wrote to IODIRA and read back: 0x00 // but this hasn't changed
-----
Read IODIRA: 0xff
Wrote to IODIRA and read back: 0x00
Read IODIRA: 0xff
Wrote to IODIRA and read back: 0x00任何帮助都非常感谢。
发布于 2021-09-11 15:34:53
答案是需要在每次SPI写入时设置(低)芯片选择,以便在消息启动/完成时通知设备。因为我只想和一个设备交谈,所以我一直在用它来支持(保持设备CS低),但这是不正确的。
https://stackoverflow.com/questions/69068145
复制相似问题