我有一个Mbed和一个数字陀螺仪传感器。我想确保其中两个通过SPI进行通信,其中Mbed(主机)能够从陀螺仪传感器(从机)读取数据。有人可以帮忙吗?
#include "mbed.h"
SPI spi(p5, p6, p7); // mosi, miso, sclk
DigitalOut cs(p8);
Serial pc(USBTX, USBRX);
int main() {
// Slave select disabled //
cs = 1;
// Setup the spi for 8 bit data, high steady state clock,
// Second edge capture, with a 1MHz clock rate
spi.format(8,3);
spi.frequency(500000);
// Slave select enabled, it is active low //
cs = 0;
// Send 0x8F, the command to read the WHO_AM_I register //
// 0x8F 1000 1111, MSB = 0 means write and MSB = 1 means read //
spi.write(0x8F);
// Send a dummy byte to receive the contents of the WHO_AM_I register //
// The default response 1101 0011 //
int whoami = spi.write(0x00);
pc.printf("WHOAMI register = 0x%X\n", whoami);
// Slave select disabled //
cs = 1;
while(1) {
cs = 0 ;
// 0x28 is the register for OUT_X_L of the gyroscope //
spi.write(0x28);
int data = spi.write(0x00);
pc.printf("data output 0x%X\n", data);
wait(0.5);
cs = 1;
}
}
答案 0 :(得分:0)
一个长远的答案。陀螺仪规格可能会指定CS变低的时间,您可以开始发送数据。因此,请尝试在cs = 0之后进行延迟;
第二,为什么要读取WHO_AM_I注册时要设置MSB。 MSB = 1用于写而不是读。