aboutsummaryrefslogtreecommitdiff
path: root/drivers/ws2812/ws2812_i2s.c
blob: 8e59c908fb83f3f43e5449d699de4b1b110f6bed (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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
/*
 * Copyright (c) 2022 Jonathan Rico
 * Copyright (c) 2023 Leon Rinkel
 *
 * Adapted from the SPI driver, using the procedure in this blog post:
 * https://electronut.in/nrf52-i2s-ws2812/
 *
 * Note: the word "word" refers to a 32-bit integer unless otherwise stated.
 *
 * WS/LRCK frequency:
 * This refers to the "I2S word or channel select" clock.
 * The I2C peripheral sends two 16-bit channel values for each clock period.
 * A single LED color (8 data bits) will take up one 32-bit word or one LRCK
 * period. This means a standard RGB led will take 3 LRCK periods to transmit.
 *
 * SPDX-License-Identifier: Apache-2.0
 */

#define DT_DRV_COMPAT worldsemi_ws2812_i2s

#include <string.h>

#include <zephyr/drivers/led_strip.h>

#define LOG_LEVEL CONFIG_LED_STRIP_LOG_LEVEL
#include <zephyr/logging/log.h>
LOG_MODULE_REGISTER(ws2812_i2s);

#include <zephyr/device.h>
#include <zephyr/drivers/i2s.h>
#include <zephyr/dt-bindings/led/led.h>
#include <zephyr/kernel.h>
#include <zephyr/sys/util.h>

#include "rgbw.h"

#define WS2812_I2S_PRE_DELAY_WORDS 1

struct ws2812_i2s_cfg {
	struct device const *dev;
	size_t tx_buf_bytes;
	struct k_mem_slab *mem_slab;
	uint8_t num_colors;
	const uint8_t *color_mapping;
	uint16_t reset_words;
	uint32_t lrck_period;
	uint32_t extra_wait_time_us;
	bool active_low;
	uint8_t nibble_one;
	uint8_t nibble_zero;
};

/* Serialize an 8-bit color channel value into two 16-bit I2S values (or 1 32-bit
 * word).
 */
static inline void ws2812_i2s_ser(uint32_t *word, uint8_t color, const uint8_t sym_one,
				  const uint8_t sym_zero)
{
	*word = 0;
	for (uint16_t i = 0; i < 8; i++) {
		if ((1 << i) & color) {
			*word |= sym_one << (i * 4);
		} else {
			*word |= sym_zero << (i * 4);
		}
	}

	/* Swap the two I2S values due to the (audio) channel TX order. */
	*word = (*word >> 16) | (*word << 16);
}

static int ws2812_strip_update_rgb(const struct device *dev, struct led_rgb *pixels,
				   size_t num_pixels)
{
	const struct ws2812_i2s_cfg *cfg = dev->config;
	uint8_t sym_one, sym_zero;
	uint32_t reset_word;
	uint32_t *tx_buf;
	uint32_t flush_time_us;
	void *mem_block;
	int ret;

	if (cfg->active_low) {
		sym_one = (~cfg->nibble_one) & 0x0F;
		sym_zero = (~cfg->nibble_zero) & 0x0F;
		reset_word = 0xFFFFFFFF;
	} else {
		sym_one = cfg->nibble_one & 0x0F;
		sym_zero = cfg->nibble_zero & 0x0F;
		reset_word = 0;
	}

	/* Acquire memory for the I2S payload. */
	ret = k_mem_slab_alloc(cfg->mem_slab, &mem_block, K_SECONDS(10));
	if (ret < 0) {
		LOG_ERR("Unable to allocate mem slab for TX (err %d)", ret);
		return -ENOMEM;
	}
	tx_buf = (uint32_t *)mem_block;

	/* Add a pre-data reset, so the first pixel isn't skipped by the strip. */
	for (uint16_t i = 0; i < WS2812_I2S_PRE_DELAY_WORDS; i++) {
		*tx_buf = reset_word;
		tx_buf++;
	}

	/*
	 * Convert pixel data into I2S frames. Each frame has pixel data
	 * in color mapping on-wire format (e.g. GRB, GRBW, RGB, etc).
	 */
	for (uint16_t i = 0; i < num_pixels; i++) {
		uint8_t ro, go, bo, wo;
		rgbw_conversion(
			/* outs: */ &ro, &go, &bo, &wo,
			/*  ins: */ pixels[i].r, pixels[i].g, pixels[i].b,
			/* algo: */ 4
		);

		for (uint16_t j = 0; j < cfg->num_colors; j++) {
			uint8_t pixel;

			switch (cfg->color_mapping[j]) {
			/* White channel is not supported by LED strip API. */
			case LED_COLOR_ID_WHITE:
				pixel = wo;
				break;
			case LED_COLOR_ID_RED:
				pixel = ro;
				break;
			case LED_COLOR_ID_GREEN:
				pixel = go;
				break;
			case LED_COLOR_ID_BLUE:
				pixel = bo;
				break;
			default:
				return -EINVAL;
			}
			ws2812_i2s_ser(tx_buf, pixel, sym_one, sym_zero);
			tx_buf++;
		}
	}

	for (uint16_t i = 0; i < cfg->reset_words; i++) {
		*tx_buf = reset_word;
		tx_buf++;
	}

	/* Flush the buffer on the wire. */
	ret = i2s_write(cfg->dev, mem_block, cfg->tx_buf_bytes);
	if (ret < 0) {
		k_mem_slab_free(cfg->mem_slab, mem_block);
		LOG_ERR("Failed to write data: %d", ret);
		return ret;
	}

	ret = i2s_trigger(cfg->dev, I2S_DIR_TX, I2S_TRIGGER_START);
	if (ret < 0) {
		LOG_ERR("Failed to trigger command %d on TX: %d", I2S_TRIGGER_START, ret);
		return ret;
	}

	ret = i2s_trigger(cfg->dev, I2S_DIR_TX, I2S_TRIGGER_DRAIN);
	if (ret < 0) {
		LOG_ERR("Failed to trigger command %d on TX: %d", I2S_TRIGGER_DRAIN, ret);
		return ret;
	}

	/* Wait until transaction is over */
	flush_time_us = cfg->lrck_period * cfg->tx_buf_bytes / sizeof(uint32_t);
	k_usleep(flush_time_us + cfg->extra_wait_time_us);

	return ret;
}

static int ws2812_strip_update_channels(const struct device *dev, uint8_t *channels,
					size_t num_channels)
{
	LOG_ERR("update_channels not implemented");
	return -ENOTSUP;
}

static int ws2812_i2s_init(const struct device *dev)
{
	const struct ws2812_i2s_cfg *cfg = dev->config;
	struct i2s_config config;
	uint32_t lrck_hz;
	int ret;

	lrck_hz = USEC_PER_SEC / cfg->lrck_period;
	LOG_DBG("Word clock: freq %u Hz period %u us",
		lrck_hz, cfg->lrck_period);

	/* 16-bit stereo, 100kHz LCLK */
	config.word_size = 16;
	config.channels = 2;
	config.format = I2S_FMT_DATA_FORMAT_I2S;
	config.options = I2S_OPT_BIT_CLK_MASTER | I2S_OPT_FRAME_CLK_MASTER;
	config.frame_clk_freq = lrck_hz; /* WS (or LRCK) */
	config.mem_slab = cfg->mem_slab;
	config.block_size = cfg->tx_buf_bytes;
	config.timeout = 1000;

	ret = i2s_configure(cfg->dev, I2S_DIR_TX, &config);
	if (ret < 0) {
		LOG_ERR("Failed to configure I2S device: %d\n", ret);
		return ret;
	}

	for (uint16_t i = 0; i < cfg->num_colors; i++) {
		switch (cfg->color_mapping[i]) {
		case LED_COLOR_ID_WHITE:
		case LED_COLOR_ID_RED:
		case LED_COLOR_ID_GREEN:
		case LED_COLOR_ID_BLUE:
			break;
		default:
			LOG_ERR("%s: invalid channel to color mapping."
				"Check the color-mapping DT property",
				dev->name);
			return -EINVAL;
		}
	}

	return 0;
}

static const struct led_strip_driver_api ws2812_i2s_api = {
	.update_rgb = ws2812_strip_update_rgb,
	.update_channels = ws2812_strip_update_channels,
};

/* Integer division, but always rounds up: e.g. 10/3 = 4 */
#define WS2812_ROUNDED_DIVISION(x, y) ((x + (y - 1)) / y)

#define WS2812_I2S_LRCK_PERIOD_US(idx) DT_INST_PROP(idx, lrck_period)

#define WS2812_RESET_DELAY_US(idx)    DT_INST_PROP(idx, reset_delay)
/* Rounds up to the next 20us. */
#define WS2812_RESET_DELAY_WORDS(idx) WS2812_ROUNDED_DIVISION(WS2812_RESET_DELAY_US(idx), \
							      WS2812_I2S_LRCK_PERIOD_US(idx))

