max30001.c 9.89 KB
Newer Older
schneider's avatar
schneider committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <stdio.h>
#include <string.h>

#include "gpio.h"
#include "pmic.h"
#include "spi.h"

#include "MAX30003.h"

#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"

#include "epicardium.h"
#include "modules/log.h"
#include "modules/modules.h"
#include "modules/stream.h"
18
#include "modules/mutex.h"
schneider's avatar
schneider committed
19 20 21 22 23 24 25 26 27 28 29 30

/* Interrupt Pin */
static const gpio_cfg_t max30001_interrupt_pin = {
	PORT_1, PIN_12, GPIO_FUNC_IN, GPIO_PAD_PULL_UP
};

static const gpio_cfg_t analog_switch = {
	PORT_0, PIN_31, GPIO_FUNC_OUT, GPIO_PAD_NONE
};

/* clang-format on */

31
/* MAX30001 Task ID */
schneider's avatar
schneider committed
32 33
static TaskHandle_t max30001_task_id = NULL;

34
/* MAX30001 Mutex */
35
static struct mutex max30001_mutex = { 0 };
schneider's avatar
schneider committed
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51

/* Stream */
static struct stream_info max30001_stream;
;

/* Active */
static bool max30001_sensor_active = false;

static int ecg_enable(int sample_rate, bool enable_internal_pull);
static int ecg_disable(void);

/* -- API -------------------------------------------------------------- {{{ */
int epic_max30001_enable_sensor(struct max30001_sensor_config *config)
{
	int result = 0;

52 53
	mutex_lock(&max30001_mutex);
	hwlock_acquire(HWLOCK_SPI_ECG);
schneider's avatar
schneider committed
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

	struct stream_info *stream = &max30001_stream;
	;
	stream->item_size = sizeof(uint16_t);
	stream->queue =
		xQueueCreate(config->sample_buffer_len, stream->item_size);
	if (stream->queue == NULL) {
		result = -ENOMEM;
		goto out_free_both;
	}

	result = stream_register(SD_MAX30001_ECG, stream);
	if (result < 0) {
		vQueueDelete(stream->queue);
		goto out_free_both;
	}

	result = ecg_enable(config->sample_rate, config->bias);

	if (result < 0) {
		vQueueDelete(stream->queue);
		goto out_free_both;
	}

	if (config->usb) {
		GPIO_OutSet(&analog_switch); // USB
	} else {
		GPIO_OutClr(&analog_switch); // Wrist
	}

	max30001_sensor_active = true;
	result                 = SD_MAX30001_ECG;

out_free_both:
	hwlock_release(HWLOCK_SPI_ECG);
89
	mutex_unlock(&max30001_mutex);
schneider's avatar
schneider committed
90 91 92 93 94 95 96
	return result;
}

int epic_max30001_disable_sensor(void)
{
	int result = 0;

97 98
	mutex_lock(&max30001_mutex);
	hwlock_acquire(HWLOCK_SPI_ECG);
schneider's avatar
schneider committed
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117

	struct stream_info *stream = &max30001_stream;
	result                     = stream_deregister(SD_MAX30001_ECG, stream);
	if (result < 0) {
		goto out_free_both;
	}

	vQueueDelete(stream->queue);
	stream->queue = NULL;
	result        = ecg_disable();
	if (result < 0) {
		goto out_free_both;
	}

	max30001_sensor_active = false;

	result = 0;
out_free_both:
	hwlock_release(HWLOCK_SPI_ECG);
118
	mutex_unlock(&max30001_mutex);
schneider's avatar
schneider committed
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
	return result;
}

/* }}} */

/* -- Driver ----------------------------------------------------------- {{{ */
/*
 * Handle a single packet from the FIFO.  For most sensors this means pushing
 * the sample into its sample queue.
 */
static void max30001_handle_samples(int16_t *sensor_data, int16_t n)
{
	if (max30001_stream.queue == NULL) {
		return;
	}

	while (n--) {
136
		uint16_t data = -*sensor_data++;
137 138 139

		/* Discard overflow.  See discussion in !316. */
		if (xQueueSend(max30001_stream.queue, &data, 0) != pdTRUE) {
140 141 142 143 144 145
			if (!max30001_stream.was_full) {
				LOG_WARN("max30001", "queue full");
			}
			max30001_stream.was_full = true;
		} else {
			max30001_stream.was_full = false;
schneider's avatar
schneider committed
146 147
		}
	}
148
	interrupt_trigger(EPIC_INT_MAX30001_ECG);
schneider's avatar
schneider committed
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 276 277 278 279 280 281 282 283 284
}

/***** Functions *****/
static uint32_t ecg_read_reg(uint8_t reg)
{
	spi_req_t req;
	uint8_t tx_data[] = { (reg << 1) | 1, 0, 0, 0 };
	uint8_t rx_data[] = { 0, 0, 0, 0 };
	req.tx_data       = tx_data;
	req.rx_data       = rx_data;
	req.len           = 4;
	req.bits          = 8;
	req.width         = SPI17Y_WIDTH_1;
	req.ssel          = 0;
	req.deass         = 1;
	req.ssel_pol      = SPI17Y_POL_LOW;
	req.tx_num        = 0;
	req.rx_num        = 0;

	SPI_MasterTrans(SPI0, &req);

	return (rx_data[1] << 16) | (rx_data[2] << 8) | rx_data[3];
}

