/*  
		C Program to run a pulse density modulation (PDM) Microphone on the nRF9160 Dev Kit using the Nordic SDK
*/

#include <nrf9160.h>
#include <zephyr.h>
#include <misc/printk.h>
#include <string.h>
#include <stdlib.h>
#include <nrfx_pdm_ns.h>




#include <gpio.h>

#undef NRFX_PDM_ENABLED
#define NRFX_PDM_ENABLED

#define PDM_BUF_ADDRESS 0x20000000 // buffer address in RAM
#define PDM_BUF_SIZE 256 //size in 32 bit words --> 40 bytes

int16_t pdm_buf[PDM_BUF_SIZE];


void nrfx_pdm_event_handler(nrfx_pdm_evt_t const *const p_evt)
{
	if (p_evt->buffer_requested) {
		nrfx_pdm_buffer_set(pdm_buf, PDM_BUF_SIZE);
	}
	if (p_evt->buffer_released != 0) {
		printk("Out: %.2x %2x\r\n", (uint16_t)pdm_buf[0],
		       (uint16_t)pdm_buf[1]);
	}
}

static void pdm_init(void)
{
	nrfx_pdm_config_t pdm_config = NRFX_PDM_DEFAULT_CONFIG(10, 11); /*configures CLK to pin 10 and Din to pin 11*/
	nrfx_pdm_init(&pdm_config, nrfx_pdm_event_handler);
}

void main(void)
{
	printk("Starting PDM program!\n");
	printk("PDM Buffer size: %d\n", (PDM_BUF_SIZE * 4));
	printk("PDM Starting Address: %x\n", PDM_BUF_ADDRESS);

	pdm_init();
}