summaryrefslogtreecommitdiff
path: root/samples/drivers/spi_lsm9ds0/src/main.c
blob: f86d3d2cfc3d6f165db8be40cdd3cf2267b0032a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
 * Copyright (c) 2016 Intel Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <zephyr.h>

#include <device.h>
#include <spi.h>

#include <misc/printk.h>

#define LSM9DS0_WHOAMI_G 0xf
#define LSM9DS0_READ_MASK 0x80

static uint8_t rx_buffer[2], tx_buffer[2];

static uint8_t lsm9ds0_read_whoami_g(struct device *dev)
{
	int err;

	tx_buffer[1] = LSM9DS0_WHOAMI_G | LSM9DS0_READ_MASK;

	err = spi_transceive(dev, tx_buffer, sizeof(tx_buffer),
			     rx_buffer, sizeof(rx_buffer));
	if (err) {
		printk("Error during SPI transfer\n");
		return 0;
	}

	return rx_buffer[0];
}

void main(void)
{
	struct spi_config config = { 0 };
	struct device *spi_mst_0 = device_get_binding("SPI_0");
	uint8_t id;
	int err;

	printk("SPI Example application\n");

	if (!spi_mst_0)
		return;

	config.config = SPI_MODE_CPOL | SPI_MODE_CPHA | SPI_WORD(16);
	config.max_sys_freq = 256;

	err = spi_configure(spi_mst_0, &config);
	if (err) {
		printk("Could not configure SPI device\n");
		return;
	}

	err = spi_slave_select(spi_mst_0, 1);
	if (err) {
		printk("Could not select SPI slave\n");
		return;
	}

	id = lsm9ds0_read_whoami_g(spi_mst_0);

	printk("LSM9DS0 Who Am I: 0x%x\n", id);
}