static void ecg_write_reg(uint8_t reg, uint32_t data)
{
	//printf("write %02x %06lx\n", reg, data);
	spi_req_t req;
	uint8_t tx_data[] = {
		(reg << 1) | 0, data >> 16, (data >> 8) & 0xFF, data & 0xFF
	};
	uint8_t rx_data[] = { 0, 0, 0, 0 };
	req.tx_data       = tx_data;
	req.rx_data       = rx_data;
	req.len           = 4;
	req.bits          = 8;
	req.width         = SPI17Y_WIDTH_1;
	req.ssel          = 0;
	req.deass         = 1;
	req.ssel_pol      = SPI17Y_POL_LOW;
	req.tx_num        = 0;
	req.rx_num        = 0;

	SPI_MasterTrans(SPI0, &req);
}

static int ecg_enable(int sample_rate, bool enable_internal_pull)
{
	// Reset ECG to clear registers
	ecg_write_reg(SW_RST, 0);

	// General config register setting
	union GeneralConfiguration_u CNFG_GEN_r;
	CNFG_GEN_r.bits.en_ecg = 1; // Enable ECG channel
	if (enable_internal_pull) {
		CNFG_GEN_r.bits.rbiasn =
			1; // Enable resistive bias on negative input
		CNFG_GEN_r.bits.rbiasp =
			1; // Enable resistive bias on positive input
		CNFG_GEN_r.bits.en_rbias = 1; // Enable resistive bias
	} else {
		CNFG_GEN_r.bits.rbiasn =
			0; // Enable resistive bias on negative input
		CNFG_GEN_r.bits.rbiasp =
			0; // Enable resistive bias on positive input
		CNFG_GEN_r.bits.en_rbias = 0; // Enable resistive bias
	}

	CNFG_GEN_r.bits.imag      = 2; // Current magnitude = 10nA
	CNFG_GEN_r.bits.en_dcloff = 1; // Enable DC lead-off detection
	ecg_write_reg(CNFG_GEN, CNFG_GEN_r.all);

	// ECG Config register setting
	union ECGConfiguration_u CNFG_ECG_r;
	CNFG_ECG_r.bits.dlpf = 1; // Digital LPF cutoff = 40Hz
	CNFG_ECG_r.bits.dhpf = 1; // Digital HPF cutoff = 0.5Hz
	//CNFG_ECG_r.bits.gain = 3;       // ECG gain = 160V/V
	CNFG_ECG_r.bits.gain = 0;
	if (sample_rate == 128) {
		CNFG_ECG_r.bits.rate = 2; // Sample rate = 128 sps
	} else if (sample_rate == 256) {
		CNFG_ECG_r.bits.rate = 1; // Sample rate = 256 sps
	} else {
		return -EINVAL;
	}

	ecg_write_reg(CNFG_ECG, CNFG_ECG_r.all);

	//R-to-R configuration
	union RtoR1Configuration_u CNFG_RTOR_r;
	CNFG_RTOR_r.bits.en_rtor = 1; // Enable R-to-R detection
	ecg_write_reg(CNFG_RTOR1, CNFG_RTOR_r.all);

	//Manage interrupts register setting
	union ManageInterrupts_u MNG_INT_r;
	MNG_INT_r.bits.efit      = 0b00011; // Assert EINT w/ 4 unread samples
	MNG_INT_r.bits.clr_rrint = 0b01; // Clear R-to-R on RTOR reg. read back
	ecg_write_reg(MNGR_INT, MNG_INT_r.all);

	//Enable interrupts register setting
	union EnableInterrupts_u EN_INT_r;
	EN_INT_r.all            = 0;
	EN_INT_r.bits.en_eint   = 1; // Enable EINT interrupt
	EN_INT_r.bits.en_rrint  = 0; // Disable R-to-R interrupt
	EN_INT_r.bits.intb_type = 3; // Open-drain NMOS with internal pullup
	ecg_write_reg(EN_INT, EN_INT_r.all);

	//Dyanmic modes config
	union ManageDynamicModes_u MNG_DYN_r;
	MNG_DYN_r.bits.fast = 0; // Fast recovery mode disabled
	ecg_write_reg(MNGR_DYN, MNG_DYN_r.all);

	// MUX Config
	union MuxConfiguration_u CNFG_MUX_r;
	CNFG_MUX_r.bits.openn = 0; // Connect ECGN to AFE channel
	CNFG_MUX_r.bits.openp = 0; // Connect ECGP to AFE channel
	ecg_write_reg(CNFG_EMUX, CNFG_MUX_r.all);

	ecg_write_reg(SYNCH, 0);

	return 0;
}

