所以我很难设置我的SPI,并让它与LSM330设备一起工作以读取加速度计数据。我只是设置SPI系统,并尝试使用它来读取WHO_AM_I_A寄存器以确认它正在工作,而我所得到的只是0xff而不是0x40。
这是我的代码:
的main.c
#include <avr/io.h>
#include "LSM330.h"
#include "spi.h"
#include "CLK.h"
#include "accel.h"
int main(void) {
//set clock
set32MhzClock();
//first set SPI slave selects for accel gyro to false(high)
PORTF.OUTSET = PIN4_bm | PIN3_bm;
//set serial system of SPI
PORTA_OUTCLR = PIN4_bm;
//init SPI
spi_init();
//reset LSM330 accel by sending 0x01 to CTRL_REG4_A
accel_write(0x01, CTRL_REG4_A);
//trying to read from WHO_AM_I_A reg
uint8_t whoAreYou = accel_read(WHO_AM_I_A);
printf(whoAreYou);
}
accel.h
#include "LSM330.h"
#include "spi.h"
void accel_write(uint8_t reg_addr, uint8_t data) {
//make slave select signal LOW
PORTF_OUTCLR = PIN3_bm;
//set sensor_sel
PORTF_OUTSET = PIN2_bm;
//first write reg_addr, w/ RW=0 and MS=0
uint8_t writeResult = spi_write(reg_addr);
//then write data byte
spi_write(data);
return;
}
spi.h中
void spi_init(void) {
//set correct pins as outputs and inputs
PORTF.DIRSET = PIN7_bm | PIN5_bm | PIN4_bm | PIN3_bm; //SCK, MOSI, SSG, SSA as outputs
PORTF.DIRCLR = PIN6_bm; //MISO as input
//set up SPI as master
SPIF.CTRL = SPI_ENABLE_bm | SPI_MASTER_bm | SPI_MODE_3_gc | SPI_PRESCALER_DIV16_gc;
//clear spi interrupt flag by reading spsr and spdr
SPIF_STATUS;
SPIF_DATA;
return
}
uint8_t spi_write(uint8_t dataIn) {
//write data
SPIF.DATA = dataIn;
//wait for transmission to complete
while(!(SPIF_STATUS & SPI_IF_bm));
return SPIF.DATA;
}
uint8_t spi_read(vodi) {
return spi_write(0xFF);
}
这就是我的全部。尝试了很多东西,似乎无法让这件事情发挥作用。似乎SPI正在工作,因为它在写入数据时不会陷入任何while循环中。
答案 0 :(得分:0)
没有太多细节,这里肯定有问题:
//reset LSM330 accel by sending 0x01 to CTRL_REG4_A
accel_write(0x01, CTRL_REG4_A);
但是你的功能声明如下:
void accel_write(uint8_t reg_addr, uint8_t data)
您似乎将寄存器0x01设置为CTRL_REG4_A的值。