#define WS2812_NUM_COLORS(idx) (DT_INST_PROP_LEN(idx, color_mapping))

#define WS2812_I2S_NUM_PIXELS(idx) (DT_INST_PROP(idx, chain_length))

#define WS2812_I2S_BUFSIZE(idx)                                                                    \
	(((WS2812_NUM_COLORS(idx) * WS2812_I2S_NUM_PIXELS(idx)) +	                           \
	  WS2812_I2S_PRE_DELAY_WORDS + WS2812_RESET_DELAY_WORDS(idx)) * 4)

#define WS2812_I2S_DEVICE(idx)                                                                     \
                                                                                                   \
	K_MEM_SLAB_DEFINE_STATIC(ws2812_i2s_##idx##_slab, WS2812_I2S_BUFSIZE(idx), 2, 4);          \
                                                                                                   \
	static const uint8_t ws2812_i2s_##idx##_color_mapping[] =                                  \
		DT_INST_PROP(idx, color_mapping);                                                  \
                                                                                                   \
	static const struct ws2812_i2s_cfg ws2812_i2s_##idx##_cfg = {                              \
		.dev = DEVICE_DT_GET(DT_INST_PROP(idx, i2s_dev)),                                  \
		.tx_buf_bytes = WS2812_I2S_BUFSIZE(idx),                                           \
		.mem_slab = &ws2812_i2s_##idx##_slab,                                              \
		.num_colors = WS2812_NUM_COLORS(idx),                                              \
		.color_mapping = ws2812_i2s_##idx##_color_mapping,                                 \
		.lrck_period = WS2812_I2S_LRCK_PERIOD_US(idx),                                     \
		.extra_wait_time_us = DT_INST_PROP(idx, extra_wait_time),                          \
		.reset_words = WS2812_RESET_DELAY_WORDS(idx),                                      \
		.active_low = DT_INST_PROP(idx, out_active_low),                                   \
		.nibble_one = DT_INST_PROP(idx, nibble_one),                                       \
		.nibble_zero = DT_INST_PROP(idx, nibble_zero),                                     \
	};                                                                                         \
                                                                                                   \
	DEVICE_DT_INST_DEFINE(idx, ws2812_i2s_init, NULL, NULL, &ws2812_i2s_##idx##_cfg,           \
			      POST_KERNEL, CONFIG_LED_STRIP_INIT_PRIORITY, &ws2812_i2s_api);

DT_INST_FOREACH_STATUS_OKAY(WS2812_I2S_DEVICE)