static int ecg_disable(void)
{
	// TODO
	return 0;
}
/*
 * Fetch all data available from FIFO buffer and handle all data
 * contained in it.
 */
static int max30001_fetch_fifo(void)
{
	int result = 0;

285 286
	mutex_lock(&max30001_mutex);
	hwlock_acquire(HWLOCK_SPI_ECG);
schneider's avatar
schneider committed
287 288 289

	uint32_t ecgFIFO, readECGSamples, ETAG[32], status;
	int16_t ecgSample[32];
290 291 292 293 294
	const uint32_t EINT_STATUS_MASK       = 1 << 23;
	const uint32_t FIFO_OVF_MASK          = 0x7;
	const uint32_t FIFO_VALID_SAMPLE_MASK = 0x0;
	const uint32_t FIFO_FAST_SAMPLE_MASK  = 0x1;
	const uint32_t ETAG_BITS_MASK         = 0x7;
schneider's avatar
schneider committed
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315

	status = ecg_read_reg(STATUS); // Read the STATUS register

	// Check if EINT interrupt asserted
	if ((status & EINT_STATUS_MASK) == EINT_STATUS_MASK) {
		readECGSamples = 0; // Reset sample counter

		do {
			ecgFIFO = ecg_read_reg(ECG_FIFO); // Read FIFO
			ecgSample[readECGSamples] =
				ecgFIFO >> 8; // Isolate voltage data
			ETAG[readECGSamples] =
				(ecgFIFO >> 3) & ETAG_BITS_MASK; // Isolate ETAG
			readECGSamples++; // Increment sample counter

			// Check that sample is not last sample in FIFO
		} while (ETAG[readECGSamples - 1] == FIFO_VALID_SAMPLE_MASK ||
			 ETAG[readECGSamples - 1] == FIFO_FAST_SAMPLE_MASK);

		// Check if FIFO has overflowed
		if (ETAG[readECGSamples - 1] == FIFO_OVF_MASK) {
316 317 318 319
			ecg_write_reg(FIFO_RST, 0); // Reset FIFO
			LOG_WARN(
				"max30001",
				"fifo overflow"); // TODO; handle fifo full
schneider's avatar
schneider committed
320 321 322 323 324
		}
		max30001_handle_samples(ecgSample, readECGSamples);
	}

	hwlock_release(HWLOCK_SPI_ECG);
325
	mutex_unlock(&max30001_mutex);
schneider's avatar
schneider committed
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
	return result;
}

/*
 * Callback for the MAX30001 interrupt pin.  This callback is called from the
 * SDK's GPIO interrupt driver, in interrupt context.
 */
static void max300001_interrupt_callback(void *_)
{
	BaseType_t xHigherPriorityTaskWoken = pdFALSE;

	if (max30001_task_id != NULL) {
		vTaskNotifyGiveFromISR(
			max30001_task_id, &xHigherPriorityTaskWoken
		);
		portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
	}
}
/* }}} */

346 347
void max30001_mutex_init(void)
{
348
	mutex_create(&max30001_mutex);
349 350
}

schneider's avatar
schneider committed
351 352 353 354
void vMAX30001Task(void *pvParameters)
{
	max30001_task_id = xTaskGetCurrentTaskHandle();

355 356
	mutex_lock(&max30001_mutex);
	hwlock_acquire(HWLOCK_SPI_ECG);
schneider's avatar
schneider committed
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377

	/* Install interrupt callback */
	GPIO_Config(&max30001_interrupt_pin);
	GPIO_RegisterCallback(
		&max30001_interrupt_pin, max300001_interrupt_callback, NULL
	);
	GPIO_IntConfig(
		&max30001_interrupt_pin, GPIO_INT_EDGE, GPIO_INT_FALLING
	);
	GPIO_IntEnable(&max30001_interrupt_pin);
	NVIC_SetPriority(
		(IRQn_Type)MXC_GPIO_GET_IRQ(max30001_interrupt_pin.port), 2
	);
	NVIC_EnableIRQ(
		(IRQn_Type)MXC_GPIO_GET_IRQ(max30001_interrupt_pin.port)
	);

	GPIO_Config(&analog_switch);
	GPIO_OutClr(&analog_switch); // Wrist

	hwlock_release(HWLOCK_SPI_ECG);
378
	mutex_unlock(&max30001_mutex);
schneider's avatar
schneider committed
379 380 381 382 383 384

	/* ----------------------------------------- */

	while (1) {
		if (max30001_sensor_active) {
			int ret = max30001_fetch_fifo();
385
			if (ret < 0) {
schneider's avatar
schneider committed
386 387 388 389 390 391 392 393 394 395 396 397
				LOG_ERR("max30001", "Unknown error: %d", -ret);
			}
		}
		/*
		 * Wait for interrupt.  After two seconds, fetch FIFO anyway
		 *
		 * In the future, reads using epic_stream_read() might also
		 * trigger a FIFO fetch, from outside this task.
		 */
		ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(2000));
	}
}