编辑代码

#include "stm32f10x.h"
#include "i2c.h"
#include "gyro.h"

// 陀螺仪的 I2C 地址
#define GYRO_ADDR 0x68

// 定义陀螺仪数据结构体
typedef struct {
    int16_t x;
    int16_t y;
    int16_t z;
} GyroData;

GyroData gyroData;

// 初始化 I2C 通信
void I2C_Init(void)
{
    // 配置 I2C 相关的时钟、引脚等
    //...
}

// 读取陀螺仪数据
void ReadGyroData(GyroData *data)
{
    uint8_t buf[6];
    // 发送读取数据的命令
    I2C_Start();
    I2C_SendByte(GYRO_ADDR << 1 | 0);
    I2C_WaitAck();
    I2C_SendByte(0x67);
    I2C_WaitAck();

    I2C_Start();
    I2C_SendByte(GYRO_ADDR << 1 | 1);
    I2C_WaitAck();

    I2C_ReadByte(buf, 6);
    I2C_Stop();

    data->x = (int16_t)((buf[0] << 8) | buf[1]);
    data->y = (int16_t)((buf[2] << 8) | buf[3]);
    data->z = (int16_t)((buf[4] << 8) | buf[5]);
}

int main(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;

    // 初始化系统时钟
    SystemInit();

    // 初始化 I2C 通信
    I2C_Init();

    // 配置 B3 和 B4 引脚为输出模式
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3 | GPIO_Pin_4;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOB, &GPIO_InitStructure);

    while (1) {
        ReadGyroData(&gyroData);

        // 判断 X 轴和 Y 轴向左转
        if ((gyroData.x < 0) && (gyroData.y < 0)) {
            GPIO_SetBits(GPIOB, GPIO_Pin_3);
            Delay_ms(250);
            GPIO_ResetBits(GPIOB, GPIO_Pin_3);
            Delay_ms(250);
            Delay_ms(5000);
        }
        // 判断 X 轴和 Y 轴向右转
        else if ((gyroData.x > 0) && (gyroData.y > 0)) {
            GPIO_SetBits(GPIOB, GPIO_Pin_4);
            Delay_ms(250);
            GPIO_ResetBits(GPIOB, GPIO_Pin_4);
            Delay_ms(250);
            Delay_ms(5000);
        }
    }
}