使用sample中的例子把LED闪烁和BLE程序完成了,之前那两次对config等修改很少,且代码也基本未做更改,这次自己编写一个简单点的程序,根据手中的资源就开发一个6轴sensor的程序吧。
(当时买开发板的时候要的是LIS3DSH芯片3轴加速度计,不知道怎么发来了MPU6050,刚收到货的时候没注意,开始使用才发现)
在zephyr根目录创建了一个projectors目录,然后创建sensor目录,在其中添加prj.conf、Makefile和src目录,src目录下包含main.c和Makefile。
sensor\Makefile内容如下:
BOARD ?= nrf52_pca10040 CONF_FILE = prj.conf include ${ZEPHYR_BASE}/Makefile.inc
prj.conf内容如下:
CONFIG_STDOUT_CONSOLE=y CONFIG_PRINTK=y CONFIG_UART_NRF5=y CONFIG_I2C=y CONFIG_SENSOR=y CONFIG_MPU6050=y CONFIG_I2C_NRF5=y CONFIG_I2C_NRF5_GPIO_SCA_PIN=23 CONFIG_I2C_NRF5_GPIO_SCL_PIN=22 CONFIG_I2C_0=y CONFIG_SYS_LOG_SENSOR_LEVEL=4 CONFIG_I2C_0_IRQ_PRI=1 CONFIG_SYS_LOG_I2C_LEVEL=1 CONFIG_SYS_LOG=y
src\Makefile内容如下:
obj-y = main.o
最后程序代码在main.c中:
#include
#include
#include
#include
#include
static int abs(int i) { return (i >= 0) ? i : -i; }
#define SLEEP_TIME 500
void main(void)
{
int ret;
struct device *dev;
struct sensor_value sen_val[3];
printk("nrf52 sensor test start\n");
dev = device_get_binding(CONFIG_MPU6050_NAME);
__ASSERT(dev != NULL, "Failed to get device binding");
printk("device is %p, name is %s\n", dev, dev->config->name);
while (1) {
ret = sensor_sample_fetch(dev);
if (ret) {
printk("sensor_sample_fetch failed ret %d\n", ret);
}
else {
ret = sensor_channel_get(dev, SENSOR_CHAN_ACCEL_XYZ, sen_val);
if (ret) {
printk("sensor_channel_get failed ret %d\n", ret);
}
else
printk("acc: x: %s%d.%06d y: %s%d.%06d z: %s%d.%06d\n",
(sen_val[0].val2<0 || sen_val[0].val2<0)?"-":" ", abs(sen_val[0].val1), abs(sen_val[0].val2),
(sen_val[1].val2<0 || sen_val[1].val2<0)?"-":" ", abs(sen_val[1].val1), abs(sen_val[1].val2),
(sen_val[2].val2<0 || sen_val[2].val2<0)?"-":" ", abs(sen_val[2].val1), abs(sen_val[2].val2));
ret = sensor_channel_get(dev, SENSOR_CHAN_GYRO_XYZ, sen_val);
if (ret) {
printk("sensor_channel_get failed ret %d\n", ret);
}
else
printk("gyro: x: %s%d.%06d y: %s%d.%06d z: %s%d.%06d\n",
(sen_val[0].val2<0 || sen_val[0].val2<0)?"-":" ", abs(sen_val[0].val1), abs(sen_val[0].val2),
(sen_val[1].val2<0 || sen_val[1].val2<0)?"-":" ", abs(sen_val[1].val1), abs(sen_val[1].val2),
(sen_val[2].val2<0 || sen_val[2].val2<0)?"-":" ", abs(sen_val[2].val1), abs(sen_val[2].val2));
printk("\n---------------------\n");
}
k_sleep(SLEEP_TIME);
}
}
执行make看将zephyr.hex烧录到开发板上,在串口中看到了MPU6050的信息
nrf52 sensor test start device is 0x2000033c, name is MPU6050 acc: x: 0.440533 y: -0.158018 z: 9.806650 gyro: x: 0.050761 y: 0.013989 z: -0.000532 --------------------- acc: x: 0.466869 y: -0.256180 z: 9.686939 gyro: x: 0.048096 y: 0.012257 z: -0.006261 --------------------- acc: x: 0.438138 y: -0.167595 z: 9.763554 gyro: x: 0.051027 y: 0.009859 z: -0.004263 --------------------- acc: x: 0.514753 y: -0.174777 z: 9.708487 gyro: x: 0.050094 y: 0.011857 z: -0.002931
此程序目前使用的是查询方式来读取sensor信息,未使用中断模式,在后续文章中会分析中断使用的方式。